<commit_before>/*
** Copyright 2011-2012,2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <memory>
#include <QCoreApplication>
#include <QMutex>
#include <QMutexLocker>
#include "com/centreon/broker/config/applier/endpoint.hh"
#include "com/centreon/broker/config/applier/logger.hh"
#include "com/centreon/broker/config/applier/modules.hh"
#include "com/centreon/broker/config/applier/state.hh"
#include "com/centreon/broker/config/applier/temporary.hh"
#include "com/centreon/broker/logging/file.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"

using namespace com::centreon::broker::config::applier;

// Class instance.
static state* gl_state = NULL;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Destructor.
 */
state::~state() {}

/**
 *  Apply a configuration state.
 *
 *  @param[in] s       State to apply.
 *  @param[in] run_mux Set to true if multiplexing must be run.
 */
void state::apply(
              com::centreon::broker::config::state const& s,
              bool run_mux) {
  // Apply logging configuration.
  logger::instance().apply(s.loggers());

  // Flush logs or not.
  com::centreon::broker::logging::file::with_flush(
    s.flush_logs());

  // Enable or not thread ID logging.
  com::centreon::broker::logging::file::with_thread_id(
    s.log_thread_id());

  // Enable or not timestamp logging.
  com::centreon::broker::logging::file::with_timestamp(
    s.log_timestamp());

  // Enable or not human readable timstamp logging.
  com::centreon::broker::logging::file::with_human_redable_timestamp(
    s.log_human_readable_timestamp());

  // Apply modules configuration.
  modules::instance().apply(
                        s.module_list(),
                        s.module_directory(),
                        &s);
  static bool first_application(true);
  if (first_application)
    first_application = false;
  else {
    unsigned int module_count(0);
    for (modules::iterator
           it(modules::instance().begin()),
           end(modules::instance().end());
         it != end;
         ++it)
      ++module_count;
    if (module_count)
      logging::config(logging::high) << "applier: " << module_count
        << " modules loaded";
    else
      logging::config(logging::high) << "applier: no module loaded, "
        "you might want to check the 'module_directory' directive";
  }

  com::centreon::broker::multiplexing::subscriber::event_queue_max_size(s.event_queue_max_size());

  // Apply temporary configuration.
  temporary::instance().apply(s.temporary());

  // Create command file input.
  {
    config::endpoint ept;
    ept.name = s.command_file();
    ept.type = "command_file";
    const_cast<com::centreon::broker::config::state&>(s)
      .inputs().push_back(ept);
  }

  // Apply input and output configuration.
  endpoint::instance().apply(
                         s.inputs(),
                         s.outputs(),
                         s.cache_directory());

  // Enable multiplexing loop.
  if (run_mux)
    com::centreon::broker::multiplexing::engine::instance().start();

  return ;
}

/**
 *  Get the instance of this object.
 *
 *  @return Class instance.
 */
state& state::instance() {
  return (*gl_state);
}

/**
 *  Load singleton.
 */
void state::load() {
  if (!gl_state)
    gl_state = new state;
  return ;
}

/**
 *  Unload singleton.
 */
