<commit_before>/*
 *
 * Copyright 2015 gRPC 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.
 *
 */

// Generates Objective C gRPC service interface out of Protobuf IDL.

#include <memory>

#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"

#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>

using ::google::protobuf::compiler::objectivec::
    IsProtobufLibraryBundledProtoFile;
using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName;
using ::grpc_objective_c_generator::FrameworkImport;
using ::grpc_objective_c_generator::LocalImport;
using ::grpc_objective_c_generator::PreprocIfElse;
using ::grpc_objective_c_generator::PreprocIfNot;
using ::grpc_objective_c_generator::SystemImport;

namespace {

inline ::grpc::string ImportProtoHeaders(
    const grpc::protobuf::FileDescriptor* dep, const char* indent,
    const ::grpc::string& framework) {
  ::grpc::string header = grpc_objective_c_generator::MessageHeaderName(dep);

  if (!IsProtobufLibraryBundledProtoFile(dep)) {
    if (framework.empty()) {
      return indent + LocalImport(header);
    } else {
      return indent + FrameworkImport(header, framework);
    }
  }

  ::grpc::string base_name = header;
  grpc_generator::StripPrefix(&base_name, "google/protobuf/");
  // create the import code snippet
  ::grpc::string framework_header =
      ::grpc::string(ProtobufLibraryFrameworkName) + "/" + base_name;

  static const ::grpc::string kFrameworkImportsCondition =
      "GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS";
  return PreprocIfElse(kFrameworkImportsCondition,
                       indent + SystemImport(framework_header),
                       indent + LocalImport(header));
}

}  // namespace

class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
 public:
  ObjectiveCGrpcGenerator() {}
  virtual ~ObjectiveCGrpcGenerator() {}

 public:
  virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
                        const ::grpc::string& parameter,
                        grpc::protobuf::compiler::GeneratorContext* context,
                        ::grpc::string* error) const {
    if (file->service_count() == 0) {
      // No services.  Do nothing.
      return true;
    }

    ::grpc::string framework;
    std::vector<::grpc::string> params_list =
        grpc_generator::tokenize(parameter, ",");
    for (auto param_str = params_list.begin(); param_str != params_list.end();
         ++param_str) {
      std::vector<::grpc::string> param =
          grpc_generator::tokenize(*param_str, "=");
      if (param[0] == "generate_for_named_framework") {
        if (param.size() != 2) {
          *error =
              grpc::string("Format: generate_for_named_framework=<Framework>");
          return false;
        } else if (param[1].empty()) {
          *error = grpc::string(
                       "Name of framework cannot be empty for parameter: ") +
                   param[0];
          return false;
        }
        framework = param[1];
      }
    }

    static const ::grpc::string kNonNullBegin = "NS_ASSUME_NONNULL_BEGIN\n";
    static const ::grpc::string kNonNullEnd = "NS_ASSUME_NONNULL_END\n";
    static const ::grpc::string kProtocolOnly = "GPB_GRPC_PROTOCOL_ONLY";
    static const ::grpc::string kForwardDeclare =
        "GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO";

    ::grpc::string file_name =
        google::protobuf::compiler::objectivec::FilePath(file);

    grpc_objective_c_generator::Parameters generator_params;
    generator_params.no_v1_compatibility = false;

    if (!parameter.empty()) {
      std::vector<grpc::string> parameters_list =
          grpc_generator::tokenize(parameter, ",");
      for (auto parameter_string = parameters_list.begin();
           parameter_string != parameters_list.end(); parameter_string++) {
        std::vector<grpc::string> param =
            grpc_generator::tokenize(*parameter_string, "=");
        if (param[0] == "no_v1_compatibility") {
          generator_params.no_v1_compatibility = true;
        }
      }
    }

    {
      // Generate .pbrpc.h

      ::grpc::string imports;
      if (framework.empty()) {
        imports = LocalImport(file_name + ".pbobjc.h");
      } else {
        imports = FrameworkImport(file_name + ".pbobjc.h", framework);
      }

      ::grpc::string system_imports =
          SystemImport("ProtoRPC/ProtoService.h") +
          (generator_params.no_v1_compatibility
               ? SystemImport("ProtoRPC/ProtoRPC.h")
               : SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
      if (!generator_params.no_v1_compatibility) {
        system_imports += SystemImport("RxLibrary/GRXWriteable.h") +
                          SystemImport("RxLibrary/GRXWriter.h");
      }

      ::grpc::string forward_declarations =
          "@class GRPCUnaryProtoCall;\n"
          "@class GRPCStreamingProtoCall;\n"
          "@class GRPCCallOptions;\n"
          "@protocol GRPCProtoResponseHandler;\n";
      if (!generator_params.no_v1_compatibility) {
        forward_declarations += "@class GRPCProtoCall;\n";
      }
      forward_declarations += "\n";

      ::grpc::string class_declarations =
          grpc_objective_c_generator::GetAllMessageClasses(file);

      ::grpc::string class_imports;
      for (int i = 0; i < file->dependency_count(); i++) {
        class_imports +=
            ImportProtoHeaders(file->dependency(i), "  ", framework);
      }

      ::grpc::string ng_protocols;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        ng_protocols += grpc_objective_c_generator::GetV2Protocol(service);
      }

      ::grpc::string protocols;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        protocols +=
            grpc_objective_c_generator::GetProtocol(service, generator_params);
      }

      ::grpc::string interfaces;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        interfaces +=
            grpc_objective_c_generator::GetInterface(service, generator_params);
      }

      Write(context, file_name + ".pbrpc.h",
            PreprocIfNot(kForwardDeclare, imports) + "\n" +
                PreprocIfNot(kProtocolOnly, system_imports) + "\n" +
                class_declarations + "\n" +
                PreprocIfNot(kForwardDeclare, class_imports) + "\n" +
                forward_declarations + "\n" + kNonNullBegin + "\n" +
                ng_protocols + protocols + "\n" +
                PreprocIfNot(kProtocolOnly, interfaces) + "\n" + kNonNullEnd +
                "\n");
    }

    {
      // Generate .pbrpc.m

      ::grpc::string imports;
      if (framework.empty()) {
        imports = LocalImport(file_name + ".pbrpc.h") +
                  LocalImport(file_name + ".pbobjc.h");
      } else {
        imports = FrameworkImport(file_name + ".pbrpc.h", framework) +
                  FrameworkImport(file_name + ".pbobjc.h", framework);
      }
      imports += (generator_params.no_v1_compatibility
                      ? SystemImport("ProtoRPC/ProtoRPC.h")
                      : SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
      if (!generator_params.no_v1_compatibility) {
        imports += SystemImport("RxLibrary/GRXWriter+Immediate.h");
      }

      ::grpc::string class_imports;
      for (int i = 0; i < file->dependency_count(); i++) {
        class_imports += ImportProtoHeaders(file->dependency(i), "", framework);
      }

      ::grpc::string definitions;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        definitions +=
            grpc_objective_c_generator::GetSource(service, generator_params);
      }

      Write(context, file_name + ".pbrpc.m",
            PreprocIfNot(kProtocolOnly,
                         imports + "\n" + class_imports + "\n" + definitions));
    }

    return true;
  }

 private:
  // Write the given code into the given file.
  void Write(grpc::protobuf::compiler::GeneratorContext* context,
             const ::grpc::string& filename, const ::grpc::string& code) const {
    std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
        context->Open(filename));
    grpc::protobuf::io::CodedOutputStream coded_out(output.get());
    coded_out.WriteRaw(code.data(), code.size());
  }
};

