<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <unistd.h>

#include <new>

#include <functional>
#include <string>

#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <process/io.hpp>
#include <process/process.hpp>

#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>

#include <stout/os/pagesize.hpp>
#include <stout/os/shell.hpp>
#include <stout/os/su.hpp>
#include <stout/os/write.hpp>

// TODO(abudnik): `ENABLE_LAUNCHER_SEALING` should be replaced with
// `__linux__`, once we drop support for kernels older than 3.17, which
// do not support memfd.
#ifdef ENABLE_LAUNCHER_SEALING
#include "linux/memfd.hpp"
#endif // ENABLE_LAUNCHER_SEALING

#include "logging/logging.hpp"

#include "slave/container_loggers/logrotate.hpp"

using std::string;

using namespace process;
using namespace mesos::internal::logger::rotate;

class LogrotateLoggerProcess : public Process<LogrotateLoggerProcess>
{
public:
  static Try<LogrotateLoggerProcess*> create(const Flags& flags)
  {
    Option<int_fd> configMemFd;

    // Calculate the size of the buffer that is used for reading from
    // the `incoming` pipe.
    const size_t bufferSize = os::pagesize();

    // Populate the `logrotate` configuration file.
    // See `Flags::logrotate_options` for the format.
    //
    // NOTE: We specify a size of `--max_size - bufferSize` because `logrotate`
    // has slightly different size semantics.  `logrotate` will rotate when the
    // max size is *exceeded*.  We rotate to keep files *under* the max size.
    const string config =
      "\"" + flags.log_filename.get() + "\" {\n" +
      flags.logrotate_options.getOrElse("") + "\n" +
      "size " + stringify(flags.max_size.bytes() - bufferSize) + "\n" +
      "}";

    // TODO(abudnik): `ENABLE_LAUNCHER_SEALING` should be replaced with
    // `__linux__`, once we drop support for kernels older than 3.17, which
    // do not support memfd.
#ifdef ENABLE_LAUNCHER_SEALING
    // Create a temporary anonymous file, which can be accessed by a child
    // process by opening a `/proc/self/fd/<FD of anonymous file>`.
    // This file is automatically removed on process termination, so we don't
    // need to garbage collect it.
    // We use the `memfd` file to pass the configuration to `logrotate`.
    Try<int_fd> memFd =
      mesos::internal::memfd::create("mesos_logrotate", 0);

    if (memFd.isError()) {
      return Error(
          "Failed to create memfd file '" +
          flags.log_filename.get() + "': " + memFd.error());
    }

    Try<Nothing> write = os::write(memFd.get(), config);
    if (write.isError()) {
      os::close(memFd.get());
      return Error("Failed to write memfd file '" + flags.log_filename.get() +
                   "': " + write.error());
    }

    // `logrotate` requires configuration file to have 0644 or 0444 permissions.
    int ret = fchmod(memFd.get(), S_IRUSR | S_IRGRP | S_IROTH);
    if (ret == -1) {
      ErrnoError error("Failed to chmod memfd file '" +
                       flags.log_filename.get() + "'");
      os::close(memFd.get());
      return error;
    }

    configMemFd = memFd.get();
#else
    Try<Nothing> result = os::write(
        flags.log_filename.get() + CONF_SUFFIX, config);

    if (result.isError()) {
      return Error("Failed to write configuration file: " + result.error());
    }
#endif // ENABLE_LAUNCHER_SEALING

    return new LogrotateLoggerProcess(flags, configMemFd, bufferSize);
  }

  ~LogrotateLoggerProcess() override
  {
    if (configMemFd.isSome()) {
      os::close(configMemFd.get());
    }

    if (buffer != nullptr) {
      delete[] buffer;
      buffer = nullptr;
    }

    if (leading.isSome()) {
      os::close(leading.get());
    }
  }

  // Prepares and starts the loop which reads from stdin, writes to the
  // leading log file, and manages total log size.
  Future<Nothing> run()
  {
    // NOTE: This is a prerequisuite for `io::read`.
    Try<Nothing> async = io::prepare_async(STDIN_FILENO);
    if (async.isError()) {
      return Failure("Failed to set async pipe: " + async.error());
    }

    // NOTE: This does not block.
    loop();

    return promise.future();
  }

  // Reads from stdin and writes to the leading log file.
  void loop()
  {
    io::read(STDIN_FILENO, buffer, bufferSize)
      .then(defer(self(), [&](size_t readSize) -> Future<Nothing> {
        // Check if EOF has been reached on the input stream.
        // This indicates that the container (whose logs are being
        // piped to this process) has exited.
        if (readSize <= 0) {
          promise.set(Nothing());
          return Nothing();
        }

        // Do log rotation (if necessary) and write the bytes to the
        // leading log file.
        Try<Nothing> result = write(readSize);
        if (result.isError()) {
          promise.fail("Failed to write: " + result.error());
          return Nothing();
        }

        // Use `dispatch` to limit the size of the call stack.
        dispatch(self(), &LogrotateLoggerProcess::loop);

        return Nothing();
      }));
  }