void state::unload() {
  delete gl_state;
  gl_state = NULL;
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
state::state() {}
<commit_msg>Core: Do not create command file if empty name.<commit_after>/*
** Copyright 2011-2012,2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <memory>
#include <QCoreApplication>
#include <QMutex>
#include <QMutexLocker>
#include "com/centreon/broker/config/applier/endpoint.hh"
#include "com/centreon/broker/config/applier/logger.hh"
#include "com/centreon/broker/config/applier/modules.hh"
#include "com/centreon/broker/config/applier/state.hh"
#include "com/centreon/broker/config/applier/temporary.hh"
#include "com/centreon/broker/logging/file.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"

using namespace com::centreon::broker::config::applier;

// Class instance.
static state* gl_state = NULL;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Destructor.
 */
state::~state() {}

/**
 *  Apply a configuration state.
 *
 *  @param[in] s       State to apply.
 *  @param[in] run_mux Set to true if multiplexing must be run.
 */
void state::apply(
              com::centreon::broker::config::state const& s,
              bool run_mux) {
  // Apply logging configuration.
  logger::instance().apply(s.loggers());

  // Flush logs or not.
  com::centreon::broker::logging::file::with_flush(
    s.flush_logs());

  // Enable or not thread ID logging.
  com::centreon::broker::logging::file::with_thread_id(
    s.log_thread_id());

  // Enable or not timestamp logging.
  com::centreon::broker::logging::file::with_timestamp(
    s.log_timestamp());

  // Enable or not human readable timstamp logging.
  com::centreon::broker::logging::file::with_human_redable_timestamp(
    s.log_human_readable_timestamp());

  // Apply modules configuration.
  modules::instance().apply(
                        s.module_list(),
                        s.module_directory(),
                        &s);
  static bool first_application(true);
  if (first_application)
    first_application = false;
  else {
    unsigned int module_count(0);
    for (modules::iterator
           it(modules::instance().begin()),
           end(modules::instance().end());
         it != end;
         ++it)
      ++module_count;
    if (module_count)
      logging::config(logging::high) << "applier: " << module_count
        << " modules loaded";
    else
      logging::config(logging::high) << "applier: no module loaded, "
        "you might want to check the 'module_directory' directive";
  }

  com::centreon::broker::multiplexing::subscriber::event_queue_max_size(s.event_queue_max_size());

  // Apply temporary configuration.
  temporary::instance().apply(s.temporary());

  // Create command file input.
  if (!s.command_file().isEmpty()) {
    config::endpoint ept;
    ept.name = s.command_file();
    ept.type = "command_file";
    const_cast<com::centreon::broker::config::state&>(s)
      .inputs().push_back(ept);
  }

  // Apply input and output configuration.
  endpoint::instance().apply(
                         s.inputs(),
                         s.outputs(),
                         s.cache_directory());

  // Enable multiplexing loop.
  if (run_mux)
    com::centreon::broker::multiplexing::engine::instance().start();

  return ;
}

/**
 *  Get the instance of this object.
 *
 *  @return Class instance.
 */
state& state::instance() {
  return (*gl_state);
}

/**
 *  Load singleton.
 */
void state::load() {
  if (!gl_state)
    gl_state = new state;
  return ;
}

/**
 *  Unload singleton.
 */
void state::unload() {
  delete gl_state;
  gl_state = NULL;
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
state::state() {}
<|endoftext|>


<commit_before>// thrax_g2p.cc
//
// 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.
//
// Copyright 2016 Google, Inc.
// Author: mjansche@google.com (Martin Jansche)
//
// \file
// Grapheme-to-phoneme processing with weighted grammars (typically Thrax).

#include <iostream>
#include <memory>
#include <string>
#include <vector>

#include <fst/arc.h>
#include <fst/compact-fst.h>
#include <fst/compat.h>
#include <fst/compose.h>
#include <fst/project.h>
#include <fst/properties.h>
#include <fst/prune.h>
#include <fst/rmepsilon.h>
#include <fst/string.h>
#include <fst/symbol-table.h>
#include <fst/util.h>
#include <fst/vector-fst.h>
#include <thrax/grm-manager.h>

#include "festus/fst-util.h"
#include "festus/label-maker.h"
#include "festus/string-util.h"

using fst::StdVectorFst;
using fst::SymbolTable;
using std::string;

DEFINE_string(fst, "", "Path to G2P FST.");
DEFINE_string(far, "", "Path to FAR file containing G2P FST.");
DEFINE_string(far_g2p_key, "G2P", "Name of G2P FST within the FAR file.");
DEFINE_string(phoneme_syms, "", "Path to phoneme symbols.");

int main(int argc, char *argv[]) {
  SET_FLAGS(argv[0], &argc, &argv, true);

  std::unique_ptr<StdVectorFst> fst;
  if (!FLAGS_fst.empty()) {
    if (!FLAGS_far.empty()) {
      LOG(WARNING) << "Both --fst and --far were specified; ignoring --far";
    }
    fst.reset(StdVectorFst::Read(FLAGS_fst));
    if (!fst) return 1;
  } else if (!FLAGS_far.empty()) {
    thrax::GrmManager grm_manager;
    if (!grm_manager.LoadArchive(FLAGS_far)) {
      LOG(ERROR) << "Could not load FAR from " << FLAGS_far;
      return 1;
    }
    const auto *g2p = grm_manager.GetFst(FLAGS_far_g2p_key);
    if (!g2p) {
      LOG(ERROR) << "Could not find G2P FST with key " << FLAGS_far_g2p_key
                 << " inside FAR " << FLAGS_far;
      return 1;
    }
    fst.reset(new StdVectorFst());
    *fst = *g2p;
  } else {
    LOG(ERROR) << "Neither --fst nor --far was specified";
    return 1;
  }

  if (FLAGS_phoneme_syms.empty()) {
    LOG(ERROR) << "--phoneme_syms not specified";
    return 1;
  }
  std::unique_ptr<SymbolTable> phoneme_syms(
      SymbolTable::ReadText(FLAGS_phoneme_syms));
  if (!phoneme_syms) return 1;

  festus::UnicodeLabelMaker input_label_maker;
  festus::SymbolLabelMaker output_label_maker(phoneme_syms.get(), " ");
  StdVectorFst lattice;
  for (string line; std::getline(std::cin, line); ) {
    std::cout << line << "\t";
    bool at_start = true;
    for (const auto phrase : festus::Split(line, " ")) {
      if (at_start) {
        at_start = false;
      } else {
        std::cout << " # ";
      }
      fst::StdCompactStringFst graphemes;
      if (!input_label_maker.StringToCompactFst(phrase, &graphemes)) {
        std::cout << "ERROR_compiling_input: " << phrase;
        continue;
      }
      fst::Compose(graphemes, *fst, &lattice);
      if (fst::kNoStateId == lattice.Start()) {
        std::cout << "ERROR_empty_composition: " << phrase;
        continue;
      }
      fst::Project(&lattice, fst::PROJECT_OUTPUT);
      if (lattice.Properties(fst::kString, true)) {
        VLOG(1) << "Lattice is a string after composition, no pruning required";
      } else {
        fst::Prune(&lattice, 0.1);
        if (!lattice.Properties(fst::kString, true)) {
          std::cout << "ERROR_ambiguous_output: " << phrase;
          continue;
        }
      }
      fst::RmEpsilon(&lattice);
      std::cout << festus::OneString(lattice, output_label_maker);
    }
    std::cout << std::endl;
  }

  return 0;
}
<commit_msg>Change minor/internal boundary symbol to IPA pipe.<commit_after>// thrax_g2p.cc
//
// 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.
//
// Copyright 2016 Google, Inc.
// Author: mjansche@google.com (Martin Jansche)
//
// \file
// Grapheme-to-phoneme processing with weighted grammars (typically Thrax).

#include <iostream>
#include <memory>
#include <string>
#include <vector>

#include <fst/arc.h>
#include <fst/compact-fst.h>
#include <fst/compat.h>
#include <fst/compose.h>
#include <fst/project.h>
#include <fst/properties.h>
#include <fst/prune.h>
#include <fst/rmepsilon.h>
#include <fst/string.h>
#include <fst/symbol-table.h>
#include <fst/util.h>
#include <fst/vector-fst.h>
#include <thrax/grm-manager.h>

#include "festus/fst-util.h"
#include "festus/label-maker.h"
#include "festus/string-util.h"

using fst::StdVectorFst;
using fst::SymbolTable;
using std::string;

DEFINE_string(fst, "", "Path to G2P FST.");
DEFINE_string(far, "", "Path to FAR file containing G2P FST.");
DEFINE_string(far_g2p_key, "G2P", "Name of G2P FST within the FAR file.");
DEFINE_string(phoneme_syms, "", "Path to phoneme symbols.");

int main(int argc, char *argv[]) {
  SET_FLAGS(argv[0], &argc, &argv, true);

  std::unique_ptr<StdVectorFst> fst;
  if (!FLAGS_fst.empty()) {
    if (!FLAGS_far.empty()) {
      LOG(WARNING) << "Both --fst and --far were specified; ignoring --far";
    }
    fst.reset(StdVectorFst::Read(FLAGS_fst));
    if (!fst) return 1;
  } else if (!FLAGS_far.empty()) {
    thrax::GrmManager grm_manager;
    if (!grm_manager.LoadArchive(FLAGS_far)) {
      LOG(ERROR) << "Could not load FAR from " << FLAGS_far;
      return 1;
    }
    const auto *g2p = grm_manager.GetFst(FLAGS_far_g2p_key);
    if (!g2p) {
      LOG(ERROR) << "Could not find G2P FST with key " << FLAGS_far_g2p_key
                 << " inside FAR " << FLAGS_far;
      return 1;
    }
    fst.reset(new StdVectorFst());
    *fst = *g2p;
  } else {
    LOG(ERROR) << "Neither --fst nor --far was specified";
    return 1;
  }

  if (FLAGS_phoneme_syms.empty()) {
    LOG(ERROR) << "--phoneme_syms not specified";
    return 1;
  }
  std::unique_ptr<SymbolTable> phoneme_syms(
      SymbolTable::ReadText(FLAGS_phoneme_syms));
  if (!phoneme_syms) return 1;

  festus::UnicodeLabelMaker input_label_maker;
  festus::SymbolLabelMaker output_label_maker(phoneme_syms.get(), " ");
  StdVectorFst lattice;
  for (string line; std::getline(std::cin, line); ) {
    std::cout << line << "\t";
    bool at_start = true;
    for (const auto phrase : festus::Split(line, " ")) {
      if (at_start) {
        at_start = false;
      } else {
        std::cout << " | ";
      }
      fst::StdCompactStringFst graphemes;
      if (!input_label_maker.StringToCompactFst(phrase, &graphemes)) {
        std::cout << "ERROR_compiling_input: " << phrase;
        continue;
      }
      fst::Compose(graphemes, *fst, &lattice);
      if (fst::kNoStateId == lattice.Start()) {
        std::cout << "ERROR_empty_composition: " << phrase;
        continue;
      }
      fst::Project(&lattice, fst::PROJECT_OUTPUT);
      if (lattice.Properties(fst::kString, true)) {
        VLOG(1) << "Lattice is a string after composition, no pruning required";
      } else {
        fst::Prune(&lattice, 0.1);
        if (!lattice.Properties(fst::kString, true)) {
          std::cout << "ERROR_ambiguous_output: " << phrase;
          continue;
        }
      }
      fst::RmEpsilon(&lattice);
      std::cout << festus::OneString(lattice, output_label_maker);
    }
    std::cout << std::endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3277
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3277 to 3278<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3278
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3328
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3328 to 3329<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3329
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3134
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3134 to 3135<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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 VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3135
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __MODPROPERTY_H
#define __MODPROPERTY_H

#include "../mozartcore.hh"

#ifndef MOZART_GENERATOR

namespace mozart {

namespace builtins {

//////////////////////
// Property module //
//////////////////////

class ModProperty: public Module {
public:
  ModProperty(): Module("Property") {}

  class Get: public Builtin<Get> {
  public:
    Get(): Builtin("get") {}

    static void call(VM vm, In property, Out result, Out found) {
      if (vm->getPropertyRegistry().get(vm, property, result)) {
        found = build(vm, true);
      } else {
        result = build(vm, unit);
        found = build(vm, false);
      }
    }
  };

  class Put: public Builtin<Put> {
  public:
    Put(): Builtin("put") {}

    static void call(VM vm, In property, In value, Out found) {
      found = build(vm, vm->getPropertyRegistry().put(vm, property, value));
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODPROPERTY_H
<commit_msg>Added builtins to register new system properties from Oz.<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __MODPROPERTY_H
#define __MODPROPERTY_H

#include "../mozartcore.hh"

#ifndef MOZART_GENERATOR

namespace mozart {

namespace builtins {

/////////////////////
// Property module //
/////////////////////

class ModProperty: public Module {
public:
  ModProperty(): Module("Property") {}

  class RegisterValue: public Builtin<RegisterValue> {
  public:
    RegisterValue(): Builtin("registerValue") {}

    static void call(VM vm, In property, In value) {
      auto propertyAtom = getArgument<atom_t>(vm, property);
      vm->getPropertyRegistry().registerValueProp(
        vm, propertyAtom.contents(), value);
    }
  };

  class RegisterConstant: public Builtin<RegisterConstant> {
  public:
    RegisterConstant(): Builtin("registerConstant") {}

    static void call(VM vm, In property, In value) {
      auto propertyAtom = getArgument<atom_t>(vm, property);
      vm->getPropertyRegistry().registerConstantProp(
        vm, propertyAtom.contents(), value);
    }
  };

  class Get: public Builtin<Get> {
  public:
    Get(): Builtin("get") {}

    static void call(VM vm, In property, Out result, Out found) {
      if (vm->getPropertyRegistry().get(vm, property, result)) {
        found = build(vm, true);
      } else {
        result = build(vm, unit);
        found = build(vm, false);
      }
    }
  };

  class Put: public Builtin<Put> {
  public:
    Put(): Builtin("put") {}

    static void call(VM vm, In property, In value, Out found) {
      found = build(vm, vm->getPropertyRegistry().put(vm, property, value));
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODPROPERTY_H
<|endoftext|>


<commit_before>/* Copyright 2015 Google Inc. 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.
==============================================================================*/

// See docs in ../ops/array_ops.cc.

#define EIGEN_USE_THREADS

#include <limits>

#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/edit_distance.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"

namespace tensorflow {

namespace {

Status ValidateShapes(OpKernelContext* ctx, const Tensor& hypothesis_indices,
                      const Tensor& hypothesis_values,
                      const Tensor& hypothesis_shape,
                      const Tensor& truth_indices, const Tensor& truth_values,
                      const Tensor& truth_shape) {
  if (!TensorShapeUtils::IsMatrix(hypothesis_indices.shape()))
    return errors::InvalidArgument(
        "hypothesis_indices should be a matrix, but got shape: ",
        hypothesis_indices.shape().DebugString());
  if (!TensorShapeUtils::IsMatrix(truth_indices.shape()))
    return errors::InvalidArgument(
        "truth_indices should be a matrix, but got shape: ",
        truth_indices.shape().DebugString());
  if (!TensorShapeUtils::IsVector(hypothesis_values.shape()))
    return errors::InvalidArgument(
        "hypothesis_values should be a vector, but got shape: ",
        hypothesis_values.shape().DebugString());
  if (!TensorShapeUtils::IsVector(truth_values.shape()))
    return errors::InvalidArgument(
        "truth_values should be a vector, but got shape: ",
        truth_values.shape().DebugString());
  if (!TensorShapeUtils::IsVector(hypothesis_shape.shape()))
    return errors::InvalidArgument(
        "hypothesis_shape should be a vector, but got shape: ",
        hypothesis_shape.shape().DebugString());
  if (!TensorShapeUtils::IsVector(truth_shape.shape()))
    return errors::InvalidArgument(
        "truth_shape should be a vector, but got shape: ",
        truth_shape.shape().DebugString());
  if (hypothesis_shape.NumElements() != hypothesis_indices.dim_size(1))
    return errors::InvalidArgument(
        "Expected hypothesis_shape.NumElements == "
        "#cols(hypothesis_indices), their shapes are: ",
        hypothesis_shape.shape().DebugString(), " and ",
        hypothesis_indices.shape().DebugString());
  if (truth_shape.NumElements() < 2)
    return errors::InvalidArgument(
        "Input SparseTensors must have rank at least 2, but truth_shape "
        "rank is: ",
        truth_shape.NumElements());
  if (truth_shape.NumElements() != truth_indices.dim_size(1))
    return errors::InvalidArgument(
        "Expected truth_shape.NumElements == "
        "#cols(truth_indices), their shapes are: ",
        truth_shape.shape().DebugString(), " and ",
        truth_indices.shape().DebugString());
  if (truth_shape.NumElements() != hypothesis_shape.NumElements())
    return errors::InvalidArgument(
        "Expected truth and hypothesis to have matching ranks, but "
        "their shapes are: ",
        truth_shape.shape().DebugString(), " and ",
        hypothesis_shape.shape().DebugString());

  return Status::OK();
}

}  // namespace

template <typename T>
class EditDistanceOp : public OpKernel {
 public:
  explicit EditDistanceOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("normalize", &normalize_));
  }

  void Compute(OpKernelContext* ctx) override {
    const Tensor* hypothesis_indices;
    const Tensor* hypothesis_values;
    const Tensor* hypothesis_shape;
    const Tensor* truth_indices;
    const Tensor* truth_values;
    const Tensor* truth_shape;
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_indices", &hypothesis_indices));
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_values", &hypothesis_values));
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_shape", &hypothesis_shape));
    OP_REQUIRES_OK(ctx, ctx->input("truth_indices", &truth_indices));
    OP_REQUIRES_OK(ctx, ctx->input("truth_values", &truth_values));
    OP_REQUIRES_OK(ctx, ctx->input("truth_shape", &truth_shape));

    OP_REQUIRES_OK(
        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,
                            *hypothesis_shape, *truth_indices, *truth_values,
                            *truth_shape));

    TensorShape hypothesis_st_shape;
    OP_REQUIRES_OK(
        ctx, TensorShapeUtils::MakeShape(hypothesis_shape->vec<int64>().data(),
                                         hypothesis_shape->NumElements(),
                                         &hypothesis_st_shape));
    TensorShape truth_st_shape;
    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
                            truth_shape->vec<int64>().data(),
                            truth_shape->NumElements(), &truth_st_shape));

    // Assume indices are sorted in row-major order.
    std::vector<int64> sorted_order(truth_st_shape.dims());
    std::iota(sorted_order.begin(), sorted_order.end(), 0);

    sparse::SparseTensor hypothesis(*hypothesis_indices, *hypothesis_values,
                                    hypothesis_st_shape, sorted_order);
    sparse::SparseTensor truth(*truth_indices, *truth_values, truth_st_shape,
                               sorted_order);

    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed
    // to store the variable length sequences.
    std::vector<int64> group_dims(truth_st_shape.dims() - 1);
    std::iota(group_dims.begin(), group_dims.end(), 0);

    TensorShape output_shape;
    for (size_t d = 0; d < group_dims.size(); ++d) {
      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),
                                   truth_st_shape.dim_size(d)));
    }

    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output("output", output_shape, &output));
    auto output_t = output->flat<float>();
    output_t.setZero();

    std::vector<int64> output_strides(output_shape.dims());
    output_strides[output_shape.dims() - 1] = 1;
    for (int d = output_shape.dims() - 2; d >= 0; --d) {
      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);
    }

    auto hypothesis_grouper = hypothesis.group(group_dims);
    auto truth_grouper = truth.group(group_dims);

    auto hypothesis_iter = hypothesis_grouper.begin();
    auto truth_iter = truth_grouper.begin();

    auto cmp = std::equal_to<T>();

    while (hypothesis_iter != hypothesis_grouper.end() &&
           truth_iter != truth_grouper.end()) {
      sparse::Group truth_i = *truth_iter;
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector<int64> g_truth = truth_i.group();
      std::vector<int64> g_hypothesis = hypothesis_j.group();
      auto truth_seq = truth_i.values<T>();
      auto hypothesis_seq = hypothesis_j.values<T>();

      if (g_truth == g_hypothesis) {
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), 0);
        output_t(loc) =
            gtl::LevenshteinDistance<T>(truth_seq, hypothesis_seq, cmp);
        if (normalize_) output_t(loc) /= truth_seq.size();

        ++hypothesis_iter;
        ++truth_iter;
      } else if (g_truth > g_hypothesis) {  // missing truth @ this hypothesis
        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                      output_strides.begin(), 0);
        output_t(loc) = hypothesis_seq.size();
        if (normalize_) output_t(loc) /= 0.0;
        ++hypothesis_iter;
      } else {  // missing hypothesis @ this truth
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), 0);
        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
        ++truth_iter;
      }
    }
    while (hypothesis_iter != hypothesis_grouper.end()) {  // missing truths
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector<int64> g_hypothesis = hypothesis_j.group();
      auto hypothesis_seq = hypothesis_j.values<T>();
      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                    output_strides.begin(), 0);
      output_t(loc) = hypothesis_seq.size();
      if (normalize_) output_t(loc) /= 0.0;
      ++hypothesis_iter;
    }
    while (truth_iter != truth_grouper.end()) {  // missing hypotheses
      sparse::Group truth_i = *truth_iter;
      std::vector<int64> g_truth = truth_i.group();
      auto truth_seq = truth_i.values<T>();
      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                    output_strides.begin(), 0);
      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
      ++truth_iter;
    }
  }

 private:
  bool normalize_;

  TF_DISALLOW_COPY_AND_ASSIGN(EditDistanceOp);
};