int main(int argc, char* argv[]) {
  ObjectiveCGrpcGenerator generator;
  return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<commit_msg>objc: add autogenerated header to generated files<commit_after>/*
 *
 * Copyright 2015 gRPC 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.
 *
 */

// Generates Objective C gRPC service interface out of Protobuf IDL.

#include <memory>

#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"

#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>

using ::google::protobuf::compiler::objectivec::
    IsProtobufLibraryBundledProtoFile;
using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName;
using ::grpc_objective_c_generator::FrameworkImport;
using ::grpc_objective_c_generator::LocalImport;
using ::grpc_objective_c_generator::PreprocIfElse;
using ::grpc_objective_c_generator::PreprocIfNot;
using ::grpc_objective_c_generator::SystemImport;

namespace {

inline ::grpc::string ImportProtoHeaders(
    const grpc::protobuf::FileDescriptor* dep, const char* indent,
    const ::grpc::string& framework) {
  ::grpc::string header = grpc_objective_c_generator::MessageHeaderName(dep);

  if (!IsProtobufLibraryBundledProtoFile(dep)) {
    if (framework.empty()) {
      return indent + LocalImport(header);
    } else {
      return indent + FrameworkImport(header, framework);
    }
  }

  ::grpc::string base_name = header;
  grpc_generator::StripPrefix(&base_name, "google/protobuf/");
  // create the import code snippet
  ::grpc::string framework_header =
      ::grpc::string(ProtobufLibraryFrameworkName) + "/" + base_name;

  static const ::grpc::string kFrameworkImportsCondition =
      "GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS";
  return PreprocIfElse(kFrameworkImportsCondition,
                       indent + SystemImport(framework_header),
                       indent + LocalImport(header));
}

}  // namespace

class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
 public:
  ObjectiveCGrpcGenerator() {}
  virtual ~ObjectiveCGrpcGenerator() {}

 public:
  virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
                        const ::grpc::string& parameter,
                        grpc::protobuf::compiler::GeneratorContext* context,
                        ::grpc::string* error) const {
    if (file->service_count() == 0) {
      // No services.  Do nothing.
      return true;
    }

    ::grpc::string framework;
    std::vector<::grpc::string> params_list =
        grpc_generator::tokenize(parameter, ",");
    for (auto param_str = params_list.begin(); param_str != params_list.end();
         ++param_str) {
      std::vector<::grpc::string> param =
          grpc_generator::tokenize(*param_str, "=");
      if (param[0] == "generate_for_named_framework") {
        if (param.size() != 2) {
          *error =
              grpc::string("Format: generate_for_named_framework=<Framework>");
          return false;
        } else if (param[1].empty()) {
          *error = grpc::string(
                       "Name of framework cannot be empty for parameter: ") +
                   param[0];
          return false;
        }
        framework = param[1];
      }
    }

    static const ::grpc::string kNonNullBegin = "NS_ASSUME_NONNULL_BEGIN\n";
    static const ::grpc::string kNonNullEnd = "NS_ASSUME_NONNULL_END\n";
    static const ::grpc::string kProtocolOnly = "GPB_GRPC_PROTOCOL_ONLY";
    static const ::grpc::string kForwardDeclare =
        "GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO";

    ::grpc::string file_name =
        google::protobuf::compiler::objectivec::FilePath(file);

    grpc_objective_c_generator::Parameters generator_params;
    generator_params.no_v1_compatibility = false;

    if (!parameter.empty()) {
      std::vector<grpc::string> parameters_list =
          grpc_generator::tokenize(parameter, ",");
      for (auto parameter_string = parameters_list.begin();
           parameter_string != parameters_list.end(); parameter_string++) {
        std::vector<grpc::string> param =
            grpc_generator::tokenize(*parameter_string, "=");
        if (param[0] == "no_v1_compatibility") {
          generator_params.no_v1_compatibility = true;
        }
      }
    }

    // Write out a file header.
    ::grpc::string file_header =
        "// Code generated by gRPC proto compiler.  DO NOT EDIT!\n"
        "// source: " +
        file->name() + "\n\n";

    {
      // Generate .pbrpc.h

      ::grpc::string imports;
      if (framework.empty()) {
        imports = LocalImport(file_name + ".pbobjc.h");
      } else {
        imports = FrameworkImport(file_name + ".pbobjc.h", framework);
      }

      ::grpc::string system_imports =
          SystemImport("ProtoRPC/ProtoService.h") +
          (generator_params.no_v1_compatibility
               ? SystemImport("ProtoRPC/ProtoRPC.h")
               : SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
      if (!generator_params.no_v1_compatibility) {
        system_imports += SystemImport("RxLibrary/GRXWriteable.h") +
                          SystemImport("RxLibrary/GRXWriter.h");
      }

      ::grpc::string forward_declarations =
          "@class GRPCUnaryProtoCall;\n"
          "@class GRPCStreamingProtoCall;\n"
          "@class GRPCCallOptions;\n"
          "@protocol GRPCProtoResponseHandler;\n";
      if (!generator_params.no_v1_compatibility) {
        forward_declarations += "@class GRPCProtoCall;\n";
      }
      forward_declarations += "\n";

      ::grpc::string class_declarations =
          grpc_objective_c_generator::GetAllMessageClasses(file);

      ::grpc::string class_imports;
      for (int i = 0; i < file->dependency_count(); i++) {
        class_imports +=
            ImportProtoHeaders(file->dependency(i), "  ", framework);
      }

      ::grpc::string ng_protocols;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        ng_protocols += grpc_objective_c_generator::GetV2Protocol(service);
      }

      ::grpc::string protocols;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        protocols +=
            grpc_objective_c_generator::GetProtocol(service, generator_params);
      }

      ::grpc::string interfaces;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        interfaces +=
            grpc_objective_c_generator::GetInterface(service, generator_params);
      }

      Write(context, file_name + ".pbrpc.h",
            file_header + PreprocIfNot(kForwardDeclare, imports) + "\n" +
                PreprocIfNot(kProtocolOnly, system_imports) + "\n" +
                class_declarations + "\n" +
                PreprocIfNot(kForwardDeclare, class_imports) + "\n" +
                forward_declarations + "\n" + kNonNullBegin + "\n" +
                ng_protocols + protocols + "\n" +
                PreprocIfNot(kProtocolOnly, interfaces) + "\n" + kNonNullEnd +
                "\n");
    }

    {
      // Generate .pbrpc.m

      ::grpc::string imports;
      if (framework.empty()) {
        imports = LocalImport(file_name + ".pbrpc.h") +
                  LocalImport(file_name + ".pbobjc.h");
      } else {
        imports = FrameworkImport(file_name + ".pbrpc.h", framework) +
                  FrameworkImport(file_name + ".pbobjc.h", framework);
      }
      imports += (generator_params.no_v1_compatibility
                      ? SystemImport("ProtoRPC/ProtoRPC.h")
                      : SystemImport("ProtoRPC/ProtoRPCLegacy.h"));
      if (!generator_params.no_v1_compatibility) {
        imports += SystemImport("RxLibrary/GRXWriter+Immediate.h");
      }

      ::grpc::string class_imports;
      for (int i = 0; i < file->dependency_count(); i++) {
        class_imports += ImportProtoHeaders(file->dependency(i), "", framework);
      }

      ::grpc::string definitions;
      for (int i = 0; i < file->service_count(); i++) {
        const grpc::protobuf::ServiceDescriptor* service = file->service(i);
        definitions +=
            grpc_objective_c_generator::GetSource(service, generator_params);
      }

      Write(context, file_name + ".pbrpc.m",
            file_header +
                PreprocIfNot(kProtocolOnly, imports + "\n" + class_imports +
                                                "\n" + definitions));
    }

    return true;
  }

 private:
  // Write the given code into the given file.
  void Write(grpc::protobuf::compiler::GeneratorContext* context,
             const ::grpc::string& filename, const ::grpc::string& code) const {
    std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
        context->Open(filename));
    grpc::protobuf::io::CodedOutputStream coded_out(output.get());
    coded_out.WriteRaw(code.data(), code.size());
  }
};