  // Writes the buffer from stdin to the leading log file.
  // When the number of written bytes exceeds `--max_size`, the leading
  // log file is rotated.  When the number of log files exceed `--max_files`,
  // the oldest log file is deleted.
  Try<Nothing> write(size_t readSize)
  {
    // Rotate the log file if it will grow beyond the `--max_size`.
    if (bytesWritten + readSize > flags.max_size.bytes()) {
      rotate();
    }

    // If the leading log file is not open, open it.
    // NOTE: We open the file in append-mode as `logrotate` may sometimes fail.
    if (leading.isNone()) {
      Try<int> open = os::open(
          flags.log_filename.get(),
          O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,
          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

      if (open.isError()) {
        return Error(
            "Failed to open '" + flags.log_filename.get() +
            "': " + open.error());
      }

      leading = open.get();
    }

    // Write from stdin to `leading`.
    // NOTE: We do not exit on error here since we are prioritizing
    // clearing the STDIN pipe (which would otherwise potentially block
    // the container on write) over log fidelity.
    Try<Nothing> result =
      os::write(leading.get(), string(buffer, readSize));

    if (result.isError()) {
      std::cerr << "Failed to write: " << result.error() << std::endl;
    }

    bytesWritten += readSize;

    return Nothing();
  }

  // Calls `logrotate` on the leading log file and resets the `bytesWritten`.
  void rotate()
  {
    if (leading.isSome()) {
      os::close(leading.get());
      leading = None();
    }

    // Call `logrotate` to move around the files.
    // NOTE: If `logrotate` fails for whatever reason, we will ignore
    // the error and continue logging.  In case the leading log file
    // is not renamed, we will continue appending to the existing
    // leading log file.
    os::shell(
        flags.logrotate_path +
        " --state \"" + flags.log_filename.get() + STATE_SUFFIX + "\" \"" +
        configPath + "\"");

    // Reset the number of bytes written.
    bytesWritten = 0;
  }

private:
  explicit LogrotateLoggerProcess(
      const Flags& _flags,
      const Option<int_fd>& _configMemFd,
      size_t _bufferSize)
    : ProcessBase(process::ID::generate("logrotate-logger")),
      flags(_flags),
      configMemFd(_configMemFd),
      buffer(new char[_bufferSize]),
      bufferSize(_bufferSize),
      leading(None()),
      bytesWritten(0)
  {
    if (configMemFd.isSome()) {
      configPath = "/proc/self/fd/" + stringify(configMemFd.get());
    } else {
      configPath = flags.log_filename.get() + CONF_SUFFIX;
    }
  }

  const Flags flags;
  const Option<int_fd> configMemFd;

  string configPath;

  // For reading from stdin.
  char* buffer;
  const size_t bufferSize;

  // For writing and rotating the leading log file.
  Option<int> leading;
  size_t bytesWritten;

  // Used to capture when log rotation has completed because the
  // underlying process/input has terminated.
  Promise<Nothing> promise;
};

int main(int argc, char** argv)
{
  Flags flags;

  // Load and validate flags from the environment and command line.
  Try<flags::Warnings> load = flags.load(None(), &argc, &argv);

  if (flags.help) {
    std::cout << flags.usage() << std::endl;
    return EXIT_SUCCESS;
  }

  if (load.isError()) {
    std::cerr << flags.usage(load.error()) << std::endl;
    return EXIT_FAILURE;
  }

  mesos::internal::logging::initialize(argv[0], false);

  // Log any flag warnings.
  foreach (const flags::Warning& warning, load->warnings) {
    LOG(WARNING) << warning.message;
  }

  // Make sure this process is running in its own session.
  // This ensures that, if the parent process (presumably the Mesos agent)
  // terminates, this logger process will continue to run.
  if (::setsid() == -1) {
    EXIT(EXIT_FAILURE)
      << ErrnoError("Failed to put child in a new session").message;
  }

  // If the `--user` flag is set, change the UID of this process to that user.
  if (flags.user.isSome()) {
    Try<Nothing> result = os::su(flags.user.get());

    if (result.isError()) {
      EXIT(EXIT_FAILURE)
        << ErrnoError("Failed to switch user for logrotate process").message;
    }
  }

  // Asynchronously control the flow and size of logs.
  Try<LogrotateLoggerProcess*> process = LogrotateLoggerProcess::create(flags);
  if (process.isError()) {
    EXIT(EXIT_FAILURE)
      << Error("Failed to create Logrotate process: " + process.error());
  }

  spawn(process.get());

  // Wait for the logging process to finish.
  Future<Nothing> status =
    dispatch(process.get(), &LogrotateLoggerProcess::run);

  status.await();

  terminate(process.get());
  wait(process.get());

  delete process.get();

  return status.isReady() ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Fixed compile error with a built-in logrotate module.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <unistd.h>

#include <new>

#include <functional>
#include <string>

#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <process/io.hpp>
#include <process/process.hpp>

#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>

#include <stout/os/pagesize.hpp>
#include <stout/os/shell.hpp>
#include <stout/os/su.hpp>
#include <stout/os/write.hpp>

// TODO(abudnik): `ENABLE_LAUNCHER_SEALING` should be replaced with
// `__linux__`, once we drop support for kernels older than 3.17, which
// do not support memfd.
#ifdef ENABLE_LAUNCHER_SEALING
#include "linux/memfd.hpp"
#endif // ENABLE_LAUNCHER_SEALING

#include "logging/logging.hpp"

#include "slave/container_loggers/logrotate.hpp"

using std::string;

using namespace process;
using namespace mesos::internal::logger::rotate;

class LogrotateLoggerProcess : public Process<LogrotateLoggerProcess>
{
public:
  static Try<LogrotateLoggerProcess*> create(const Flags& flags)
  {
    Option<int_fd> configMemFd;

    // Calculate the size of the buffer that is used for reading from
    // the `incoming` pipe.
    const size_t bufferSize = os::pagesize();

    // Populate the `logrotate` configuration file.
    // See `Flags::logrotate_options` for the format.
    //
    // NOTE: We specify a size of `--max_size - bufferSize` because `logrotate`
    // has slightly different size semantics.  `logrotate` will rotate when the
    // max size is *exceeded*.  We rotate to keep files *under* the max size.
    const string config =
      "\"" + flags.log_filename.get() + "\" {\n" +
      flags.logrotate_options.getOrElse("") + "\n" +
      "size " + stringify(flags.max_size.bytes() - bufferSize) + "\n" +
      "}";

    // TODO(abudnik): `ENABLE_LAUNCHER_SEALING` should be replaced with
    // `__linux__`, once we drop support for kernels older than 3.17, which
    // do not support memfd.
#ifdef ENABLE_LAUNCHER_SEALING
    // Create a temporary anonymous file, which can be accessed by a child
    // process by opening a `/proc/self/fd/<FD of anonymous file>`.
    // This file is automatically removed on process termination, so we don't
    // need to garbage collect it.
    // We use the `memfd` file to pass the configuration to `logrotate`.
    Try<int_fd> memFd =
      mesos::internal::memfd::create("mesos_logrotate", 0);

    if (memFd.isError()) {
      return Error(
          "Failed to create memfd file '" +
          flags.log_filename.get() + "': " + memFd.error());
    }

    Try<Nothing> write = os::write(memFd.get(), config);
    if (write.isError()) {
      os::close(memFd.get());
      return Error("Failed to write memfd file '" + flags.log_filename.get() +
                   "': " + write.error());
    }

    // `logrotate` requires configuration file to have 0644 or 0444 permissions.
    int ret = fchmod(memFd.get(), S_IRUSR | S_IRGRP | S_IROTH);
    if (ret == -1) {
      ErrnoError error("Failed to chmod memfd file '" +
                       flags.log_filename.get() + "'");
      os::close(memFd.get());
      return error;
    }

    configMemFd = memFd.get();
#else
    Try<Nothing> result = os::write(
        flags.log_filename.get() + CONF_SUFFIX, config);

    if (result.isError()) {
      return Error("Failed to write configuration file: " + result.error());
    }
#endif // ENABLE_LAUNCHER_SEALING

    return new LogrotateLoggerProcess(flags, configMemFd, bufferSize);
  }

  ~LogrotateLoggerProcess() override
  {
    if (configMemFd.isSome()) {
      os::close(configMemFd.get());
    }

    if (buffer != nullptr) {
      delete[] buffer;
      buffer = nullptr;
    }

    if (leading.isSome()) {
      os::close(leading.get());
    }
  }

  // Prepares and starts the loop which reads from stdin, writes to the
  // leading log file, and manages total log size.
  Future<Nothing> run()
  {
    // NOTE: This is a prerequisuite for `io::read`.
    Try<Nothing> async = io::prepare_async(STDIN_FILENO);
    if (async.isError()) {
      return Failure("Failed to set async pipe: " + async.error());
    }

    // NOTE: This does not block.
    loop();

    return promise.future();
  }

  // Reads from stdin and writes to the leading log file.
  void loop()
  {
    io::read(STDIN_FILENO, buffer, bufferSize)
      .then(defer(self(), [&](size_t readSize) -> Future<Nothing> {
        // Check if EOF has been reached on the input stream.
        // This indicates that the container (whose logs are being
        // piped to this process) has exited.
        if (readSize <= 0) {
          promise.set(Nothing());
          return Nothing();
        }

        // Do log rotation (if necessary) and write the bytes to the
        // leading log file.
        Try<Nothing> result = write(readSize);
        if (result.isError()) {
          promise.fail("Failed to write: " + result.error());
          return Nothing();
        }

        // Use `dispatch` to limit the size of the call stack.
        dispatch(self(), &LogrotateLoggerProcess::loop);

        return Nothing();
      }));
  }

  // Writes the buffer from stdin to the leading log file.
  // When the number of written bytes exceeds `--max_size`, the leading
  // log file is rotated.  When the number of log files exceed `--max_files`,
  // the oldest log file is deleted.
  Try<Nothing> write(size_t readSize)
  {
    // Rotate the log file if it will grow beyond the `--max_size`.
    if (bytesWritten + readSize > flags.max_size.bytes()) {
      rotate();
    }

    // If the leading log file is not open, open it.
    // NOTE: We open the file in append-mode as `logrotate` may sometimes fail.
    if (leading.isNone()) {
      Try<int> open = os::open(
          flags.log_filename.get(),
          O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC,
          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

      if (open.isError()) {
        return Error(
            "Failed to open '" + flags.log_filename.get() +
            "': " + open.error());
      }

      leading = open.get();
    }

    // Write from stdin to `leading`.
    // NOTE: We do not exit on error here since we are prioritizing
    // clearing the STDIN pipe (which would otherwise potentially block
    // the container on write) over log fidelity.
    Try<Nothing> result =
      os::write(leading.get(), string(buffer, readSize));

    if (result.isError()) {
      std::cerr << "Failed to write: " << result.error() << std::endl;
    }

    bytesWritten += readSize;

    return Nothing();
  }

  // Calls `logrotate` on the leading log file and resets the `bytesWritten`.
  void rotate()
  {
    if (leading.isSome()) {
      os::close(leading.get());
      leading = None();
    }

    // Call `logrotate` to move around the files.
    // NOTE: If `logrotate` fails for whatever reason, we will ignore
    // the error and continue logging.  In case the leading log file
    // is not renamed, we will continue appending to the existing
    // leading log file.
    os::shell(
        flags.logrotate_path +
        " --state \"" + flags.log_filename.get() + STATE_SUFFIX + "\" \"" +
        configPath + "\"");

    // Reset the number of bytes written.
    bytesWritten = 0;
  }

private:
  explicit LogrotateLoggerProcess(
      const Flags& _flags,
      const Option<int_fd>& _configMemFd,
      size_t _bufferSize)
    : ProcessBase(process::ID::generate("logrotate-logger")),
      flags(_flags),
      configMemFd(_configMemFd),
      buffer(new char[_bufferSize]),
      bufferSize(_bufferSize),
      leading(None()),
      bytesWritten(0)
  {
    if (configMemFd.isSome()) {
      configPath = "/proc/self/fd/" + stringify(configMemFd.get());
    } else {
      configPath = flags.log_filename.get() + CONF_SUFFIX;
    }
  }

  const Flags flags;
  const Option<int_fd> configMemFd;

  string configPath;

  // For reading from stdin.
  char* buffer;
  const size_t bufferSize;

  // For writing and rotating the leading log file.
  Option<int> leading;
  size_t bytesWritten;

  // Used to capture when log rotation has completed because the
  // underlying process/input has terminated.
  Promise<Nothing> promise;
};

int main(int argc, char** argv)
{
  Flags flags;

  // Load and validate flags from the environment and command line.
  Try<flags::Warnings> load = flags.load(None(), &argc, &argv);

  if (flags.help) {
    std::cout << flags.usage() << std::endl;
    return EXIT_SUCCESS;
  }

  if (load.isError()) {
    std::cerr << flags.usage(load.error()) << std::endl;
    return EXIT_FAILURE;
  }

  mesos::internal::logging::initialize(argv[0], false);

  // Log any flag warnings.
  foreach (const flags::Warning& warning, load->warnings) {
    LOG(WARNING) << warning.message;
  }

  // Make sure this process is running in its own session.
  // This ensures that, if the parent process (presumably the Mesos agent)
  // terminates, this logger process will continue to run.
  if (::setsid() == -1) {
    EXIT(EXIT_FAILURE)
      << ErrnoError("Failed to put child in a new session").message;
  }

  // If the `--user` flag is set, change the UID of this process to that user.
  if (flags.user.isSome()) {
    Try<Nothing> result = os::su(flags.user.get());

    if (result.isError()) {
      EXIT(EXIT_FAILURE)
        << ErrnoError("Failed to switch user for logrotate process").message;
    }
  }

  // Asynchronously control the flow and size of logs.
  Try<LogrotateLoggerProcess*> process = LogrotateLoggerProcess::create(flags);
  if (process.isError()) {
    EXIT(EXIT_FAILURE)
      << "Failed to create Logrotate process: " << process.error();
  }

  spawn(process.get());

  // Wait for the logging process to finish.
  Future<Nothing> status =
    dispatch(process.get(), &LogrotateLoggerProcess::run);

  status.await();

  terminate(process.get());
  wait(process.get());

  delete process.get();

  return status.isReady() ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>// Copyright 2020 The TensorFlow Runtime Authors
//
// 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.

// cuDNN enum parsers and printers.
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include "tfrt/gpu/wrapper/cudnn_wrapper.h"
#include "tfrt/support/fp16.h"
#include "wrapper_detail.h"

namespace tfrt {
namespace gpu {
namespace wrapper {

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnStatus_t status) {
  switch (status) {
    case CUDNN_STATUS_SUCCESS:
      return os << "CUDNN_STATUS_SUCCESS";
    case CUDNN_STATUS_NOT_INITIALIZED:
      return os << "CUDNN_STATUS_NOT_INITIALIZED";
    case CUDNN_STATUS_ALLOC_FAILED:
      return os << "CUDNN_STATUS_ALLOC_FAILED";
    case CUDNN_STATUS_BAD_PARAM:
      return os << "CUDNN_STATUS_BAD_PARAM";
    case CUDNN_STATUS_INTERNAL_ERROR:
      return os << "CUDNN_STATUS_INTERNAL_ERROR";
    case CUDNN_STATUS_INVALID_VALUE:
      return os << "CUDNN_STATUS_INVALID_VALUE";
    case CUDNN_STATUS_ARCH_MISMATCH:
      return os << "CUDNN_STATUS_ARCH_MISMATCH";
    case CUDNN_STATUS_MAPPING_ERROR:
      return os << "CUDNN_STATUS_MAPPING_ERROR";
    case CUDNN_STATUS_EXECUTION_FAILED:
      return os << "CUDNN_STATUS_EXECUTION_FAILED";
    case CUDNN_STATUS_NOT_SUPPORTED:
      return os << "CUDNN_STATUS_NOT_SUPPORTED";
    case CUDNN_STATUS_LICENSE_ERROR:
      return os << "CUDNN_STATUS_LICENSE_ERROR";
    case CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING:
      return os << "CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING";
    case CUDNN_STATUS_RUNTIME_IN_PROGRESS:
      return os << "CUDNN_STATUS_RUNTIME_IN_PROGRESS";
    case CUDNN_STATUS_RUNTIME_FP_OVERFLOW:
      return os << "CUDNN_STATUS_RUNTIME_FP_OVERFLOW";
    default:
      return os << llvm::formatv("cudnnStatus_t({0})",
                                 static_cast<int>(status));
  }
}

template <>
Expected<cudnnDataType_t> Parse<cudnnDataType_t>(llvm::StringRef name) {
  if (name == "CUDNN_DATA_FLOAT") return CUDNN_DATA_FLOAT;
  if (name == "CUDNN_DATA_DOUBLE") return CUDNN_DATA_DOUBLE;
  if (name == "CUDNN_DATA_HALF") return CUDNN_DATA_HALF;
  if (name == "CUDNN_DATA_INT8") return CUDNN_DATA_INT8;
  if (name == "CUDNN_DATA_INT32") return CUDNN_DATA_INT32;
  if (name == "CUDNN_DATA_INT8x4") return CUDNN_DATA_INT8x4;
  if (name == "CUDNN_DATA_UINT8") return CUDNN_DATA_UINT8;
  if (name == "CUDNN_DATA_UINT8x4") return CUDNN_DATA_UINT8x4;
  if (name == "CUDNN_DATA_INT8x32") return CUDNN_DATA_INT8x32;
  return MakeStringError("Unknown cudnnDataType_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnDataType_t value) {
  switch (value) {
    case CUDNN_DATA_FLOAT:
      return os << "CUDNN_DATA_FLOAT";
    case CUDNN_DATA_DOUBLE:
      return os << "CUDNN_DATA_DOUBLE";
    case CUDNN_DATA_HALF:
      return os << "CUDNN_DATA_HALF";
    case CUDNN_DATA_INT8:
      return os << "CUDNN_DATA_INT8";
    case CUDNN_DATA_UINT8:
      return os << "CUDNN_DATA_UINT8";
    case CUDNN_DATA_INT32:
      return os << "CUDNN_DATA_INT32";
    case CUDNN_DATA_INT8x4:
      return os << "CUDNN_DATA_INT8x4";
    case CUDNN_DATA_INT8x32:
      return os << "CUDNN_DATA_INT8x32";
    case CUDNN_DATA_UINT8x4:
      return os << "CUDNN_DATA_UINT8x4";
    default:
      return os << llvm::formatv("cudnnDataType_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnConvolutionMode_t> Parse<cudnnConvolutionMode_t>(
    llvm::StringRef name) {
  if (name == "CUDNN_CONVOLUTION") return CUDNN_CONVOLUTION;
  if (name == "CUDNN_CROSS_CORRELATION") return CUDNN_CROSS_CORRELATION;
  return MakeStringError("Unknown cudnnConvolutionMode_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os,
                              cudnnConvolutionMode_t value) {
  switch (value) {
    case CUDNN_CONVOLUTION:
      return os << "CUDNN_CONVOLUTION";
    case CUDNN_CROSS_CORRELATION:
      return os << "CUDNN_CROSS_CORRELATION";
    default:
      return os << llvm::formatv("cudnnConvolutionMode_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnActivationMode_t> Parse<cudnnActivationMode_t>(
    llvm::StringRef name) {
  if (name == "CUDNN_ACTIVATION_SIGMOID") return CUDNN_ACTIVATION_SIGMOID;
  if (name == "CUDNN_ACTIVATION_RELU") return CUDNN_ACTIVATION_RELU;
  if (name == "CUDNN_ACTIVATION_TANH") return CUDNN_ACTIVATION_TANH;
  if (name == "CUDNN_ACTIVATION_CLIPPED_RELU")
    return CUDNN_ACTIVATION_CLIPPED_RELU;
  if (name == "CUDNN_ACTIVATION_ELU") return CUDNN_ACTIVATION_ELU;
  if (name == "CUDNN_ACTIVATION_IDENTITY") return CUDNN_ACTIVATION_IDENTITY;
  if (name == "CUDNN_ACTIVATION_SWISH") return CUDNN_ACTIVATION_SWISH;
  return MakeStringError("Unknown cudnnActivationMode_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os,
                              cudnnActivationMode_t value) {
  switch (value) {
    case CUDNN_ACTIVATION_SIGMOID:
      return os << "CUDNN_ACTIVATION_SIGMOID";
    case CUDNN_ACTIVATION_RELU:
      return os << "CUDNN_ACTIVATION_RELU";
    case CUDNN_ACTIVATION_TANH:
      return os << "CUDNN_ACTIVATION_TANH";
    case CUDNN_ACTIVATION_CLIPPED_RELU:
      return os << "CUDNN_ACTIVATION_CLIPPED_RELU";
    case CUDNN_ACTIVATION_ELU:
      return os << "CUDNN_ACTIVATION_ELU";
    case CUDNN_ACTIVATION_IDENTITY:
      return os << "CUDNN_ACTIVATION_IDENTITY";
    case CUDNN_ACTIVATION_SWISH:
      return os << "CUDNN_ACTIVATION_SWISH";
    default:
      return os << llvm::formatv("cudnnActivationMode_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnMathType_t> Parse<cudnnMathType_t>(llvm::StringRef name) {
  if (name == "CUDNN_DEFAULT_MATH") return CUDNN_DEFAULT_MATH;
  if (name == "CUDNN_TENSOR_OP_MATH") return CUDNN_TENSOR_OP_MATH;
  if (name == "CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION")
    return CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION;
  if (name == "CUDNN_FMA_MATH") return CUDNN_FMA_MATH;
  return MakeStringError("Unknown cudnnMathType_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnMathType_t value) {
  switch (value) {
    case CUDNN_DEFAULT_MATH:
      return os << "CUDNN_DEFAULT_MATH";
    case CUDNN_TENSOR_OP_MATH:
      return os << "CUDNN_TENSOR_OP_MATH";
    case CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION:
      return os << "CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION";
    case CUDNN_FMA_MATH:
      return os << "CUDNN_FMA_MATH";
    default:
      return os << llvm::formatv("cudnnMathType_t({0})",
                                 static_cast<int>(value));
  }
}

mlir::TypeID GetCudnnDataTypeId(cudnnDataType_t data_type) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
      return mlir::TypeID::get<float>();
    case CUDNN_DATA_DOUBLE:
      return mlir::TypeID::get<double>();
    case CUDNN_DATA_HALF:
      return mlir::TypeID::get<fp16>();
    case CUDNN_DATA_INT8:
      return mlir::TypeID::get<int8_t>();
    case CUDNN_DATA_INT32:
      return mlir::TypeID::get<int32_t>();
    case CUDNN_DATA_UINT8:
      return mlir::TypeID::get<uint8_t>();
    case CUDNN_DATA_INT64:
      return mlir::TypeID::get<int64_t>();
    default:
      return {};
  }
}

std::pair<int, int> GetCudnnVectorizedSizeAndDim(cudnnDataType_t data_type) {
  int vector_size, vector_dim;
  switch (data_type) {
    case CUDNN_DATA_INT8x4:
    case CUDNN_DATA_UINT8x4:
      vector_size = 4;
      vector_dim = 1;
      break;
    case CUDNN_DATA_INT8x32:
      vector_size = 32;
      vector_dim = 1;
      break;
    default:
      vector_size = 1;
      vector_dim = -1;
      break;
  }
  return std::make_pair(vector_size, vector_dim);
}

cudnnDataType_t GetUnvectorizedCudnnDataType(cudnnDataType_t data_type) {
  switch (data_type) {
    case CUDNN_DATA_INT8x4:
    case CUDNN_DATA_INT8x32:
      return CUDNN_DATA_INT8;
    case CUDNN_DATA_UINT8x4:
      return CUDNN_DATA_UINT8;
    default:
      return data_type;
  }
}

cudnnDataType_t GetCudnnConvAccumulatorType(cudnnDataType_t data_type,
                                            bool fp32_computation_for_fp16) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
    case CUDNN_DATA_DOUBLE:
      return data_type;
    case CUDNN_DATA_HALF:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_HALF;
    case CUDNN_DATA_INT8:
    case CUDNN_DATA_INT32:
      return CUDNN_DATA_INT32;
#if CUDNN_VERSION >= 8200
    case CUDNN_DATA_BFLOAT16:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_BFLOAT16;
#endif
    default:
      assert(0 && "Invalid cudnnDataType_t");
  }
  return data_type;
}

cudnnDataType_t GetCudnnConvActivationType(cudnnDataType_t data_type,
                                           bool fp32_computation_for_fp16) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
    case CUDNN_DATA_DOUBLE:
      return data_type;
    case CUDNN_DATA_HALF:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_HALF;
    case CUDNN_DATA_INT8:
    case CUDNN_DATA_INT32:
      return CUDNN_DATA_FLOAT;
#if CUDNN_VERSION >= 8200
    case CUDNN_DATA_BFLOAT16:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_BFLOAT16;
#endif
    default:
      assert(0 && "Invalid cudnnDataType_t");
  }
  return data_type;
}

}  // namespace wrapper
}  // namespace gpu
}  // namespace tfrt
<commit_msg>Skip parsing/printing CUDNN_ACTIVATION_SWISH for cuDNN < v8.2.<commit_after>// Copyright 2020 The TensorFlow Runtime Authors
//
// 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.

// cuDNN enum parsers and printers.
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include "tfrt/gpu/wrapper/cudnn_wrapper.h"
#include "tfrt/support/fp16.h"
#include "wrapper_detail.h"

namespace tfrt {
namespace gpu {
namespace wrapper {

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnStatus_t status) {
  switch (status) {
    case CUDNN_STATUS_SUCCESS:
      return os << "CUDNN_STATUS_SUCCESS";
    case CUDNN_STATUS_NOT_INITIALIZED:
      return os << "CUDNN_STATUS_NOT_INITIALIZED";
    case CUDNN_STATUS_ALLOC_FAILED:
      return os << "CUDNN_STATUS_ALLOC_FAILED";
    case CUDNN_STATUS_BAD_PARAM:
      return os << "CUDNN_STATUS_BAD_PARAM";
    case CUDNN_STATUS_INTERNAL_ERROR:
      return os << "CUDNN_STATUS_INTERNAL_ERROR";
    case CUDNN_STATUS_INVALID_VALUE:
      return os << "CUDNN_STATUS_INVALID_VALUE";
    case CUDNN_STATUS_ARCH_MISMATCH:
      return os << "CUDNN_STATUS_ARCH_MISMATCH";
    case CUDNN_STATUS_MAPPING_ERROR:
      return os << "CUDNN_STATUS_MAPPING_ERROR";
    case CUDNN_STATUS_EXECUTION_FAILED:
      return os << "CUDNN_STATUS_EXECUTION_FAILED";
    case CUDNN_STATUS_NOT_SUPPORTED:
      return os << "CUDNN_STATUS_NOT_SUPPORTED";
    case CUDNN_STATUS_LICENSE_ERROR:
      return os << "CUDNN_STATUS_LICENSE_ERROR";
    case CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING:
      return os << "CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING";
    case CUDNN_STATUS_RUNTIME_IN_PROGRESS:
      return os << "CUDNN_STATUS_RUNTIME_IN_PROGRESS";
    case CUDNN_STATUS_RUNTIME_FP_OVERFLOW:
      return os << "CUDNN_STATUS_RUNTIME_FP_OVERFLOW";
    default:
      return os << llvm::formatv("cudnnStatus_t({0})",
                                 static_cast<int>(status));
  }
}

template <>
Expected<cudnnDataType_t> Parse<cudnnDataType_t>(llvm::StringRef name) {
  if (name == "CUDNN_DATA_FLOAT") return CUDNN_DATA_FLOAT;
  if (name == "CUDNN_DATA_DOUBLE") return CUDNN_DATA_DOUBLE;
  if (name == "CUDNN_DATA_HALF") return CUDNN_DATA_HALF;
  if (name == "CUDNN_DATA_INT8") return CUDNN_DATA_INT8;
  if (name == "CUDNN_DATA_INT32") return CUDNN_DATA_INT32;
  if (name == "CUDNN_DATA_INT8x4") return CUDNN_DATA_INT8x4;
  if (name == "CUDNN_DATA_UINT8") return CUDNN_DATA_UINT8;
  if (name == "CUDNN_DATA_UINT8x4") return CUDNN_DATA_UINT8x4;
  if (name == "CUDNN_DATA_INT8x32") return CUDNN_DATA_INT8x32;
  return MakeStringError("Unknown cudnnDataType_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnDataType_t value) {
  switch (value) {
    case CUDNN_DATA_FLOAT:
      return os << "CUDNN_DATA_FLOAT";
    case CUDNN_DATA_DOUBLE:
      return os << "CUDNN_DATA_DOUBLE";
    case CUDNN_DATA_HALF:
      return os << "CUDNN_DATA_HALF";
    case CUDNN_DATA_INT8:
      return os << "CUDNN_DATA_INT8";
    case CUDNN_DATA_UINT8:
      return os << "CUDNN_DATA_UINT8";
    case CUDNN_DATA_INT32:
      return os << "CUDNN_DATA_INT32";
    case CUDNN_DATA_INT8x4:
      return os << "CUDNN_DATA_INT8x4";
    case CUDNN_DATA_INT8x32:
      return os << "CUDNN_DATA_INT8x32";
    case CUDNN_DATA_UINT8x4:
      return os << "CUDNN_DATA_UINT8x4";
    default:
      return os << llvm::formatv("cudnnDataType_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnConvolutionMode_t> Parse<cudnnConvolutionMode_t>(
    llvm::StringRef name) {
  if (name == "CUDNN_CONVOLUTION") return CUDNN_CONVOLUTION;
  if (name == "CUDNN_CROSS_CORRELATION") return CUDNN_CROSS_CORRELATION;
  return MakeStringError("Unknown cudnnConvolutionMode_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os,
                              cudnnConvolutionMode_t value) {
  switch (value) {
    case CUDNN_CONVOLUTION:
      return os << "CUDNN_CONVOLUTION";
    case CUDNN_CROSS_CORRELATION:
      return os << "CUDNN_CROSS_CORRELATION";
    default:
      return os << llvm::formatv("cudnnConvolutionMode_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnActivationMode_t> Parse<cudnnActivationMode_t>(
    llvm::StringRef name) {
  if (name == "CUDNN_ACTIVATION_SIGMOID") return CUDNN_ACTIVATION_SIGMOID;
  if (name == "CUDNN_ACTIVATION_RELU") return CUDNN_ACTIVATION_RELU;
  if (name == "CUDNN_ACTIVATION_TANH") return CUDNN_ACTIVATION_TANH;
  if (name == "CUDNN_ACTIVATION_CLIPPED_RELU")
    return CUDNN_ACTIVATION_CLIPPED_RELU;
  if (name == "CUDNN_ACTIVATION_ELU") return CUDNN_ACTIVATION_ELU;
  if (name == "CUDNN_ACTIVATION_IDENTITY") return CUDNN_ACTIVATION_IDENTITY;
#if CUDNN_VERSION >= 8200
  if (name == "CUDNN_ACTIVATION_SWISH") return CUDNN_ACTIVATION_SWISH;
#endif
  return MakeStringError("Unknown cudnnActivationMode_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os,
                              cudnnActivationMode_t value) {
  switch (value) {
    case CUDNN_ACTIVATION_SIGMOID:
      return os << "CUDNN_ACTIVATION_SIGMOID";
    case CUDNN_ACTIVATION_RELU:
      return os << "CUDNN_ACTIVATION_RELU";
    case CUDNN_ACTIVATION_TANH:
      return os << "CUDNN_ACTIVATION_TANH";
    case CUDNN_ACTIVATION_CLIPPED_RELU:
      return os << "CUDNN_ACTIVATION_CLIPPED_RELU";
    case CUDNN_ACTIVATION_ELU:
      return os << "CUDNN_ACTIVATION_ELU";
    case CUDNN_ACTIVATION_IDENTITY:
      return os << "CUDNN_ACTIVATION_IDENTITY";
#if CUDNN_VERSION >= 8200
    case CUDNN_ACTIVATION_SWISH:
      return os << "CUDNN_ACTIVATION_SWISH";
#endif
    default:
      return os << llvm::formatv("cudnnActivationMode_t({0})",
                                 static_cast<int>(value));
  }
}

template <>
Expected<cudnnMathType_t> Parse<cudnnMathType_t>(llvm::StringRef name) {
  if (name == "CUDNN_DEFAULT_MATH") return CUDNN_DEFAULT_MATH;
  if (name == "CUDNN_TENSOR_OP_MATH") return CUDNN_TENSOR_OP_MATH;
  if (name == "CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION")
    return CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION;
  if (name == "CUDNN_FMA_MATH") return CUDNN_FMA_MATH;
  return MakeStringError("Unknown cudnnMathType_t: ", name);
}

llvm::raw_ostream& operator<<(llvm::raw_ostream& os, cudnnMathType_t value) {
  switch (value) {
    case CUDNN_DEFAULT_MATH:
      return os << "CUDNN_DEFAULT_MATH";
    case CUDNN_TENSOR_OP_MATH:
      return os << "CUDNN_TENSOR_OP_MATH";
    case CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION:
      return os << "CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION";
    case CUDNN_FMA_MATH:
      return os << "CUDNN_FMA_MATH";
    default:
      return os << llvm::formatv("cudnnMathType_t({0})",
                                 static_cast<int>(value));
  }
}

mlir::TypeID GetCudnnDataTypeId(cudnnDataType_t data_type) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
      return mlir::TypeID::get<float>();
    case CUDNN_DATA_DOUBLE:
      return mlir::TypeID::get<double>();
    case CUDNN_DATA_HALF:
      return mlir::TypeID::get<fp16>();
    case CUDNN_DATA_INT8:
      return mlir::TypeID::get<int8_t>();
    case CUDNN_DATA_INT32:
      return mlir::TypeID::get<int32_t>();
    case CUDNN_DATA_UINT8:
      return mlir::TypeID::get<uint8_t>();
    case CUDNN_DATA_INT64:
      return mlir::TypeID::get<int64_t>();
    default:
      return {};
  }
}

std::pair<int, int> GetCudnnVectorizedSizeAndDim(cudnnDataType_t data_type) {
  int vector_size, vector_dim;
  switch (data_type) {
    case CUDNN_DATA_INT8x4:
    case CUDNN_DATA_UINT8x4:
      vector_size = 4;
      vector_dim = 1;
      break;
    case CUDNN_DATA_INT8x32:
      vector_size = 32;
      vector_dim = 1;
      break;
    default:
      vector_size = 1;
      vector_dim = -1;
      break;
  }
  return std::make_pair(vector_size, vector_dim);
}

cudnnDataType_t GetUnvectorizedCudnnDataType(cudnnDataType_t data_type) {
  switch (data_type) {
    case CUDNN_DATA_INT8x4:
    case CUDNN_DATA_INT8x32:
      return CUDNN_DATA_INT8;
    case CUDNN_DATA_UINT8x4:
      return CUDNN_DATA_UINT8;
    default:
      return data_type;
  }
}

cudnnDataType_t GetCudnnConvAccumulatorType(cudnnDataType_t data_type,
                                            bool fp32_computation_for_fp16) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
    case CUDNN_DATA_DOUBLE:
      return data_type;
    case CUDNN_DATA_HALF:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_HALF;
    case CUDNN_DATA_INT8:
    case CUDNN_DATA_INT32:
      return CUDNN_DATA_INT32;
#if CUDNN_VERSION >= 8200
    case CUDNN_DATA_BFLOAT16:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_BFLOAT16;
#endif
    default:
      assert(0 && "Invalid cudnnDataType_t");
  }
  return data_type;
}

cudnnDataType_t GetCudnnConvActivationType(cudnnDataType_t data_type,
                                           bool fp32_computation_for_fp16) {
  switch (data_type) {
    case CUDNN_DATA_FLOAT:
    case CUDNN_DATA_DOUBLE:
      return data_type;
    case CUDNN_DATA_HALF:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_HALF;
    case CUDNN_DATA_INT8:
    case CUDNN_DATA_INT32:
      return CUDNN_DATA_FLOAT;
#if CUDNN_VERSION >= 8200
    case CUDNN_DATA_BFLOAT16:
      return fp32_computation_for_fp16 ? CUDNN_DATA_FLOAT : CUDNN_DATA_BFLOAT16;
#endif
    default:
      assert(0 && "Invalid cudnnDataType_t");
  }
  return data_type;
}

}  // namespace wrapper
}  // namespace gpu
}  // namespace tfrt
<|endoftext|>


<commit_before>#ifndef __STAN__AGRAD__FWD__MATRIX__DOT_PRODUCT_HPP__
#define __STAN__AGRAD__FWD__MATRIX__DOT_PRODUCT_HPP__

#include <vector>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/matrix/typedefs.hpp>
#include <stan/math/matrix/validate_vector.hpp>
#include <stan/math/matrix/validate_matching_sizes.hpp>
#include <stan/agrad/fvar.hpp>
#include <stan/agrad/fwd/matrix/typedefs.hpp>
#include <stan/agrad/fwd/matrix/to_fvar.hpp>

namespace stan {
  namespace agrad {

    //dot_product for vec (in matrix) * vec (in matrix); does all combos of row row, col col, row col, col row
    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1(i) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<T2, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1(i) * to_fvar(v2(i));
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<T1, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += to_fvar(v1(i)) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1(i) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<T2, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1(i) * to_fvar(v2(i));
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<T1, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += to_fvar(v1(i)) * v2(i);
      return ret;
    }

    //not sure what this is for..
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const var* v1, const var* v2, size_t length) {
    //   return var(new dot_product_vv_vari(v1, v2, length));
    // }
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const var* v1, const double* v2, size_t length) {
    //   return var(new dot_product_vd_vari(v1, v2, length));
    // }
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const double* v1, const var* v2, size_t length) {
    //   return var(new dot_product_vd_vari(v2, v1, length));
    // }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<fvar<T2> >& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1.at(i) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<T1>& v1,
                const std::vector<fvar<T2> >& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += to_fvar(v1.at(i)) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1, T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<T2>& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1.at(i) * to_fvar(v2.at(i));
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<fvar<T2> >& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1.at(i) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<T1>& v1,
                const std::vector<fvar<T2> >& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += to_fvar(v1.at(i)) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1, T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<T2>& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1.at(i) * to_fvar(v2.at(i));
      return ret;
    }
  }
}
#endif
<commit_msg>eliminated sign compare warning from stan/agrad/fwd/matrix/dot_product.hpp<commit_after>#ifndef __STAN__AGRAD__FWD__MATRIX__DOT_PRODUCT_HPP__
#define __STAN__AGRAD__FWD__MATRIX__DOT_PRODUCT_HPP__

#include <vector>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/matrix/typedefs.hpp>
#include <stan/math/matrix/validate_vector.hpp>
#include <stan/math/matrix/validate_matching_sizes.hpp>
#include <stan/agrad/fvar.hpp>
#include <stan/agrad/fwd/matrix/typedefs.hpp>
#include <stan/agrad/fwd/matrix/to_fvar.hpp>

namespace stan {
  namespace agrad {

    //dot_product for vec (in matrix) * vec (in matrix); does all combos of row row, col col, row col, col row
    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1(i) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<T2, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += v1(i) * to_fvar(v2(i));
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<T1, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");
      stan::math::validate_matching_sizes(v1,v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < v1.size(); i++)
        ret += to_fvar(v1(i)) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1(i) * v2(i);
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<fvar<T1>, R1, C1>& v1,
                const Eigen::Matrix<T2, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1(i) * to_fvar(v2(i));
      return ret;
    }

    template<typename T1, typename T2, int R1,int C1, int R2, int C2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const Eigen::Matrix<T1, R1, C1>& v1,
                const Eigen::Matrix<fvar<T2>, R2, C2>& v2,
                size_type& length) {
      stan::math::validate_vector(v1,"dot_product");
      stan::math::validate_vector(v2,"dot_product");

      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += to_fvar(v1(i)) * v2(i);
      return ret;
    }

    //not sure what this is for..
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const var* v1, const var* v2, size_t length) {
    //   return var(new dot_product_vv_vari(v1, v2, length));
    // }
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const var* v1, const double* v2, size_t length) {
    //   return var(new dot_product_vd_vari(v1, v2, length));
    // }
    // /**
    //  * Returns the dot product.
    //  *
    //  * @param[in] v1 First array.
    //  * @param[in] v2 Second array.
    //  * @param[in] length Length of both arrays.
    //  * @return Dot product of the arrays.
    //  */
    // inline var dot_product(const double* v1, const var* v2, size_t length) {
    //   return var(new dot_product_vd_vari(v2, v1, length));
    // }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<fvar<T2> >& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(typename std::vector<fvar<T1> >::size_type i = 0; i < v1.size(); i++)
        ret += v1.at(i) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<T1>& v1,
                const std::vector<fvar<T2> >& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(typename std::vector<T1>::size_type i = 0; i < v1.size(); i++)
        ret += to_fvar(v1.at(i)) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1, T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<T2>& v2) {
      stan::math::validate_matching_sizes(v1,v2,"dot_product");
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(typename std::vector<fvar<T1> >::size_type i = 0; i < v1.size(); i++)
        ret += v1.at(i) * to_fvar(v2.at(i));
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<fvar<T2> >& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1.at(i) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1,T2>::type>
    dot_product(const std::vector<T1>& v1,
                const std::vector<fvar<T2> >& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += to_fvar(v1.at(i)) * v2.at(i);
      return ret;
    }

    template<typename T1, typename T2>
    inline
    fvar<typename stan::return_type<T1, T2>::type>
    dot_product(const std::vector<fvar<T1> >& v1,
                const std::vector<T2>& v2,
                size_type& length) {
      fvar<typename stan::return_type<T1,T2>::type> ret(0,0);
      for(size_type i = 0; i < length; i++)
        ret += v1.at(i) * to_fvar(v2.at(i));
      return ret;
    }
  }
}
#endif
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------

#include <queso/VectorGaussianRandomField.h>

namespace QUESO {

// Default constructor -----------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::VectorGaussianRandomField(
  const char*                                                 prefix,
  const VectorSet<P_V,P_M>&                            indexSet,
  const VectorSet<Q_V,Q_M>&                            imageSetPerIndex,
  const BaseVectorFunction<P_V,P_M,Q_V,Q_M>&           meanFunction,
  const BaseMatrixCovarianceFunction<P_V,P_M,Q_V,Q_M>& covarianceFunction)
  :
  m_env                (indexSet.env()),
  m_prefix             ((std::string)(prefix)+"grf_"),
  m_indexSet           (indexSet),
  m_imageSetPerIndex   (imageSetPerIndex),
  m_meanFunction       (meanFunction),
  m_covarianceFunction (covarianceFunction),
  m_savedRvImageSpace  (NULL),
  m_savedRvLawExpVector(NULL),
  m_savedRvLawCovMatrix(NULL),
  m_savedRv            (NULL)
{
  m_savedPositions.clear();
}
// Destructor ---------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::~VectorGaussianRandomField()
{
}
// Math methods -------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const VectorSet<P_V,P_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::indexSet() const
{
  return m_indexSet;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const BaseVectorFunction<P_V,P_M,Q_V,Q_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::meanFunction() const
{
  return m_meanFunction;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const BaseMatrixCovarianceFunction<P_V,P_M,Q_V,Q_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::covarianceFunction() const
{
  return m_covarianceFunction;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
void
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction(const std::vector<P_V*>& fieldPositions, Q_V& sampleValues)
{
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "Entering VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << std::endl;
  }

  UQ_FATAL_TEST_MACRO(( sampleValues.sizeLocal() % fieldPositions.size() ) != 0,
                      m_env.fullRank(),
                      "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                      "input data is not multiple of each other");

  unsigned int numberOfImageValuesPerIndex = sampleValues.sizeLocal()/fieldPositions.size();

  UQ_FATAL_TEST_MACRO(numberOfImageValuesPerIndex != m_imageSetPerIndex.vectorSpace().dimLocal(),
                      m_env.fullRank(),
                      "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                      "invalid input data dimension");

  if ((m_savedPositions.size() == 0   ) &&
      (m_savedRvImageSpace     == NULL) &&
      (m_savedRvLawExpVector   == NULL) &&
      (m_savedRvLawCovMatrix   == NULL) &&
      (m_savedRv               == NULL)) {
    // Ok
  }
  else if ((m_savedPositions.size() != 0   ) &&
           (m_savedRvImageSpace     != NULL) &&
           (m_savedRvLawExpVector   != NULL) &&
           (m_savedRvLawCovMatrix   != NULL) &&
           (m_savedRv               != NULL)) {
    // Ok
  }
  else {
    UQ_FATAL_TEST_MACRO(true,
                        m_env.fullRank(),
                        "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                        "invalid combination of pointer values");
  }

  unsigned int numberOfPositions = fieldPositions.size();
  bool instantiate = true;
  if (m_savedPositions.size() == numberOfPositions) {
    bool allPositionsAreEqual = true;
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      UQ_FATAL_TEST_MACRO(m_savedPositions[i] == NULL,
                          m_env.fullRank(),
                          "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                          "m_savedPositions[i] should not be NULL");
      if ((m_savedPositions[i]->sizeLocal() == fieldPositions[i]->sizeLocal()) &&
          (*(m_savedPositions[i])           == *(fieldPositions[i])          )) {
        // Ok
      }
      else {
        allPositionsAreEqual = false;
        break;
      }
    } // for i
    instantiate = !allPositionsAreEqual;
  }

  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": numberOfPositions = " << numberOfPositions
                            << ", instantiate = "       << instantiate
                            << std::endl;
  }

  if (instantiate) {
    delete m_savedRv;
    delete m_savedRvLawCovMatrix;
    delete m_savedRvLawExpVector;
    delete m_savedRvImageSpace;
    for (unsigned int i = 0; i < m_savedPositions.size(); ++i) {
      delete m_savedPositions[i];
    }
    m_savedPositions.clear();

    // Set m_savedPositions
    m_savedPositions.resize(numberOfPositions,NULL);
    for (unsigned int i = 0; i < m_savedPositions.size(); ++i) {
      m_savedPositions[i] = new P_V(*(fieldPositions[i]));
    }

    // Set m_savedRvImageSpace
    m_savedRvImageSpace = new VectorSpace<Q_V,Q_M>(m_env, "grf_", numberOfPositions*numberOfImageValuesPerIndex, NULL);

    // Set m_savedRvLawExpVector
    Q_V tmpVec(m_imageSetPerIndex.vectorSpace().zeroVector());
    m_savedRvLawExpVector = new Q_V(m_savedRvImageSpace->zeroVector());
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      m_meanFunction.compute(*(fieldPositions[i]),NULL,tmpVec,NULL,NULL,NULL);
      for (unsigned int j = 0; j < numberOfImageValuesPerIndex; ++j) {
        (*m_savedRvLawExpVector)[i*numberOfImageValuesPerIndex + j] = tmpVec[j];
      }
    }

    // Set m_savedRvLawCovMatrix
    Q_M tmpMat(m_imageSetPerIndex.vectorSpace().zeroVector());
    m_savedRvLawCovMatrix = new Q_M(m_savedRvImageSpace->zeroVector());
    if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
      *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                              << ": m_savedRvLawCovMatrix order = " << m_savedRvLawCovMatrix->numCols()
                              << ", numberOfPositions = "           << numberOfPositions
                              << ", tmpMat order = "                << tmpMat.numCols()
                              << ", numberOfImageValuesPerIndex = " << numberOfImageValuesPerIndex
                              << std::endl;
    }
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      for (unsigned int j = 0; j < numberOfPositions; ++j) {
        m_covarianceFunction.covMatrix(*(fieldPositions[i]),*(fieldPositions[j]),tmpMat);
#if 1
        Q_M testMat(tmpMat);
        if (testMat.chol() != 0) {
          *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                                  << ": i = " << i
                                  << ", j = " << j
                                  << ", *(fieldPositions[i]) = " << *(fieldPositions[i])
                                  << ", *(fieldPositions[j]) = " << *(fieldPositions[j])
                                  << ", tmpMat = "               << tmpMat
                                  << ", testMat = "              << testMat
                                  << ", tmpMat is not positive definite"
                                  << std::endl;
          UQ_FATAL_TEST_MACRO(true,
                              m_env.fullRank(),
                              "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                              "tmpMat is not positive definite");
        }
#endif
        for (unsigned int k1 = 0; k1 < numberOfImageValuesPerIndex; ++k1) {
          for (unsigned int k2 = 0; k2 < numberOfImageValuesPerIndex; ++k2) {
            unsigned int tmpI = i*numberOfImageValuesPerIndex + k1;
            unsigned int tmpJ = j*numberOfImageValuesPerIndex + k2;
            (*m_savedRvLawCovMatrix)(tmpI,tmpJ) = tmpMat(k1,k2);
            if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
              *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                                      << ": i = " << i
                                      << ", j = " << j
                                      << ", k1 = " << k1
                                      << ", k2 = " << k2
                                      << ", tmpI = " << tmpI
                                      << ", tmpJ = " << tmpJ
                                      << ", *(fieldPositions[i]) = " << *(fieldPositions[i])
                                      << ", *(fieldPositions[j]) = " << *(fieldPositions[j])
                                      << ", (*m_savedRvLawCovMatrix)(tmpI,tmpJ) = " << (*m_savedRvLawCovMatrix)(tmpI,tmpJ)
                                      << std::endl;
            }
          }
        }
      }
    }

    // Set m_savedRv
    m_savedRv = new GaussianVectorRV<Q_V,Q_M>("grf_",
                                                     *m_savedRvImageSpace,
                                                     *m_savedRvLawExpVector,
                                                     *m_savedRvLawCovMatrix);

    if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
      *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                              << ": just instantiated Gaussian RV"
                              << "\n *m_savedRvLawExpVector = " << *m_savedRvLawExpVector
                              << "\n *m_savedRvLawCovMatrix = " << *m_savedRvLawCovMatrix
                              << std::endl;
      for (unsigned int i = 0; i < numberOfPositions; ++i) {
        *m_env.subDisplayFile() << " *(m_savedPositions[" << i
                                << "]) = "                << *(m_savedPositions[i])
                                << std::endl;
      }
    }
  } // if (instantiate)

  // Generate sample function
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": about to realize sample values"
                            << std::endl;
  }
  m_savedRv->realizer().realization(sampleValues);
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": just realized sample values"
                            << std::endl;
  }

  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "Leaving VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << std::endl;
  }

  return;
}

}  // End namespace QUESO
<commit_msg>Fix whitespace in licence<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------

#include <queso/VectorGaussianRandomField.h>

namespace QUESO {

// Default constructor -----------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::VectorGaussianRandomField(
  const char*                                                 prefix,
  const VectorSet<P_V,P_M>&                            indexSet,
  const VectorSet<Q_V,Q_M>&                            imageSetPerIndex,
  const BaseVectorFunction<P_V,P_M,Q_V,Q_M>&           meanFunction,
  const BaseMatrixCovarianceFunction<P_V,P_M,Q_V,Q_M>& covarianceFunction)
  :
  m_env                (indexSet.env()),
  m_prefix             ((std::string)(prefix)+"grf_"),
  m_indexSet           (indexSet),
  m_imageSetPerIndex   (imageSetPerIndex),
  m_meanFunction       (meanFunction),
  m_covarianceFunction (covarianceFunction),
  m_savedRvImageSpace  (NULL),
  m_savedRvLawExpVector(NULL),
  m_savedRvLawCovMatrix(NULL),
  m_savedRv            (NULL)
{
  m_savedPositions.clear();
}
// Destructor ---------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::~VectorGaussianRandomField()
{
}
// Math methods -------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const VectorSet<P_V,P_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::indexSet() const
{
  return m_indexSet;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const BaseVectorFunction<P_V,P_M,Q_V,Q_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::meanFunction() const
{
  return m_meanFunction;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
const BaseMatrixCovarianceFunction<P_V,P_M,Q_V,Q_M>&
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::covarianceFunction() const
{
  return m_covarianceFunction;
}
// --------------------------------------------------
template <class P_V, class P_M, class Q_V, class Q_M>
void
VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction(const std::vector<P_V*>& fieldPositions, Q_V& sampleValues)
{
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "Entering VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << std::endl;
  }

  UQ_FATAL_TEST_MACRO(( sampleValues.sizeLocal() % fieldPositions.size() ) != 0,
                      m_env.fullRank(),
                      "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                      "input data is not multiple of each other");

  unsigned int numberOfImageValuesPerIndex = sampleValues.sizeLocal()/fieldPositions.size();

  UQ_FATAL_TEST_MACRO(numberOfImageValuesPerIndex != m_imageSetPerIndex.vectorSpace().dimLocal(),
                      m_env.fullRank(),
                      "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                      "invalid input data dimension");

  if ((m_savedPositions.size() == 0   ) &&
      (m_savedRvImageSpace     == NULL) &&
      (m_savedRvLawExpVector   == NULL) &&
      (m_savedRvLawCovMatrix   == NULL) &&
      (m_savedRv               == NULL)) {
    // Ok
  }
  else if ((m_savedPositions.size() != 0   ) &&
           (m_savedRvImageSpace     != NULL) &&
           (m_savedRvLawExpVector   != NULL) &&
           (m_savedRvLawCovMatrix   != NULL) &&
           (m_savedRv               != NULL)) {
    // Ok
  }
  else {
    UQ_FATAL_TEST_MACRO(true,
                        m_env.fullRank(),
                        "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                        "invalid combination of pointer values");
  }

  unsigned int numberOfPositions = fieldPositions.size();
  bool instantiate = true;
  if (m_savedPositions.size() == numberOfPositions) {
    bool allPositionsAreEqual = true;
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      UQ_FATAL_TEST_MACRO(m_savedPositions[i] == NULL,
                          m_env.fullRank(),
                          "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                          "m_savedPositions[i] should not be NULL");
      if ((m_savedPositions[i]->sizeLocal() == fieldPositions[i]->sizeLocal()) &&
          (*(m_savedPositions[i])           == *(fieldPositions[i])          )) {
        // Ok
      }
      else {
        allPositionsAreEqual = false;
        break;
      }
    } // for i
    instantiate = !allPositionsAreEqual;
  }

  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": numberOfPositions = " << numberOfPositions
                            << ", instantiate = "       << instantiate
                            << std::endl;
  }

  if (instantiate) {
    delete m_savedRv;
    delete m_savedRvLawCovMatrix;
    delete m_savedRvLawExpVector;
    delete m_savedRvImageSpace;
    for (unsigned int i = 0; i < m_savedPositions.size(); ++i) {
      delete m_savedPositions[i];
    }
    m_savedPositions.clear();

    // Set m_savedPositions
    m_savedPositions.resize(numberOfPositions,NULL);
    for (unsigned int i = 0; i < m_savedPositions.size(); ++i) {
      m_savedPositions[i] = new P_V(*(fieldPositions[i]));
    }

    // Set m_savedRvImageSpace
    m_savedRvImageSpace = new VectorSpace<Q_V,Q_M>(m_env, "grf_", numberOfPositions*numberOfImageValuesPerIndex, NULL);

    // Set m_savedRvLawExpVector
    Q_V tmpVec(m_imageSetPerIndex.vectorSpace().zeroVector());
    m_savedRvLawExpVector = new Q_V(m_savedRvImageSpace->zeroVector());
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      m_meanFunction.compute(*(fieldPositions[i]),NULL,tmpVec,NULL,NULL,NULL);
      for (unsigned int j = 0; j < numberOfImageValuesPerIndex; ++j) {
        (*m_savedRvLawExpVector)[i*numberOfImageValuesPerIndex + j] = tmpVec[j];
      }
    }

    // Set m_savedRvLawCovMatrix
    Q_M tmpMat(m_imageSetPerIndex.vectorSpace().zeroVector());
    m_savedRvLawCovMatrix = new Q_M(m_savedRvImageSpace->zeroVector());
    if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
      *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                              << ": m_savedRvLawCovMatrix order = " << m_savedRvLawCovMatrix->numCols()
                              << ", numberOfPositions = "           << numberOfPositions
                              << ", tmpMat order = "                << tmpMat.numCols()
                              << ", numberOfImageValuesPerIndex = " << numberOfImageValuesPerIndex
                              << std::endl;
    }
    for (unsigned int i = 0; i < numberOfPositions; ++i) {
      for (unsigned int j = 0; j < numberOfPositions; ++j) {
        m_covarianceFunction.covMatrix(*(fieldPositions[i]),*(fieldPositions[j]),tmpMat);
#if 1
        Q_M testMat(tmpMat);
        if (testMat.chol() != 0) {
          *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                                  << ": i = " << i
                                  << ", j = " << j
                                  << ", *(fieldPositions[i]) = " << *(fieldPositions[i])
                                  << ", *(fieldPositions[j]) = " << *(fieldPositions[j])
                                  << ", tmpMat = "               << tmpMat
                                  << ", testMat = "              << testMat
                                  << ", tmpMat is not positive definite"
                                  << std::endl;
          UQ_FATAL_TEST_MACRO(true,
                              m_env.fullRank(),
                              "VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()",
                              "tmpMat is not positive definite");
        }
#endif
        for (unsigned int k1 = 0; k1 < numberOfImageValuesPerIndex; ++k1) {
          for (unsigned int k2 = 0; k2 < numberOfImageValuesPerIndex; ++k2) {
            unsigned int tmpI = i*numberOfImageValuesPerIndex + k1;
            unsigned int tmpJ = j*numberOfImageValuesPerIndex + k2;
            (*m_savedRvLawCovMatrix)(tmpI,tmpJ) = tmpMat(k1,k2);
            if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
              *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                                      << ": i = " << i
                                      << ", j = " << j
                                      << ", k1 = " << k1
                                      << ", k2 = " << k2
                                      << ", tmpI = " << tmpI
                                      << ", tmpJ = " << tmpJ
                                      << ", *(fieldPositions[i]) = " << *(fieldPositions[i])
                                      << ", *(fieldPositions[j]) = " << *(fieldPositions[j])
                                      << ", (*m_savedRvLawCovMatrix)(tmpI,tmpJ) = " << (*m_savedRvLawCovMatrix)(tmpI,tmpJ)
                                      << std::endl;
            }
          }
        }
      }
    }

    // Set m_savedRv
    m_savedRv = new GaussianVectorRV<Q_V,Q_M>("grf_",
                                                     *m_savedRvImageSpace,
                                                     *m_savedRvLawExpVector,
                                                     *m_savedRvLawCovMatrix);

    if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
      *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                              << ": just instantiated Gaussian RV"
                              << "\n *m_savedRvLawExpVector = " << *m_savedRvLawExpVector
                              << "\n *m_savedRvLawCovMatrix = " << *m_savedRvLawCovMatrix
                              << std::endl;
      for (unsigned int i = 0; i < numberOfPositions; ++i) {
        *m_env.subDisplayFile() << " *(m_savedPositions[" << i
                                << "]) = "                << *(m_savedPositions[i])
                                << std::endl;
      }
    }
  } // if (instantiate)