#define REGISTER_CPU_KERNEL(T)                                        \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("EditDistance").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
      EditDistanceOp<T>);

TF_CALL_ALL_TYPES(REGISTER_CPU_KERNEL);

#undef REGISTER_CPU_KERNEL

class EditDistanceListOp : public OpKernel {
 public:
  explicit EditDistanceListOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("eos_token", &eos_token_));
  }

  void ExtractSequence(
      const OpInputList& list, std::vector<std::vector<int32>>* sequence) {
    const int64 batch_size = list[0].dim_size(0);
    sequence->resize(batch_size);

    std::vector<bool> terminated(batch_size, false);
    for (int64 t = 0; t < list.size(); ++t) {
      for (int64 b = 0; b < batch_size; ++b) {
        if (!terminated[b]) {
          const int32 token = list[t].vec<int>()(b);
          if (token == eos_token_) {
            terminated[b] = true;
          } else {
            (*sequence)[b].emplace_back(token);
          }
        }
      }
    }
  }

  void Compute(OpKernelContext* ctx) override {
    OpInputList ref_list;
    OpInputList hyp_list;
    OP_REQUIRES_OK(ctx, ctx->input_list("ref", &ref_list));
    OP_REQUIRES_OK(ctx, ctx->input_list("hyp", &hyp_list));

    std::vector<std::vector<int32>> ref;
    std::vector<std::vector<int32>> hyp;

    ExtractSequence(ref_list, &ref);
    ExtractSequence(hyp_list, &hyp);

    const int64 batch_size = ref_list[0].dim_size(0);

    TensorShape output_shape({batch_size});

    Tensor* tensor_edit_distance = nullptr;
    ctx->allocate_output(
        "edit_distance", output_shape, &tensor_edit_distance);
    Tensor* tensor_ref_length = nullptr;
    ctx->allocate_output(
        "ref_length", output_shape, &tensor_ref_length);

    auto cmp = std::equal_to<int32>();
    for (int64 b = 0; b < batch_size; ++b) {
      const int64 edit_distance =
          gtl::LevenshteinDistance<int32>(ref[b], hyp[b], cmp);
      const int64 ref_length = ref.size();

      tensor_edit_distance->vec<int64>()(b) = edit_distance;
      tensor_ref_length->vec<int64>()(b) = ref_length;
    }
  }

 private:
  int32 eos_token_;
};