int main(int argc, char* argv[]) {
  ObjectiveCGrpcGenerator generator;
  return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 3/14/2020, 9:03:01 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

int main()
{
  double A, B, C;
  cin >> A >> B >> C;
  if (sqrt(A) + sqrt(B) + epsilon < sqrt(C))
  {
    Yes();
  }
  No();
}
<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 3/14/2020, 9:03:01 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

int main()
{
  ll A, B, C;
  cin >> A >> B >> C;
  if (A + B >= C)
  {
    No();
  }
  if (4 * A * B < (C - A + B) * (C - A + B))
  {
    Yes();
  }
  No();
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/common/lag_prediction.h"

#include <algorithm>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::adapter::AdapterManager;
using apollo::perception::PerceptionObstacle;
using apollo::prediction::PredictionObstacle;
using apollo::prediction::PredictionObstacles;

LagPrediction::LagPrediction(uint32_t min_appear_num,
                             uint32_t max_disappear_num)
    : min_appear_num_(min_appear_num), max_disappear_num_(max_disappear_num) {
  if (AdapterManager::GetPredictionConfig().message_history_limit() <
      static_cast<int32_t>(min_appear_num_)) {
    AWARN << "Prediction adapter history limit is "
          << AdapterManager::GetPredictionConfig().message_history_limit()
          << ", but an obstacle need to be observed at least "
          << min_appear_num_ << " times";
    return;
  }
}

void LagPrediction::GetLaggedPrediction(PredictionObstacles* obstacles) const {
  obstacles->mutable_prediction_obstacle()->Clear();
  if (!AdapterManager::GetPrediction() ||
      AdapterManager::GetPrediction()->Empty()) {
    return;
  }
  const auto& prediction = *(AdapterManager::GetPrediction());
  if (!AdapterManager::GetLocalization() ||
      AdapterManager::GetLocalization()->Empty()) {  // no localization
    obstacles->CopyFrom(prediction.GetLatestObserved());
    return;
  }
  const auto adc_position =
      AdapterManager::GetLocalization()->GetLatestObserved().pose().position();
  const auto latest_prediction = (*prediction.begin());
  const double timestamp = latest_prediction->header().timestamp_sec();

  std::unordered_set<int> protected_obstacles;
  for (const auto& obstacle : latest_prediction->prediction_obstacle()) {
    const auto& perception = obstacle.perception_obstacle();
    if (perception.confidence() < FLAGS_perception_confidence_threshold &&
        perception.type() != PerceptionObstacle::VEHICLE) {
      continue;
    }
    double distance =
        common::util::DistanceXY(perception.position(), adc_position);
    if (distance < FLAGS_lag_prediction_protection_distance) {
      protected_obstacles.insert(obstacle.perception_obstacle().id());
      // add protected obstacle
      AddObstacleToPrediction(0.0, obstacle, obstacles);
    }
  }

  std::unordered_map<int, LagInfo> obstacle_lag_info;
  int index = 0;  // data in begin() is the most recent data
  for (auto it = prediction.begin(); it != prediction.end(); ++it, ++index) {
    for (const auto& obstacle : (*it)->prediction_obstacle()) {
      const auto& perception = obstacle.perception_obstacle();
      auto id = perception.id();
      if (perception.confidence() < FLAGS_perception_confidence_threshold &&
          perception.type() != PerceptionObstacle::VEHICLE) {
        continue;
      }
      if (protected_obstacles.count(id) > 0) {
        continue;  // don't need to count the already added protected obstacle
      }
      auto& info = obstacle_lag_info[id];
      ++info.count;
      if ((*it)->header().timestamp_sec() > info.last_observed_time) {
        info.last_observed_time = (*it)->header().timestamp_sec();
        info.last_observed_seq = index;
        info.obstacle_ptr = &obstacle;
      }
    }
  }

  obstacles->mutable_header()->CopyFrom(latest_prediction->header());
  obstacles->mutable_header()->set_module_name("lag_prediction");
  obstacles->set_perception_error_code(
      latest_prediction->perception_error_code());
  obstacles->set_start_timestamp(latest_prediction->start_timestamp());
  obstacles->set_end_timestamp(latest_prediction->end_timestamp());
  bool apply_lag = std::distance(prediction.begin(), prediction.end()) >=
                   static_cast<int32_t>(min_appear_num_);
  for (const auto& iter : obstacle_lag_info) {
    if (apply_lag && iter.second.count < min_appear_num_) {
      continue;
    }
    if (apply_lag && iter.second.last_observed_seq > max_disappear_num_) {
      continue;
    }
    AddObstacleToPrediction(timestamp - iter.second.last_observed_time,
                            *(iter.second.obstacle_ptr), obstacles);
  }
}

void LagPrediction::AddObstacleToPrediction(
    double delay_sec, const prediction::PredictionObstacle& history_obstacle,
    prediction::PredictionObstacles* obstacles) const {
  auto* obstacle = obstacles->add_prediction_obstacle();
  if (delay_sec <= 1e-6) {
    obstacle->CopyFrom(history_obstacle);
    return;
  }
  obstacle->mutable_perception_obstacle()->CopyFrom(
      history_obstacle.perception_obstacle());
  for (const auto& hist_trajectory : history_obstacle.trajectory()) {
    auto* traj = obstacle->add_trajectory();
    for (const auto& hist_point : hist_trajectory.trajectory_point()) {
      if (hist_point.relative_time() < delay_sec) {
        continue;
      }
      auto* point = traj->add_trajectory_point();
      point->CopyFrom(hist_point);
      point->set_relative_time(hist_point.relative_time() - delay_sec);
    }
    if (traj->trajectory_point_size() <= 0) {
      obstacle->mutable_trajectory()->RemoveLast();
      continue;
    }
    traj->set_probability(hist_trajectory.probability());
  }
  if (obstacle->trajectory_size() <= 0) {
    obstacles->mutable_prediction_obstacle()->RemoveLast();
    return;
  }
  obstacle->set_timestamp(history_obstacle.timestamp());
  obstacle->set_predicted_period(history_obstacle.predicted_period());
}

}  // namespace planning
}  // namespace apollo
<commit_msg>bugfix for nullptr failure.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/common/lag_prediction.h"