  // Generate sample function
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": about to realize sample values"
                            << std::endl;
  }
  m_savedRv->realizer().realization(sampleValues);
  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "In VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << ": just realized sample values"
                            << std::endl;
  }

  if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 3)) {
    *m_env.subDisplayFile() << "Leaving VectorGaussianRandomField<P_V,P_M,Q_V,Q_M>::sampleFunction()"
                            << std::endl;
  }

  return;
}

}  // End namespace QUESO
<|endoftext|>


<commit_before>/* ffsdumper.cpp

Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

*/

#include "ffsdumper.h"

USTATUS FfsDumper::dump(const QModelIndex & root, const QString & path, const DumpMode dumpMode, const UINT8 sectionType, const QString & guid)
{
    dumped = false;
    counter = 0;

    QDir dir;
    if (dir.cd(path))
        return U_DIR_ALREADY_EXIST;

    UINT8 result = recursiveDump(root, path, dumpMode, sectionType, guid);
    if (result)
        return result;
    else if (!dumped)
        return U_ITEM_NOT_FOUND;
    return U_SUCCESS;
}

USTATUS FfsDumper::recursiveDump(const QModelIndex & index, const QString & path, const DumpMode dumpMode, const UINT8 sectionType, const QString & guid)
{
    if (!index.isValid())
        return U_INVALID_PARAMETER;

    QDir dir;
    if (guid.isEmpty() ||
        (model->subtype(index) == EFI_SECTION_FREEFORM_SUBTYPE_GUID &&
        guidToUString(*(const EFI_GUID*)(model->header(index).constData() + sizeof(EFI_COMMON_SECTION_HEADER))) == guid) ||
        guidToUString(*(const EFI_GUID*)model->header(index).constData()) == guid ||
        guidToUString(*(const EFI_GUID*)model->header(model->findParentOfType(index, Types::File)).constData()) == guid) {

        if (!dir.cd(path) && !dir.mkpath(path))
            return U_DIR_CREATE;

        QFile file;
        if (dumpMode == DUMP_ALL || model->rowCount(index) == 0)  { // Dump if leaf item or dumpAll is true
            if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_HEADER) {
                if (!model->header(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                    if (counter == 0)
                        file.setFileName(QObject::tr("%1/header.bin").arg(path));
                    else
                        file.setFileName(QObject::tr("%1/header_%2.bin").arg(path).arg(counter));
                    counter++;
                    if (!file.open(QFile::WriteOnly))
                        return U_FILE_OPEN;

                    file.write(model->header(index));
                    file.close();
                }
            }

            if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_BODY) {
                if (!model->body(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                    if (counter == 0)
                        file.setFileName(QObject::tr("%1/body.bin").arg(path));
                    else
                        file.setFileName(QObject::tr("%1/body_%2.bin").arg(path).arg(counter));
                    counter++;
                    if (!file.open(QFile::WriteOnly))
                        return U_FILE_OPEN;

                    file.write(model->body(index));
                    file.close();
                }
            }

            if (dumpMode == DUMP_FILE && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                UModelIndex fileIndex = model->findParentOfType(index, Types::File);
                if (!fileIndex.isValid())
                    fileIndex = index;
                if (counter == 0)
                    file.setFileName(QObject::tr("%1/file.ffs").arg(path));
                else
                    file.setFileName(QObject::tr("%1/file_%2.ffs").arg(path).arg(counter));
                counter++;
                if (!file.open(QFile::WriteOnly))
                    return U_FILE_OPEN;
                file.write(model->header(fileIndex));
                file.write(model->body(fileIndex));
                file.write(model->tail(fileIndex));
                file.close();
            }
        }

        // Always dump info unless explicitly prohibited
        if ((dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_INFO)
            && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
            QString info = QObject::tr("Type: %1\nSubtype: %2\n%3%4\n")
                .arg(itemTypeToUString(model->type(index)))
                .arg(itemSubtypeToUString(model->type(index), model->subtype(index)))
                .arg(model->text(index).isEmpty() ? QObject::tr("") : QObject::tr("Text: %1\n").arg(model->text(index)))
                .arg(model->info(index));
            if (counter == 0)
                file.setFileName(QObject::tr("%1/info.txt").arg(path));
            else
                file.setFileName(QObject::tr("%1/info_%2.bin").arg(path).arg(counter));
            counter++;
            if (!file.open(QFile::Text | QFile::WriteOnly))
                return U_FILE_OPEN;

            file.write(info.toLatin1());
            file.close();
        }

        dumped = true;
    }

    UINT8 result;
    for (int i = 0; i < model->rowCount(index); i++) {
        QModelIndex childIndex = index.child(i, 0);
        bool useText = FALSE;
        if (model->type(childIndex) != Types::Volume)
            useText = !model->text(childIndex).isEmpty();

        QString childPath = path;
        if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT)
            childPath = QString("%1/%2 %3").arg(path).arg(i).arg(useText ? model->text(childIndex) : model->name(childIndex));
        result = recursiveDump(childIndex, childPath, dumpMode, sectionType, guid);
        if (result)
            return result;
    }

    return U_SUCCESS;
}
<commit_msg>Fix info extension<commit_after>/* ffsdumper.cpp

Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

*/