REGISTER_KERNEL_BUILDER(                                                       \
    Name("EditDistanceList").Device(DEVICE_CPU),                               \
    EditDistanceListOp);
}  // end namespace tensorflow
<commit_msg>bug fix<commit_after>/* Copyright 2015 Google Inc. 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.
==============================================================================*/

// See docs in ../ops/array_ops.cc.

#define EIGEN_USE_THREADS

#include <limits>

#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/edit_distance.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"

namespace tensorflow {

namespace {

Status ValidateShapes(OpKernelContext* ctx, const Tensor& hypothesis_indices,
                      const Tensor& hypothesis_values,
                      const Tensor& hypothesis_shape,
                      const Tensor& truth_indices, const Tensor& truth_values,
                      const Tensor& truth_shape) {
  if (!TensorShapeUtils::IsMatrix(hypothesis_indices.shape()))
    return errors::InvalidArgument(
        "hypothesis_indices should be a matrix, but got shape: ",
        hypothesis_indices.shape().DebugString());
  if (!TensorShapeUtils::IsMatrix(truth_indices.shape()))
    return errors::InvalidArgument(
        "truth_indices should be a matrix, but got shape: ",
        truth_indices.shape().DebugString());
  if (!TensorShapeUtils::IsVector(hypothesis_values.shape()))
    return errors::InvalidArgument(
        "hypothesis_values should be a vector, but got shape: ",
        hypothesis_values.shape().DebugString());
  if (!TensorShapeUtils::IsVector(truth_values.shape()))
    return errors::InvalidArgument(
        "truth_values should be a vector, but got shape: ",
        truth_values.shape().DebugString());
  if (!TensorShapeUtils::IsVector(hypothesis_shape.shape()))
    return errors::InvalidArgument(
        "hypothesis_shape should be a vector, but got shape: ",
        hypothesis_shape.shape().DebugString());
  if (!TensorShapeUtils::IsVector(truth_shape.shape()))
    return errors::InvalidArgument(
        "truth_shape should be a vector, but got shape: ",
        truth_shape.shape().DebugString());
  if (hypothesis_shape.NumElements() != hypothesis_indices.dim_size(1))
    return errors::InvalidArgument(
        "Expected hypothesis_shape.NumElements == "
        "#cols(hypothesis_indices), their shapes are: ",
        hypothesis_shape.shape().DebugString(), " and ",
        hypothesis_indices.shape().DebugString());
  if (truth_shape.NumElements() < 2)
    return errors::InvalidArgument(
        "Input SparseTensors must have rank at least 2, but truth_shape "
        "rank is: ",
        truth_shape.NumElements());
  if (truth_shape.NumElements() != truth_indices.dim_size(1))
    return errors::InvalidArgument(
        "Expected truth_shape.NumElements == "
        "#cols(truth_indices), their shapes are: ",
        truth_shape.shape().DebugString(), " and ",
        truth_indices.shape().DebugString());
  if (truth_shape.NumElements() != hypothesis_shape.NumElements())
    return errors::InvalidArgument(
        "Expected truth and hypothesis to have matching ranks, but "
        "their shapes are: ",
        truth_shape.shape().DebugString(), " and ",
        hypothesis_shape.shape().DebugString());

  return Status::OK();
}

}  // namespace

template <typename T>
class EditDistanceOp : public OpKernel {
 public:
  explicit EditDistanceOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("normalize", &normalize_));
  }

  void Compute(OpKernelContext* ctx) override {
    const Tensor* hypothesis_indices;
    const Tensor* hypothesis_values;
    const Tensor* hypothesis_shape;
    const Tensor* truth_indices;
    const Tensor* truth_values;
    const Tensor* truth_shape;
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_indices", &hypothesis_indices));
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_values", &hypothesis_values));
    OP_REQUIRES_OK(ctx, ctx->input("hypothesis_shape", &hypothesis_shape));
    OP_REQUIRES_OK(ctx, ctx->input("truth_indices", &truth_indices));
    OP_REQUIRES_OK(ctx, ctx->input("truth_values", &truth_values));
    OP_REQUIRES_OK(ctx, ctx->input("truth_shape", &truth_shape));

    OP_REQUIRES_OK(
        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,
                            *hypothesis_shape, *truth_indices, *truth_values,
                            *truth_shape));

    TensorShape hypothesis_st_shape;
    OP_REQUIRES_OK(
        ctx, TensorShapeUtils::MakeShape(hypothesis_shape->vec<int64>().data(),
                                         hypothesis_shape->NumElements(),
                                         &hypothesis_st_shape));
    TensorShape truth_st_shape;
    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
                            truth_shape->vec<int64>().data(),
                            truth_shape->NumElements(), &truth_st_shape));

    // Assume indices are sorted in row-major order.
    std::vector<int64> sorted_order(truth_st_shape.dims());
    std::iota(sorted_order.begin(), sorted_order.end(), 0);

    sparse::SparseTensor hypothesis(*hypothesis_indices, *hypothesis_values,
                                    hypothesis_st_shape, sorted_order);
    sparse::SparseTensor truth(*truth_indices, *truth_values, truth_st_shape,
                               sorted_order);

    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed
    // to store the variable length sequences.
    std::vector<int64> group_dims(truth_st_shape.dims() - 1);
    std::iota(group_dims.begin(), group_dims.end(), 0);

    TensorShape output_shape;
    for (size_t d = 0; d < group_dims.size(); ++d) {
      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),
                                   truth_st_shape.dim_size(d)));
    }

    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output("output", output_shape, &output));
    auto output_t = output->flat<float>();
    output_t.setZero();

    std::vector<int64> output_strides(output_shape.dims());
    output_strides[output_shape.dims() - 1] = 1;
    for (int d = output_shape.dims() - 2; d >= 0; --d) {
      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);
    }

    auto hypothesis_grouper = hypothesis.group(group_dims);
    auto truth_grouper = truth.group(group_dims);

    auto hypothesis_iter = hypothesis_grouper.begin();
    auto truth_iter = truth_grouper.begin();

    auto cmp = std::equal_to<T>();

    while (hypothesis_iter != hypothesis_grouper.end() &&
           truth_iter != truth_grouper.end()) {
      sparse::Group truth_i = *truth_iter;
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector<int64> g_truth = truth_i.group();
      std::vector<int64> g_hypothesis = hypothesis_j.group();
      auto truth_seq = truth_i.values<T>();
      auto hypothesis_seq = hypothesis_j.values<T>();

      if (g_truth == g_hypothesis) {
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), 0);
        output_t(loc) =
            gtl::LevenshteinDistance<T>(truth_seq, hypothesis_seq, cmp);
        if (normalize_) output_t(loc) /= truth_seq.size();

        ++hypothesis_iter;
        ++truth_iter;
      } else if (g_truth > g_hypothesis) {  // missing truth @ this hypothesis
        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                      output_strides.begin(), 0);
        output_t(loc) = hypothesis_seq.size();
        if (normalize_) output_t(loc) /= 0.0;
        ++hypothesis_iter;
      } else {  // missing hypothesis @ this truth
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), 0);
        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
        ++truth_iter;
      }
    }
    while (hypothesis_iter != hypothesis_grouper.end()) {  // missing truths
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector<int64> g_hypothesis = hypothesis_j.group();
      auto hypothesis_seq = hypothesis_j.values<T>();
      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                    output_strides.begin(), 0);
      output_t(loc) = hypothesis_seq.size();
      if (normalize_) output_t(loc) /= 0.0;
      ++hypothesis_iter;
    }
    while (truth_iter != truth_grouper.end()) {  // missing hypotheses
      sparse::Group truth_i = *truth_iter;
      std::vector<int64> g_truth = truth_i.group();
      auto truth_seq = truth_i.values<T>();
      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                    output_strides.begin(), 0);
      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
      ++truth_iter;
    }
  }

 private:
  bool normalize_;

  TF_DISALLOW_COPY_AND_ASSIGN(EditDistanceOp);
};