#include <algorithm>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::common::adapter::AdapterManager;
using apollo::perception::PerceptionObstacle;
using apollo::prediction::PredictionObstacle;
using apollo::prediction::PredictionObstacles;

LagPrediction::LagPrediction(uint32_t min_appear_num,
                             uint32_t max_disappear_num)
    : min_appear_num_(min_appear_num), max_disappear_num_(max_disappear_num) {
  if (AdapterManager::GetPredictionConfig().message_history_limit() <
      static_cast<int32_t>(min_appear_num_)) {
    AWARN << "Prediction adapter history limit is "
          << AdapterManager::GetPredictionConfig().message_history_limit()
          << ", but an obstacle need to be observed at least "
          << min_appear_num_ << " times";
    return;
  }
}

void LagPrediction::GetLaggedPrediction(PredictionObstacles* obstacles) const {
  obstacles->mutable_prediction_obstacle()->Clear();
  if (!AdapterManager::GetPrediction() ||
      AdapterManager::GetPrediction()->Empty()) {
    return;
  }
  const auto& prediction = *(AdapterManager::GetPrediction());
  if (!AdapterManager::GetLocalization() ||
      AdapterManager::GetLocalization()->Empty()) {  // no localization
    obstacles->CopyFrom(prediction.GetLatestObserved());
    return;
  }
  const auto adc_position =
      AdapterManager::GetLocalization()->GetLatestObserved().pose().position();
  const auto latest_prediction = (*prediction.begin());
  const double timestamp = latest_prediction->header().timestamp_sec();

  std::unordered_set<int> protected_obstacles;
  for (const auto& obstacle : latest_prediction->prediction_obstacle()) {
    const auto& perception = obstacle.perception_obstacle();
    if (perception.confidence() < FLAGS_perception_confidence_threshold &&
        perception.type() != PerceptionObstacle::VEHICLE) {
      continue;
    }
    double distance =
        common::util::DistanceXY(perception.position(), adc_position);
    if (distance < FLAGS_lag_prediction_protection_distance) {
      protected_obstacles.insert(obstacle.perception_obstacle().id());
      // add protected obstacle
      AddObstacleToPrediction(0.0, obstacle, obstacles);
    }
  }

  std::unordered_map<int, LagInfo> obstacle_lag_info;
  int index = 0;  // data in begin() is the most recent data
  for (auto it = prediction.begin(); it != prediction.end(); ++it, ++index) {
    for (const auto& obstacle : (*it)->prediction_obstacle()) {
      const auto& perception = obstacle.perception_obstacle();
      auto id = perception.id();
      if (perception.confidence() < FLAGS_perception_confidence_threshold &&
          perception.type() != PerceptionObstacle::VEHICLE) {
        continue;
      }
      if (protected_obstacles.count(id) > 0) {
        continue;  // don't need to count the already added protected obstacle
      }
      auto& info = obstacle_lag_info[id];
      ++info.count;
      if ((*it)->header().timestamp_sec() > info.last_observed_time) {
        info.last_observed_time = (*it)->header().timestamp_sec();
        info.last_observed_seq = index;
        info.obstacle_ptr = &obstacle;
      }
    }
  }

  obstacles->mutable_header()->CopyFrom(latest_prediction->header());
  obstacles->mutable_header()->set_module_name("lag_prediction");
  obstacles->set_perception_error_code(
      latest_prediction->perception_error_code());
  obstacles->set_start_timestamp(latest_prediction->start_timestamp());
  obstacles->set_end_timestamp(latest_prediction->end_timestamp());
  bool apply_lag = std::distance(prediction.begin(), prediction.end()) >=
                   static_cast<int32_t>(min_appear_num_);
  for (const auto& iter : obstacle_lag_info) {
    if (apply_lag && iter.second.count < min_appear_num_) {
      continue;
    }
    if (apply_lag && iter.second.last_observed_seq > max_disappear_num_) {
      continue;
    }
    AddObstacleToPrediction(timestamp - iter.second.last_observed_time,
                            *(iter.second.obstacle_ptr), obstacles);
  }
}

void LagPrediction::AddObstacleToPrediction(
    double delay_sec, const prediction::PredictionObstacle& history_obstacle,
    prediction::PredictionObstacles* obstacles) const {
  CHECK_NOTNULL(obstacles);

  auto* obstacle = obstacles->add_prediction_obstacle();
  if (obstacle == nullptr) {
    AERROR << "obstalce is nullptr.";
    return;
  }

  if (delay_sec <= 1e-6) {
    obstacle->CopyFrom(history_obstacle);
    return;
  }
  obstacle->mutable_perception_obstacle()->CopyFrom(
      history_obstacle.perception_obstacle());
  for (const auto& hist_trajectory : history_obstacle.trajectory()) {
    auto* traj = obstacle->add_trajectory();
    for (const auto& hist_point : hist_trajectory.trajectory_point()) {
      if (hist_point.relative_time() < delay_sec) {
        continue;
      }
      auto* point = traj->add_trajectory_point();
      point->CopyFrom(hist_point);
      point->set_relative_time(hist_point.relative_time() - delay_sec);
    }
    if (traj->trajectory_point_size() <= 0) {
      obstacle->mutable_trajectory()->RemoveLast();
      continue;
    }
    traj->set_probability(hist_trajectory.probability());
  }
  if (obstacle->trajectory_size() <= 0) {
    obstacles->mutable_prediction_obstacle()->RemoveLast();
    return;
  }
  obstacle->set_timestamp(history_obstacle.timestamp());
  obstacle->set_predicted_period(history_obstacle.predicted_period());
}

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


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/predictor.h"