#include "ffsdumper.h"

USTATUS FfsDumper::dump(const QModelIndex & root, const QString & path, const DumpMode dumpMode, const UINT8 sectionType, const QString & guid)
{
    dumped = false;
    counter = 0;

    QDir dir;
    if (dir.cd(path))
        return U_DIR_ALREADY_EXIST;

    UINT8 result = recursiveDump(root, path, dumpMode, sectionType, guid);
    if (result)
        return result;
    else if (!dumped)
        return U_ITEM_NOT_FOUND;
    return U_SUCCESS;
}

USTATUS FfsDumper::recursiveDump(const QModelIndex & index, const QString & path, const DumpMode dumpMode, const UINT8 sectionType, const QString & guid)
{
    if (!index.isValid())
        return U_INVALID_PARAMETER;

    QDir dir;
    if (guid.isEmpty() ||
        (model->subtype(index) == EFI_SECTION_FREEFORM_SUBTYPE_GUID &&
        guidToUString(*(const EFI_GUID*)(model->header(index).constData() + sizeof(EFI_COMMON_SECTION_HEADER))) == guid) ||
        guidToUString(*(const EFI_GUID*)model->header(index).constData()) == guid ||
        guidToUString(*(const EFI_GUID*)model->header(model->findParentOfType(index, Types::File)).constData()) == guid) {

        if (!dir.cd(path) && !dir.mkpath(path))
            return U_DIR_CREATE;

        QFile file;
        if (dumpMode == DUMP_ALL || model->rowCount(index) == 0)  { // Dump if leaf item or dumpAll is true
            if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_HEADER) {
                if (!model->header(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                    if (counter == 0)
                        file.setFileName(QObject::tr("%1/header.bin").arg(path));
                    else
                        file.setFileName(QObject::tr("%1/header_%2.bin").arg(path).arg(counter));
                    counter++;
                    if (!file.open(QFile::WriteOnly))
                        return U_FILE_OPEN;

                    file.write(model->header(index));
                    file.close();
                }
            }

            if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_BODY) {
                if (!model->body(index).isEmpty() && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                    if (counter == 0)
                        file.setFileName(QObject::tr("%1/body.bin").arg(path));
                    else
                        file.setFileName(QObject::tr("%1/body_%2.bin").arg(path).arg(counter));
                    counter++;
                    if (!file.open(QFile::WriteOnly))
                        return U_FILE_OPEN;

                    file.write(model->body(index));
                    file.close();
                }
            }

            if (dumpMode == DUMP_FILE && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
                UModelIndex fileIndex = model->findParentOfType(index, Types::File);
                if (!fileIndex.isValid())
                    fileIndex = index;
                if (counter == 0)
                    file.setFileName(QObject::tr("%1/file.ffs").arg(path));
                else
                    file.setFileName(QObject::tr("%1/file_%2.ffs").arg(path).arg(counter));
                counter++;
                if (!file.open(QFile::WriteOnly))
                    return U_FILE_OPEN;
                file.write(model->header(fileIndex));
                file.write(model->body(fileIndex));
                file.write(model->tail(fileIndex));
                file.close();
            }
        }

        // Always dump info unless explicitly prohibited
        if ((dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT || dumpMode == DUMP_INFO)
            && (sectionType == IgnoreSectionType || model->subtype(index) == sectionType)) {
            QString info = QObject::tr("Type: %1\nSubtype: %2\n%3%4\n")
                .arg(itemTypeToUString(model->type(index)))
                .arg(itemSubtypeToUString(model->type(index), model->subtype(index)))
                .arg(model->text(index).isEmpty() ? QObject::tr("") : QObject::tr("Text: %1\n").arg(model->text(index)))
                .arg(model->info(index));
            if (counter == 0)
                file.setFileName(QObject::tr("%1/info.txt").arg(path));
            else
                file.setFileName(QObject::tr("%1/info_%2.txt").arg(path).arg(counter));
            counter++;
            if (!file.open(QFile::Text | QFile::WriteOnly))
                return U_FILE_OPEN;

            file.write(info.toLatin1());
            file.close();
        }

        dumped = true;
    }

    UINT8 result;
    for (int i = 0; i < model->rowCount(index); i++) {
        QModelIndex childIndex = index.child(i, 0);
        bool useText = FALSE;
        if (model->type(childIndex) != Types::Volume)
            useText = !model->text(childIndex).isEmpty();

        QString childPath = path;
        if (dumpMode == DUMP_ALL || dumpMode == DUMP_CURRENT)
            childPath = QString("%1/%2 %3").arg(path).arg(i).arg(useText ? model->text(childIndex) : model->name(childIndex));
        result = recursiveDump(childIndex, childPath, dumpMode, sectionType, guid);
        if (result)
            return result;
    }

    return U_SUCCESS;
}
<|endoftext|>