#define REGISTER_CPU_KERNEL(T)                                        \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("EditDistance").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
      EditDistanceOp<T>);

TF_CALL_ALL_TYPES(REGISTER_CPU_KERNEL);

#undef REGISTER_CPU_KERNEL

class EditDistanceListOp : public OpKernel {
 public:
  explicit EditDistanceListOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("eos_token", &eos_token_));
  }

  void ExtractSequence(
      const OpInputList& list, std::vector<std::vector<int32>>* sequence) {
    const int64 batch_size = list[0].dim_size(0);
    sequence->resize(batch_size);

    std::vector<bool> terminated(batch_size, false);
    for (int64 t = 0; t < list.size(); ++t) {
      for (int64 b = 0; b < batch_size; ++b) {
        if (!terminated[b]) {
          const int32 token = list[t].vec<int>()(b);
          if (token == eos_token_) {
            terminated[b] = true;
          } else {
            (*sequence)[b].emplace_back(token);
          }
        }
      }
    }
  }

  void Compute(OpKernelContext* ctx) override {
    OpInputList ref_list;
    OpInputList hyp_list;
    OP_REQUIRES_OK(ctx, ctx->input_list("ref", &ref_list));
    OP_REQUIRES_OK(ctx, ctx->input_list("hyp", &hyp_list));

    std::vector<std::vector<int32>> ref;
    std::vector<std::vector<int32>> hyp;
    ExtractSequence(ref_list, &ref);
    ExtractSequence(hyp_list, &hyp);

    const int64 batch_size = ref_list[0].dim_size(0);

    TensorShape output_shape({batch_size});

    Tensor* tensor_edit_distance = nullptr;
    ctx->allocate_output(
        "edit_distance", output_shape, &tensor_edit_distance);
    Tensor* tensor_ref_length = nullptr;
    ctx->allocate_output(
        "ref_length", output_shape, &tensor_ref_length);

    auto cmp = std::equal_to<int32>();
    for (int64 b = 0; b < batch_size; ++b) {
      const int64 edit_distance =
          gtl::LevenshteinDistance<int32>(ref[b], hyp[b], cmp);
      const int64 ref_length = ref[b].size();

      tensor_edit_distance->vec<int64>()(b) = edit_distance;
      tensor_ref_length->vec<int64>()(b) = ref_length;
    }
  }

 private:
  int32 eos_token_;
};