#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

#include "Eigen/Dense"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"

namespace apollo {
namespace prediction {

using apollo::common::math::LineSegment2d;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;

const std::vector<Trajectory>& Predictor::trajectories() {
  return trajectories_;
}

int Predictor::NumOfTrajectories() { return trajectories_.size(); }

Trajectory Predictor::GenerateTrajectory(
    const std::vector<apollo::common::TrajectoryPoint>& points) {
  Trajectory trajectory;
  *trajectory.mutable_trajectory_point() = {points.begin(), points.end()};
  return trajectory;
}

void Predictor::SetEqualProbability(double probability, int start_index) {
  int num = NumOfTrajectories();
  if (start_index >= 0 && num > start_index) {
    probability /= static_cast<double>(num - start_index);
    for (int i = start_index; i < num; ++i) {
      trajectories_[i].set_probability(probability);
    }
  }
}

void Predictor::Clear() { trajectories_.clear(); }

void Predictor::TrimTrajectories(
    const Obstacle* obstacle,
    const ADCTrajectoryContainer* adc_trajectory_container) {
  for (size_t i = 0; i < trajectories_.size(); ++i) {
    TrimTrajectory(obstacle, adc_trajectory_container, &trajectories_[i]);
  }
}

bool Predictor::TrimTrajectory(
    const Obstacle* obstacle,
    const ADCTrajectoryContainer* adc_trajectory_container,
    Trajectory* trajectory) {
  if (obstacle == nullptr || obstacle->history_size() == 0) {
    AERROR << "Invalid obstacle.";
    return false;
  }
  int num_point = trajectory->trajectory_point_size();
  if (num_point == 0) {
    return false;
  }
  const Feature& feature = obstacle->latest_feature();
  double length = feature.length();
  double heading = feature.theta();
  double forward_length =
      std::max(length / 2.0 - FLAGS_distance_beyond_junction, 0.0);

  double start_x = trajectory->trajectory_point(0).path_point().x() +
                   forward_length * std::cos(heading);
  double start_y = trajectory->trajectory_point(0).path_point().y() +
                   forward_length * std::sin(heading);
  if (adc_trajectory_container->IsPointInJunction({start_x, start_y}) &&
      PredictionMap::instance()->OnVirtualLane({start_x, start_y},
                                               FLAGS_virtual_lane_radius)) {
    return false;
  }
  int index = 0;
  while (index < num_point) {
    double x = trajectory->trajectory_point(index).path_point().x();
    double y = trajectory->trajectory_point(index).path_point().y();
    if (adc_trajectory_container->IsPointInJunction({x, y})) {
      break;
    }
    if (!trajectory->trajectory_point(index).path_point().has_lane_id()) {
      continue;
    }
    const std::string& lane_id =
        trajectory->trajectory_point(index).path_point().lane_id();
    if (PredictionMap::instance()->IsVirtualLane(lane_id)) {
      break;
    }
    ++index;
  }

  // if no intersect
  if (index == num_point) {
    return false;
  }

  for (int i = index; i < num_point; ++i) {
    trajectory->mutable_trajectory_point()->RemoveLast();
  }
  return true;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Prediction: fix a bug of infinite loop (#2119)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/predictor.h"

#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

#include "Eigen/Dense"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"

namespace apollo {
namespace prediction {

using apollo::common::math::LineSegment2d;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;

const std::vector<Trajectory>& Predictor::trajectories() {
  return trajectories_;
}

int Predictor::NumOfTrajectories() { return trajectories_.size(); }

Trajectory Predictor::GenerateTrajectory(
    const std::vector<apollo::common::TrajectoryPoint>& points) {
  Trajectory trajectory;
  *trajectory.mutable_trajectory_point() = {points.begin(), points.end()};
  return trajectory;
}

void Predictor::SetEqualProbability(double probability, int start_index) {
  int num = NumOfTrajectories();
  if (start_index >= 0 && num > start_index) {
    probability /= static_cast<double>(num - start_index);
    for (int i = start_index; i < num; ++i) {
      trajectories_[i].set_probability(probability);
    }
  }
}

void Predictor::Clear() { trajectories_.clear(); }

void Predictor::TrimTrajectories(
    const Obstacle* obstacle,
    const ADCTrajectoryContainer* adc_trajectory_container) {
  for (size_t i = 0; i < trajectories_.size(); ++i) {
    TrimTrajectory(obstacle, adc_trajectory_container, &trajectories_[i]);
  }
}

bool Predictor::TrimTrajectory(
    const Obstacle* obstacle,
    const ADCTrajectoryContainer* adc_trajectory_container,
    Trajectory* trajectory) {
  if (obstacle == nullptr || obstacle->history_size() == 0) {
    AERROR << "Invalid obstacle.";
    return false;
  }
  int num_point = trajectory->trajectory_point_size();
  if (num_point == 0) {
    return false;
  }
  const Feature& feature = obstacle->latest_feature();
  double length = feature.length();
  double heading = feature.theta();
  double forward_length =
      std::max(length / 2.0 - FLAGS_distance_beyond_junction, 0.0);

  double start_x = trajectory->trajectory_point(0).path_point().x() +
                   forward_length * std::cos(heading);
  double start_y = trajectory->trajectory_point(0).path_point().y() +
                   forward_length * std::sin(heading);
  if (adc_trajectory_container->IsPointInJunction({start_x, start_y}) &&
      PredictionMap::instance()->OnVirtualLane({start_x, start_y},
                                               FLAGS_virtual_lane_radius)) {
    return false;
  }
  int index = 0;
  while (index < num_point) {
    double x = trajectory->trajectory_point(index).path_point().x();
    double y = trajectory->trajectory_point(index).path_point().y();
    if (adc_trajectory_container->IsPointInJunction({x, y})) {
      break;
    }
    if (!trajectory->trajectory_point(index).path_point().has_lane_id()) {
      ++index;
      continue;
    }
    const std::string& lane_id =
        trajectory->trajectory_point(index).path_point().lane_id();
    if (PredictionMap::instance()->IsVirtualLane(lane_id)) {
      break;
    }
    ++index;
  }

  // if no intersect
  if (index == num_point) {
    return false;
  }

  for (int i = index; i < num_point; ++i) {
    trajectory->mutable_trajectory_point()->RemoveLast();
  }
  return true;
}

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


<commit_before>#include "FlowJunction.h"
#include "Conversion.h"
#include "Simulation.h"
#include "Pipe.h"
#include "FEProblem.h"
#include "Factory.h"
#include <sstream>

template<>
InputParameters validParams<FlowJunction>()
{
  InputParameters params = validParams<Junction>();

  params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");

  params.addRequiredParam<Real>("junction_vol", "Volume of the junction");
  params.addRequiredParam<Real>("junction_gravity", "Gravity in the junction");
  params.addRequiredParam<Real>("junction_loss", "Loss in the junction");
  params.addRequiredParam<Real>("junction_area", "Area of the junction");

  params.addRequiredParam<Real>("initial_rho_junction", "Initial density in the junction");
  params.addRequiredParam<Real>("initial_rhou_junction", "Initial momentum in the junction");
  params.addRequiredParam<Real>("initial_rhoE_junction", "Initial total energy in the junction");

  return params;
}

FlowJunction::FlowJunction(const std::string & name, InputParameters params) :
    Junction(name, params),
    _junction_rho_name(genName("junction_rho", _id, "")),
    _junction_rhou_name(genName("junction_rhou", _id, "")),
    _junction_rhoE_name(genName("junction_rhoE", _id, "")),
    _p_name(genName("lm", _id, "p")),
    _T_name(genName("lm", _id, "T")),
    _junction_vol(getParam<Real>("junction_vol")),
    _junction_gravity(getParam<Real>("junction_gravity")),
    _junction_loss(getParam<Real>("junction_loss")),
    _junction_area(getParam<Real>("junction_area")),
    _initial_rho_junction(getParam<Real>("initial_rho_junction")),
    _initial_rhou_junction(getParam<Real>("initial_rhou_junction")),
    _initial_rhoE_junction(getParam<Real>("initial_rhoE_junction"))
{
}

FlowJunction::~FlowJunction()
{
}

void
FlowJunction::addVariables()
{
  // add scalar variable (the conserved variables within the junction)
  switch (_model_type)
  {
  case FlowModel::EQ_MODEL_3:
  {
    // Set initial conditions for the junction variables. Should somehow agree with
    // the initial conditions in the pipes...

    // Add three separate SCALAR junction variables with individual scaling factors
    _sim.addVariable(true, _junction_rho_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.0);
    _sim.addScalarInitialCondition(_junction_rho_name, _initial_rho_junction);

    _sim.addVariable(true, _junction_rhou_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.e-4);
    _sim.addScalarInitialCondition(_junction_rhou_name, _initial_rhou_junction);

    _sim.addVariable(true, _junction_rhoE_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.e-6);
    _sim.addScalarInitialCondition(_junction_rhoE_name, _initial_rhoE_junction);

    // Add the SCALAR pressure aux variable and an initial condition.
    _sim.addVariable(false, _p_name, FEType(FIRST,  SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
    _sim.addScalarInitialCondition(_p_name, _sim.getParam<Real>("global_init_P"));

    // Add the SCALAR temperature aux variable and an initial condition.
    _sim.addVariable(false, _T_name, FEType(FIRST,  SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
    _sim.addScalarInitialCondition(_T_name, _sim.getParam<Real>("global_init_T"));

    break;
  }

  default:
    mooseError("Not implemented yet.");
    break;
  }
}

void
FlowJunction::addMooseObjects()
{
  std::vector<std::string> cv_u(1, FlowModel::VELOCITY);
  std::vector<std::string> cv_pressure(1, FlowModel::PRESSURE);
  std::vector<std::string> cv_rho(1, FlowModel::RHO);
  std::vector<std::string> cv_rhou(1, FlowModel::RHOU);
  std::vector<std::string> cv_rhoE(1, FlowModel::RHOE);

  // Add NumericalFluxUserObject for use with FlowJunction - see
  // HeatStructure.C for another example of adding a UserObject
  {
    InputParameters params = _factory.getValidParams("NumericalFluxUserObject");
    _sim.addUserObject("NumericalFluxUserObject", "numerical_flux", params);
  }

  // add BC terms
  const std::vector<unsigned int> & boundary_ids = getBoundaryIds();
  for (unsigned int i = 0; i < boundary_ids.size(); ++i)
  {
    std::vector<unsigned int> bnd_id(1, boundary_ids[i]);

    // mass
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHO;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "CONTINUITY";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mass", _id, "_bc"), params);
    }

    // momentum
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHOU;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "MOMENTUM";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mom", _id, "_bc"), params);
    }

    // energy
    if (_model_type == FlowModel::EQ_MODEL_3)
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHOE;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos")  = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "ENERGY";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("erg", _id, "_bc"), params);
    }
  }

  // Add the constraints - add the same kernel three times,
  // associating it with a different variable each time.
  {
    // Local variables to help with the loop...
    std::vector<std::string> var_names(3), eqn_names(3), ker_names(3);
    var_names[0] = _junction_rho_name; var_names[1] = _junction_rhou_name; var_names[2] = _junction_rhoE_name;
    eqn_names[0] = "CONTINUITY";       eqn_names[1] = "MOMENTUM";          eqn_names[2] = "ENERGY";
    ker_names[0] = "rho";              ker_names[1] = "rhou";              ker_names[2] = "rhoE";

    for (unsigned v=0; v<3; ++v)
    {
      InputParameters params = _factory.getValidParams("FlowConstraint");

      params.set<NonlinearVariableName>("variable") = var_names[v];
      params.set<std::string>("eqn_name") = eqn_names[v];

      params.set<FlowModel::EModelType>("model_type") = _model_type;
      params.set<std::vector<unsigned int> >("nodes") = _nodes;
      params.set<std::vector<Real> >("areas") = _Areas;
      params.set<std::vector<Real> >("normals") = _normals;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      // coupling
      params.set<std::vector<std::string> >("u") = cv_u;
      params.set<std::vector<std::string> >("p") = cv_pressure;
      params.set<std::vector<std::string> >("rho") = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

      // junction parameters
      params.set<Real>("junction_vol")     = _junction_vol;
      params.set<Real>("junction_gravity") = _junction_gravity;
      params.set<Real>("junction_loss")    = _junction_loss;
      params.set<Real>("junction_area")    = _junction_area;

      _sim.addScalarKernel("FlowConstraint", genName(ker_names[v], _id, "_c"), params);
    }
  }

  // Add an AuxScalarKernel for the junction pressure.
  {
    InputParameters params = _factory.getValidParams("ScalarPressureAux");

    // The variable associated with this kernel.
    params.set<AuxVariableName>("variable") = _p_name;

    params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
    params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
    params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

    // And the equation of state object that the AuxScalarKernel will use.
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // Add this kernel to the Simulation object
    _sim.addAuxScalarKernel("ScalarPressureAux", genName("flow", _id, "_p"), params);
  }

  // Add an AuxScalarKernel for the junction temperature.
  {
    InputParameters params = _factory.getValidParams("ScalarTemperatureAux");

    // The variable associated with this kernel.
    params.set<AuxVariableName>("variable") = _T_name;

    params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
    params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
    params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

    // And the equation of state object that the AuxScalarKernel will use.
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // Add this kernel to the Simulation object
    _sim.addAuxScalarKernel("ScalarTemperatureAux", genName("flow", _id, "_T"), params);
  }

  // add PPS for visualization of scalar aux variables
  MooseEnum execute_options(SetupInterface::getExecuteOptions());
  execute_options = "timestep";
  {
    InputParameters params = _factory.getValidParams("PrintScalarVariable");
    params.set<VariableName>("variable") = _p_name;
    params.set<MooseEnum>("execute_on") = execute_options;
    _sim.addPostprocessor("PrintScalarVariable", "p_junction", params);
  }
  {
    InputParameters params = _factory.getValidParams("PrintScalarVariable");
    params.set<VariableName>("variable") = _T_name;
    params.set<MooseEnum>("execute_on") = execute_options;
    _sim.addPostprocessor("PrintScalarVariable", "T_junction", params);
  }
}

std::vector<unsigned int>
FlowJunction::getIDs(std::string /*piece*/)
{
  mooseError("Not implemented yet");
  return std::vector<unsigned int>();
}

std::string
FlowJunction::variableName(std::string /*piece*/)
{
  mooseError("Not implemented yet");
  return std::string();
}
<commit_msg>Output values of p and T from the FlowJunction only to a file and use a unique name, so multiple junctions will not get mixed together.<commit_after>#include "FlowJunction.h"
#include "Conversion.h"
#include "Simulation.h"
#include "Pipe.h"
#include "FEProblem.h"
#include "Factory.h"
#include <sstream>

template<>
InputParameters validParams<FlowJunction>()
{
  InputParameters params = validParams<Junction>();

  params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");

  params.addRequiredParam<Real>("junction_vol", "Volume of the junction");
  params.addRequiredParam<Real>("junction_gravity", "Gravity in the junction");
  params.addRequiredParam<Real>("junction_loss", "Loss in the junction");
  params.addRequiredParam<Real>("junction_area", "Area of the junction");

  params.addRequiredParam<Real>("initial_rho_junction", "Initial density in the junction");
  params.addRequiredParam<Real>("initial_rhou_junction", "Initial momentum in the junction");
  params.addRequiredParam<Real>("initial_rhoE_junction", "Initial total energy in the junction");

  return params;
}

FlowJunction::FlowJunction(const std::string & name, InputParameters params) :
    Junction(name, params),
    _junction_rho_name(genName("junction_rho", _id, "")),
    _junction_rhou_name(genName("junction_rhou", _id, "")),
    _junction_rhoE_name(genName("junction_rhoE", _id, "")),
    _p_name(genName("lm", _id, "p")),
    _T_name(genName("lm", _id, "T")),
    _junction_vol(getParam<Real>("junction_vol")),
    _junction_gravity(getParam<Real>("junction_gravity")),
    _junction_loss(getParam<Real>("junction_loss")),
    _junction_area(getParam<Real>("junction_area")),
    _initial_rho_junction(getParam<Real>("initial_rho_junction")),
    _initial_rhou_junction(getParam<Real>("initial_rhou_junction")),
    _initial_rhoE_junction(getParam<Real>("initial_rhoE_junction"))
{
}

FlowJunction::~FlowJunction()
{
}

void
FlowJunction::addVariables()
{
  // add scalar variable (the conserved variables within the junction)
  switch (_model_type)
  {
  case FlowModel::EQ_MODEL_3:
  {
    // Set initial conditions for the junction variables. Should somehow agree with
    // the initial conditions in the pipes...

    // Add three separate SCALAR junction variables with individual scaling factors
    _sim.addVariable(true, _junction_rho_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.0);
    _sim.addScalarInitialCondition(_junction_rho_name, _initial_rho_junction);

    _sim.addVariable(true, _junction_rhou_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.e-4);
    _sim.addScalarInitialCondition(_junction_rhou_name, _initial_rhou_junction);

    _sim.addVariable(true, _junction_rhoE_name, FEType(FIRST,  SCALAR), 0, /*scale_factor=*/1.e-6);
    _sim.addScalarInitialCondition(_junction_rhoE_name, _initial_rhoE_junction);

    // Add the SCALAR pressure aux variable and an initial condition.
    _sim.addVariable(false, _p_name, FEType(FIRST,  SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
    _sim.addScalarInitialCondition(_p_name, _sim.getParam<Real>("global_init_P"));

    // Add the SCALAR temperature aux variable and an initial condition.
    _sim.addVariable(false, _T_name, FEType(FIRST,  SCALAR), /*subdomain_id=*/0, /*scale_factor=*/1.);
    _sim.addScalarInitialCondition(_T_name, _sim.getParam<Real>("global_init_T"));

    break;
  }

  default:
    mooseError("Not implemented yet.");
    break;
  }
}

void
FlowJunction::addMooseObjects()
{
  std::vector<std::string> cv_u(1, FlowModel::VELOCITY);
  std::vector<std::string> cv_pressure(1, FlowModel::PRESSURE);
  std::vector<std::string> cv_rho(1, FlowModel::RHO);
  std::vector<std::string> cv_rhou(1, FlowModel::RHOU);
  std::vector<std::string> cv_rhoE(1, FlowModel::RHOE);

  // Add NumericalFluxUserObject for use with FlowJunction - see
  // HeatStructure.C for another example of adding a UserObject
  {
    InputParameters params = _factory.getValidParams("NumericalFluxUserObject");
    _sim.addUserObject("NumericalFluxUserObject", "numerical_flux", params);
  }

  // add BC terms
  const std::vector<unsigned int> & boundary_ids = getBoundaryIds();
  for (unsigned int i = 0; i < boundary_ids.size(); ++i)
  {
    std::vector<unsigned int> bnd_id(1, boundary_ids[i]);

    // mass
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHO;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "CONTINUITY";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mass", _id, "_bc"), params);
    }

    // momentum
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHOU;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "MOMENTUM";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("mom", _id, "_bc"), params);
    }

    // energy
    if (_model_type == FlowModel::EQ_MODEL_3)
    {
      InputParameters params = _factory.getValidParams("OneDSpecifiedFluxBC");

      params.set<NonlinearVariableName>("variable") = FlowModel::RHOE;
      params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id;
      params.set<UserObjectName>("eos")  = getParam<UserObjectName>("eos");
      params.set<std::string>("eqn_name") = "ENERGY";
      params.set<std::vector<std::string> >("u")    = cv_u;
      params.set<std::vector<std::string> >("rho")  = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      _sim.addBoundaryCondition("OneDSpecifiedFluxBC", genName("erg", _id, "_bc"), params);
    }
  }

  // Add the constraints - add the same kernel three times,
  // associating it with a different variable each time.
  {
    // Local variables to help with the loop...
    std::vector<std::string> var_names(3), eqn_names(3), ker_names(3);
    var_names[0] = _junction_rho_name; var_names[1] = _junction_rhou_name; var_names[2] = _junction_rhoE_name;
    eqn_names[0] = "CONTINUITY";       eqn_names[1] = "MOMENTUM";          eqn_names[2] = "ENERGY";
    ker_names[0] = "rho";              ker_names[1] = "rhou";              ker_names[2] = "rhoE";

    for (unsigned v=0; v<3; ++v)
    {
      InputParameters params = _factory.getValidParams("FlowConstraint");

      params.set<NonlinearVariableName>("variable") = var_names[v];
      params.set<std::string>("eqn_name") = eqn_names[v];

      params.set<FlowModel::EModelType>("model_type") = _model_type;
      params.set<std::vector<unsigned int> >("nodes") = _nodes;
      params.set<std::vector<Real> >("areas") = _Areas;
      params.set<std::vector<Real> >("normals") = _normals;
      params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");
      params.set<UserObjectName>("numerical_flux") = "numerical_flux";

      // coupling
      params.set<std::vector<std::string> >("u") = cv_u;
      params.set<std::vector<std::string> >("p") = cv_pressure;
      params.set<std::vector<std::string> >("rho") = cv_rho;
      params.set<std::vector<std::string> >("rhou") = cv_rhou;
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
      params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
      params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
      params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

      // junction parameters
      params.set<Real>("junction_vol")     = _junction_vol;
      params.set<Real>("junction_gravity") = _junction_gravity;
      params.set<Real>("junction_loss")    = _junction_loss;
      params.set<Real>("junction_area")    = _junction_area;

      _sim.addScalarKernel("FlowConstraint", genName(ker_names[v], _id, "_c"), params);
    }
  }

  // Add an AuxScalarKernel for the junction pressure.
  {
    InputParameters params = _factory.getValidParams("ScalarPressureAux");

    // The variable associated with this kernel.
    params.set<AuxVariableName>("variable") = _p_name;

    params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
    params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
    params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

    // And the equation of state object that the AuxScalarKernel will use.
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // Add this kernel to the Simulation object
    _sim.addAuxScalarKernel("ScalarPressureAux", genName("flow", _id, "_p"), params);
  }

  // Add an AuxScalarKernel for the junction temperature.
  {
    InputParameters params = _factory.getValidParams("ScalarTemperatureAux");

    // The variable associated with this kernel.
    params.set<AuxVariableName>("variable") = _T_name;

    params.set<std::vector<std::string> >("junction_rho")  = std::vector<std::string>(1, _junction_rho_name);
    params.set<std::vector<std::string> >("junction_rhou") = std::vector<std::string>(1, _junction_rhou_name);
    params.set<std::vector<std::string> >("junction_rhoE") = std::vector<std::string>(1, _junction_rhoE_name);

    // And the equation of state object that the AuxScalarKernel will use.
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // Add this kernel to the Simulation object
    _sim.addAuxScalarKernel("ScalarTemperatureAux", genName("flow", _id, "_T"), params);
  }

  // add PPS for visualization of scalar aux variables
  MooseEnum execute_options(SetupInterface::getExecuteOptions());
  execute_options = "timestep";
  {
    InputParameters params = _factory.getValidParams("PrintScalarVariable");
    params.set<VariableName>("variable") = _p_name;
    params.set<MooseEnum>("output") = "file";
    params.set<MooseEnum>("execute_on") = execute_options;
    _sim.addPostprocessor("PrintScalarVariable", genName(name(), "p"), params);
  }
  {
    InputParameters params = _factory.getValidParams("PrintScalarVariable");
    params.set<VariableName>("variable") = _T_name;
    params.set<MooseEnum>("execute_on") = execute_options;
    params.set<MooseEnum>("output") = "file";
    _sim.addPostprocessor("PrintScalarVariable", genName(name(), "T"), params);
  }
}

std::vector<unsigned int>
FlowJunction::getIDs(std::string /*piece*/)
{
  mooseError("Not implemented yet");
  return std::vector<unsigned int>();
}

std::string
FlowJunction::variableName(std::string /*piece*/)
{
  mooseError("Not implemented yet");
  return std::string();
}
<|endoftext|>


<commit_before>// Time:  O(logn * nlogx * logx) = O(1)
// Space: O(nlogx) = O(1)

class Solution {
public:
    double myPow(double x, int n) {
        double result = 1;
        long long abs_n = abs(static_cast<long long>(n));
        while (abs_n > 0) {
            if (abs_n & 1) {
                result *= x;
            }
            abs_n >>= 1;
            x *= x;
        }
        return n < 0 ? 1 / result : result;
    }
};

// Time:  O(logn * nlogx * logx) = O(1)
// Space: O(nlogx) = O(1)
// Recursive solution.
class Solution2 {
public:
    double myPow(double x, int n) {
        if (n < 0 && n != -n) {
            return 1.0 / myPow(x, -n);
        }
        if (n == 0) {
            return 1;
        }
        double v = myPow(x, n / 2);
        if (n % 2 == 0) {
            return v * v;
        } else {
            return v * v * x;
        }
    }
};
<commit_msg>Update powx-n.cpp<commit_after>// Time:  O(logn)
// Space: O(1)

class Solution {
public:
    double myPow(double x, int n) {
        double result = 1;
        long long abs_n = abs(static_cast<long long>(n));
        while (abs_n > 0) {
            if (abs_n & 1) {
                result *= x;
            }
            abs_n >>= 1;
            x *= x;
        }
        return n < 0 ? 1 / result : result;
    }
};

// Time:  O(logn)
// Space: O(logn)
// Recursive solution.
class Solution2 {
public:
    double myPow(double x, int n) {
        if (n < 0 && n != -n) {
            return 1.0 / myPow(x, -n);
        }
        if (n == 0) {
            return 1;
        }
        double v = myPow(x, n / 2);
        if (n % 2 == 0) {
            return v * v;
        } else {
            return v * v * x;
        }
    }
};
<|endoftext|>