<commit_before>#include "EnemyPhysics.h"

#include "systems/sysPhysics.h"

#include "util/Logger.h"

#include "game/main/objects/Door.h"

EnemyPhysics::EnemyPhysics(int velocity, Rect hitBox,iGameObject *player, iComponentMediator *mediator)
    : _velocity(velocity),_hitBox(hitBox),cPhysics(mediator),_player(player)

{
    _offset = _hitBox.w/4;
    _hitBox.w -= _offset;
}

void EnemyPhysics::Move(Vector2D<int> v)
{
    _obj->pos += v;
    _obj->rect.x = _world->pos.x + _obj->pos.x + _world->offset.x;
    _obj->rect.y = _world->pos.y + _obj->pos.y + _world->offset.y;
    _hitBox.x = _obj->pos.x + _offset/2;
    _hitBox.y = _obj->pos.y;

}

EnemyPhysics::~EnemyPhysics()
{

}

void EnemyPhysics::receiveMessage(int msg)
{

}

void EnemyPhysics::Update(iGameObject *obj, Map *world, float dt)
{
    _obj = obj;
    _world = world;
    Move(obj->acc*_velocity);

    std::vector<Rect> colidables = world->getLayersRect("colidiveis");
    //Ver se está colidindo com algum gameObject
    bool colliding = false;
    for(iGameObject *i : world->gameObjects)
        if(sysPhysics::isColliding(obj->rect,i->rect))
        {
            //TODO estão colidindo mas não saem do canto

            //Se for uma porta, você deve colidir
            // senão, pode passar.
            if(i->type == "door")
            {
                //verifica se a porta está trancada
                if( !((Door *) i)->_open )
                    colliding = true;
            }

            break;
        }

    //TODO Colisão com os inimigos
    for(iGameObject *i : world->gameEnemies)
        if(sysPhysics::isColliding(obj->rect,i->rect))
        {

            colliding = true;
            break;
        }

    //Colisão com o mundo
    for(auto i : colidables)
    {
        if(sysPhysics::isColliding(_hitBox,i)
                || colliding)
        {
            Move(-obj->acc*_velocity);

            break;
        }
    }

}