REGISTER_KERNEL_BUILDER(                                                       \
    Name("EditDistanceList").Device(DEVICE_CPU),                               \
    EditDistanceListOp);
}  // end namespace tensorflow
<|endoftext|>


<commit_before>/* CsaReader.cpp
 *
 * Kubo Ryosuke
 */

#include "CsaReader.h"
#include "logger/Logger.h"
#include <fstream>

#define LINE_BUFFER_SIZE							1024

namespace sunfish {

	bool CsaReader::read(const char* filename, Record& record) {

		std::ifstream file(filename);
		if (!file) {
			return false;
		}

		bool ok = read(file, record);

		file.close();
		return ok;

	}

	bool CsaReader::read(std::istream& is, Record& record) {
		Board board;

		// 局面の読み込み
		if (!readBoard(is, board)) {
			return false;
		}

		record.init(board);

		// 指し手の読み込み
		if (!readMoves(is, record)) {
			return false;
		}

		return true;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::readBoard(std::istream& is, Board& board) {
		bool ok = _readBoard(is, board);
		board.refreshHash();
		return ok;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::readBoard(const char* line, Board& board) {
		bool ok = _readBoard(line, board);
		board.refreshHash();
		return ok;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::_readBoard(std::istream& is, Board& board) {
		char line[LINE_BUFFER_SIZE];

		board.init();

		while (true) {
			is.getline(line, sizeof(line));
			if (is.eof()) {
				return true;
			}
			if (is.fail()) {
				Loggers::warning << "file io error. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (!_readBoard(line, board)) {
				Loggers::warning << "invalid board format. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (line[0] == '+' || line[0] == '-') {
				return true;
			}
		}
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::_readBoard(const char* line, Board& board) {
		switch (line[0]) {
		case 'P':
			if (line[1] >= '1' && line[1] <= '9') {
				return _readBoardPieces(line, board);
			} else if (line[1] == '+') {
				return _readHand(line, board, true);
			} else if (line[1] == '-') {
				return _readHand(line, board, false);
			}
			return false;
		case '+':
			board.setBlack();
			return true;
		case '-':
			board.setWhite();
			return true;
		case 'V': case 'N': case '$': case '\'': case '\0':
			return true;
		default:
			return false;
		}
	}

	/**
	 * 盤面の読み込み
	 */
	bool CsaReader::_readBoardPieces(const char* line, Board& board) {
		if (strlen(line) < 2 + 3 * Position::FileN) {
			Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
			return false;
		}
		int rank = line[1] - '0';
		for (int file = 1; file <= Position::FileN; file++) {
			Piece piece = Piece::parseCsa(line + 2 + 3 * (9 - file));
			board.setBoardPiece(Position(file, rank), piece);
		}
		return true;
	}

	/**
	 * 持ち駒の読み込み
	 */
	bool CsaReader::_readHand(const char* line, Board& board, bool black) {
		auto length = strlen(line);
		for (auto i = 2; i + 4 <= length; i += 4) {
			unsigned file = line[i+0] - '0';
			unsigned rank = line[i+1] - '0';
			Piece piece = Piece::parseCsa(&line[i+2]);
			if (piece != Piece::Empty) {
				if (Position::isValidFile(file) && Position::isValidRank(rank)) {
					board.setBoardPiece(Position(file, rank), black ? piece.black() : piece.white());
				} else if (file == 0 && rank == 0 && piece.isUnpromoted() && piece != Piece::King) {
					if (black) {
						board.incBlackHand(piece);
					} else {
						board.incWhiteHand(piece);
					}
				} else {
					Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
					return false;
				}
			} else {
				Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
		}
		return true;
	}

	/**
	 * 手順の読み込み
	 */
	bool CsaReader::readMoves(std::istream& is, Record& record) {
		char line[LINE_BUFFER_SIZE];
		Move move;

		while (true) {
			is.getline(line, sizeof(line));
			if (is.eof()) {
				return true;
			}
			if (is.fail()) {
				Loggers::warning << "file io error. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (!readMove(line, record.getBoard(), move)) {
				Loggers::warning << "invalid move format. " << __FILE__ << "(" << __LINE__ << ")";
				Loggers::warning << "> " << line;
				return false;
			}
			record.makeMove(move);
		}
	}

	/**
	 * 指し手の読み込み
	 */
	bool CsaReader::readMove(const char* line, const Board& board, Move& move) {
		if (line[0] == '\0' || line[0] == 'T' || line[0] == '\'') {
			return true;
		}

		if (strlen(line) < 7) {
			return false;
		}

		bool black;
		if (line[0] == '+') {
			black = true;
		} else if (line[0] == '-') {
			black = false;
		} else {
			return false;
		}

		if (black != board.isBlack()) {
			return false;
		}

		Position to = Position::parse(&line[3]);
		Piece piece = Piece::parseCsa(&line[5]);
		if (line[1] == '0' && line[2] == '0') {
			move = Move(piece, to);
		} else {
			Position from = Position::parse(&line[1]);
			Piece pieceOrg = board.getBoardPiece(from).kindOnly();
			bool promote;
			if (piece == pieceOrg) {
				promote = false;
			} else if (piece == pieceOrg.promote()) {
				promote = true;
			} else {
				return false;
			}
			move = Move(pieceOrg, from, to, promote);
		}

		return true;
	}
}
<commit_msg>Fix for gcc warnings<commit_after>/* CsaReader.cpp
 *
 * Kubo Ryosuke
 */

#include "CsaReader.h"
#include "logger/Logger.h"
#include <fstream>

#define LINE_BUFFER_SIZE							1024

namespace sunfish {

	bool CsaReader::read(const char* filename, Record& record) {

		std::ifstream file(filename);
		if (!file) {
			return false;
		}

		bool ok = read(file, record);

		file.close();
		return ok;

	}

	bool CsaReader::read(std::istream& is, Record& record) {
		Board board;

		// 局面の読み込み
		if (!readBoard(is, board)) {
			return false;
		}

		record.init(board);

		// 指し手の読み込み
		if (!readMoves(is, record)) {
			return false;
		}

		return true;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::readBoard(std::istream& is, Board& board) {
		bool ok = _readBoard(is, board);
		board.refreshHash();
		return ok;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::readBoard(const char* line, Board& board) {
		bool ok = _readBoard(line, board);
		board.refreshHash();
		return ok;
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::_readBoard(std::istream& is, Board& board) {
		char line[LINE_BUFFER_SIZE];

		board.init();

		while (true) {
			is.getline(line, sizeof(line));
			if (is.eof()) {
				return true;
			}
			if (is.fail()) {
				Loggers::warning << "file io error. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (!_readBoard(line, board)) {
				Loggers::warning << "invalid board format. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (line[0] == '+' || line[0] == '-') {
				return true;
			}
		}
	}

	/**
	 * 局面の読み込み
	 */
	bool CsaReader::_readBoard(const char* line, Board& board) {
		switch (line[0]) {
		case 'P':
			if (line[1] >= '1' && line[1] <= '9') {
				return _readBoardPieces(line, board);
			} else if (line[1] == '+') {
				return _readHand(line, board, true);
			} else if (line[1] == '-') {
				return _readHand(line, board, false);
			}
			return false;
		case '+':
			board.setBlack();
			return true;
		case '-':
			board.setWhite();
			return true;
		case 'V': case 'N': case '$': case '\'': case '\0':
			return true;
		default:
			return false;
		}
	}

	/**
	 * 盤面の読み込み
	 */
	bool CsaReader::_readBoardPieces(const char* line, Board& board) {
		if (strlen(line) < 2 + 3 * Position::FileN) {
			Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
			return false;
		}
		int rank = line[1] - '0';
		for (int file = 1; file <= Position::FileN; file++) {
			Piece piece = Piece::parseCsa(line + 2 + 3 * (9 - file));
			board.setBoardPiece(Position(file, rank), piece);
		}
		return true;
	}

	/**
	 * 持ち駒の読み込み
	 */
	bool CsaReader::_readHand(const char* line, Board& board, bool black) {
		unsigned length = strlen(line);
		for (unsigned i = 2; i + 4 <= length; i += 4) {
			unsigned file = line[i+0] - '0';
			unsigned rank = line[i+1] - '0';
			Piece piece = Piece::parseCsa(&line[i+2]);
			if (piece != Piece::Empty) {
				if (Position::isValidFile(file) && Position::isValidRank(rank)) {
					board.setBoardPiece(Position(file, rank), black ? piece.black() : piece.white());
				} else if (file == 0 && rank == 0 && piece.isUnpromoted() && piece != Piece::King) {
					if (black) {
						board.incBlackHand(piece);
					} else {
						board.incWhiteHand(piece);
					}
				} else {
					Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
					return false;
				}
			} else {
				Loggers::warning << "invalid format. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
		}
		return true;
	}

	/**
	 * 手順の読み込み
	 */
	bool CsaReader::readMoves(std::istream& is, Record& record) {
		char line[LINE_BUFFER_SIZE];
		Move move;

		while (true) {
			is.getline(line, sizeof(line));
			if (is.eof()) {
				return true;
			}
			if (is.fail()) {
				Loggers::warning << "file io error. " << __FILE__ << "(" << __LINE__ << ")";
				return false;
			}
			if (!readMove(line, record.getBoard(), move)) {
				Loggers::warning << "invalid move format. " << __FILE__ << "(" << __LINE__ << ")";
				Loggers::warning << "> " << line;
				return false;
			}
			record.makeMove(move);
		}
	}

	/**
	 * 指し手の読み込み
	 */
	bool CsaReader::readMove(const char* line, const Board& board, Move& move) {
		if (line[0] == '\0' || line[0] == 'T' || line[0] == '\'') {
			return true;
		}

		if (strlen(line) < 7) {
			return false;
		}

		bool black;
		if (line[0] == '+') {
			black = true;
		} else if (line[0] == '-') {
			black = false;
		} else {
			return false;
		}

		if (black != board.isBlack()) {
			return false;
		}

		Position to = Position::parse(&line[3]);
		Piece piece = Piece::parseCsa(&line[5]);
		if (line[1] == '0' && line[2] == '0') {
			move = Move(piece, to);
		} else {
			Position from = Position::parse(&line[1]);
			Piece pieceOrg = board.getBoardPiece(from).kindOnly();
			bool promote;
			if (piece == pieceOrg) {
				promote = false;
			} else if (piece == pieceOrg.promote()) {
				promote = true;
			} else {
				return false;
			}
			move = Move(pieceOrg, from, to, promote);
		}

		return true;
	}
}
<|endoftext|>


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

#include <glosm/GeometryOperations.hh>
#include <glosm/geomath.h>
#include <math.h>

bool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {
	if (one.y < y && two.y < y)
		return false;

	if (one.y > y && two.y > y)
		return false;

	float t = (float)(one.y - y) / (float)(one.y - two.y);

	float x = (float)(two.x - one.x) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(one.x + round(x), y, one.z + round(z));
	return true;
}

bool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {
	if (one.x < x && two.x < x)
		return false;

	if (one.x > x && two.x > x)
		return false;

	float t = (float)(one.x - x) / (float)(one.x - two.x);

	float y = (float)(two.y - one.y) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(x, one.y + round(y), one.z + round(z));
	return true;
}

bool IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	return IntersectSegmentWithHorizontal(one, two, bbox.top, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.left, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.right, out);
}

bool IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	return IntersectSegmentWithVertical(one, two, bbox.right, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.left, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.top, out);
}

bool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {
	if (bbox.Contains(one)) {
		/* one is in the bbox */
		outone = one;
		if (bbox.Contains(two)) {
			/* both points are in the bbox */
			outtwo = two;
		} else {
			/* other point is outside - find intersection */
			return IntersectSegmentWithBBox(one, two, bbox, outtwo);
		}
	} else if (bbox.Contains(two)) {
		/* two is inside, one is outside */
		outtwo = two;
		return IntersectSegmentWithBBox(one, two, bbox, outone);
	}

	/* both points are outside, find two points of intersection */
	return IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo);
}

Vector3d ToLocalMetric(Vector3i what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	double dx = (double)(what.x - ref.x)/3600000000.0*WGS84_EARTH_EQ_LENGTH*cos(lat);
	double dy = (double)(what.y - ref.y)/3600000000.0*WGS84_EARTH_EQ_LENGTH;
	double dz = (double)(what.z - ref.z)/1000.0;

	return Vector3f(dx, dy, dz);
}

Vector3i FromLocalMetric(Vector3d what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	int x = ref.x + round(what.x*3600000000.0/WGS84_EARTH_EQ_LENGTH/cos(lat));
	int y = ref.y + round(what.y*3600000000.0/WGS84_EARTH_EQ_LENGTH);
	int z = ref.z + round(what.z*1000.0);

	return Vector3i(x, y, z);
}

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

#include <glosm/GeometryOperations.hh>
#include <glosm/geomath.h>
#include <math.h>

bool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {
	if (one.y < y && two.y < y)
		return false;

	if (one.y > y && two.y > y)
		return false;

	float t = (float)(one.y - y) / (float)(one.y - two.y);

	float x = (float)(two.x - one.x) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(one.x + round(x), y, one.z + round(z));
	return true;
}

bool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {
	if (one.x < x && two.x < x)
		return false;

	if (one.x > x && two.x > x)
		return false;

	float t = (float)(one.x - x) / (float)(one.x - two.x);

	float y = (float)(two.y - one.y) * t;
	float z = (float)(two.z - one.z) * t;

	out = Vector3i(x, one.y + round(y), one.z + round(z));
	return true;
}

bool IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	return IntersectSegmentWithHorizontal(one, two, bbox.top, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.left, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.right, out);
}

bool IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {
	return IntersectSegmentWithVertical(one, two, bbox.right, out) ||
	       IntersectSegmentWithVertical(one, two, bbox.left, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) ||
	       IntersectSegmentWithHorizontal(one, two, bbox.top, out);
}

bool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {
	if (bbox.Contains(one)) {
		/* one is in the bbox */
		outone = one;
		if (bbox.Contains(two)) {
			/* both points are in the bbox */
			outtwo = two;
		} else {
			/* other point is outside - find intersection */
			return IntersectSegmentWithBBox(one, two, bbox, outtwo);
		}
	} else if (bbox.Contains(two)) {
		/* two is inside, one is outside */
		outtwo = two;
		return IntersectSegmentWithBBox(one, two, bbox, outone);
	}

	/* both points are outside, find two points of intersection */
	return IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo) && bbox.Contains(outone) && bbox.Contains(outtwo);
}

Vector3d ToLocalMetric(Vector3i what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	double dx = (double)(what.x - ref.x)/3600000000.0*WGS84_EARTH_EQ_LENGTH*cos(lat);
	double dy = (double)(what.y - ref.y)/3600000000.0*WGS84_EARTH_EQ_LENGTH;
	double dz = (double)(what.z - ref.z)/1000.0;

	return Vector3f(dx, dy, dz);
}

Vector3i FromLocalMetric(Vector3d what, Vector3i ref) {
	double lat = ref.y/1800000000.0*M_PI;

	int x = ref.x + round(what.x*3600000000.0/WGS84_EARTH_EQ_LENGTH/cos(lat));
	int y = ref.y + round(what.y*3600000000.0/WGS84_EARTH_EQ_LENGTH);
	int z = ref.z + round(what.z*1000.0);

	return Vector3i(x, y, z);
}

<|endoftext|>