<commit_msg>comentário<commit_after>#include "EnemyPhysics.h"

#include "systems/sysPhysics.h"

#include "util/Logger.h"

#include "game/main/objects/Door.h"

EnemyPhysics::EnemyPhysics(int velocity, Rect hitBox,iGameObject *player, iComponentMediator *mediator)
    : _velocity(velocity),_hitBox(hitBox),cPhysics(mediator),_player(player)

{
    _offset = _hitBox.w/4;
    _hitBox.w -= _offset;
}

void EnemyPhysics::Move(Vector2D<int> v)
{
    _obj->pos += v;
    _obj->rect.x = _world->pos.x + _obj->pos.x + _world->offset.x;
    _obj->rect.y = _world->pos.y + _obj->pos.y + _world->offset.y;
    _hitBox.x = _obj->pos.x + _offset/2;
    _hitBox.y = _obj->pos.y;

}

EnemyPhysics::~EnemyPhysics()
{

}

void EnemyPhysics::receiveMessage(int msg)
{

}

void EnemyPhysics::Update(iGameObject *obj, Map *world, float dt)
{
    _obj = obj;
    _world = world;
    Move(obj->acc*_velocity);

    std::vector<Rect> colidables = world->getLayersRect("colidiveis");
    //Ver se está colidindo com algum gameObject
    bool colliding = false;
    for(iGameObject *i : world->gameObjects)
        if(sysPhysics::isColliding(obj->rect,i->rect))
        {
            //TODO estão colidindo mas não saem do canto

            //Se for uma porta, você deve colidir
            // senão, pode passar.
            if(i->type == "door")
            {
                //verifica se a porta está trancada
                if( !((Door *) i)->_open )
                    colliding = true;
            }

            break;
        }

    //BUG Colisão com os inimigos
    for(iGameObject *i : world->gameEnemies)
        if(sysPhysics::isColliding(obj->rect,i->rect))
        {

            colliding = true;
            break;
        }

    //Colisão com o mundo
    for(auto i : colidables)
    {
        if(sysPhysics::isColliding(_hitBox,i)
                || colliding)
        {
            Move(-obj->acc*_velocity);

            break;
        }
    }

}

<|endoftext|>