<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#pragma once

#include <cstdint>
#include "math/Vector2.hpp"
#include "math/Size2.hpp"

namespace ouzel
{
    const float TAU = 6.28318530717958647692F;
    const float TAU_2 = 3.14159265358979323846F; // tau/2, the same as pi
    const float TAU_4 = 1.57079632679489661923F; // tau/4, the same as pi/2
    const float PI = 3.14159265358979323846F;
    const float PI_2 = 1.57079632679489661923F; // pi/2
    const float PI_4 = 0.78539816339744830962F; // pi/4
    const float FLOAT_SMALL = 1.0e-37F;
    const float TOLERANCE = 2e-37F;
    const float E = 2.71828182845904523536F;
    const float LOG10E = 0.4342944819032518F;
    const float LOG2E = 1.442695040888963387F;
    const float PIX2 = 6.28318530717958647693F;
    const float EPSILON = 0.000001F;
    const float SQRT2 = 1.4142135623730950488F;

    inline float lerp(float v0, float v1, float t)
    {
        return (1.0F - t) * v0 + t * v1;
    }

    inline float smoothStep(float a, float b, float t)
    {
        float remapSmoothStep = t * t * (3 - 2 * t);
        return lerp(a, b, remapSmoothStep);
    }

    inline bool isPOT(uint32_t x)
    {
        return (x != 0) && (((x - 1) & x) == 0);
    }

    inline uint32_t nextPOT(uint32_t x)
    {
        x = x - 1;
        x = x | (x >> 1);
        x = x | (x >> 2);
        x = x | (x >> 4);
        x = x | (x >> 8);
        x = x | (x >>16);
        return x + 1;
    }

    template<typename T> inline int sgn(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    inline float degToRad(float x)
    {
        return x * 0.0174532925F;
    }

    inline float radToDeg(float x)
    {
        return x * 57.29577951F;
    }

    template<class T>
    inline T clamp(T x, T lo, T hi)
    {
        return (x < lo) ? lo : ((x > hi) ? hi : x);
    }

    static const uint64_t INITIAL_FNV = 2166136261U;
    static const uint64_t FNV_MULTIPLE = 16777619;

    // Fowler / Noll / Vo (FNV) hash
    inline uint64_t fnvHash(uint64_t s)
    {
        uint64_t hash = INITIAL_FNV;
        for (uint64_t i = 0; i < sizeof(uint64_t); i++)
        {
            hash = hash ^ (reinterpret_cast<uint8_t*>(&s)[i]); // xor the low 8 bits
            hash = hash * FNV_MULTIPLE; // multiply by the magic number
        }
        return hash;
    }
}
<commit_msg>Remove unneeded includes from MathUtils.hpp<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#pragma once

#include <cstdint>

namespace ouzel
{
    const float TAU = 6.28318530717958647692F;
    const float TAU_2 = 3.14159265358979323846F; // tau/2, the same as pi
    const float TAU_4 = 1.57079632679489661923F; // tau/4, the same as pi/2
    const float PI = 3.14159265358979323846F;
    const float PI_2 = 1.57079632679489661923F; // pi/2
    const float PI_4 = 0.78539816339744830962F; // pi/4
    const float FLOAT_SMALL = 1.0e-37F;
    const float TOLERANCE = 2e-37F;
    const float E = 2.71828182845904523536F;
    const float LOG10E = 0.4342944819032518F;
    const float LOG2E = 1.442695040888963387F;
    const float PIX2 = 6.28318530717958647693F;
    const float EPSILON = 0.000001F;
    const float SQRT2 = 1.4142135623730950488F;

    inline float lerp(float v0, float v1, float t)
    {
        return (1.0F - t) * v0 + t * v1;
    }

    inline float smoothStep(float a, float b, float t)
    {
        float remapSmoothStep = t * t * (3 - 2 * t);
        return lerp(a, b, remapSmoothStep);
    }

    inline bool isPOT(uint32_t x)
    {
        return (x != 0) && (((x - 1) & x) == 0);
    }

    inline uint32_t nextPOT(uint32_t x)
    {
        x = x - 1;
        x = x | (x >> 1);
        x = x | (x >> 2);
        x = x | (x >> 4);
        x = x | (x >> 8);
        x = x | (x >>16);
        return x + 1;
    }

    template<typename T> inline int sgn(T val)
    {
        return (T(0) < val) - (val < T(0));
    }

    inline float degToRad(float x)
    {
        return x * 0.0174532925F;
    }

    inline float radToDeg(float x)
    {
        return x * 57.29577951F;
    }

    template<class T>
    inline T clamp(T x, T lo, T hi)
    {
        return (x < lo) ? lo : ((x > hi) ? hi : x);
    }

    static const uint64_t INITIAL_FNV = 2166136261U;
    static const uint64_t FNV_MULTIPLE = 16777619;

    // Fowler / Noll / Vo (FNV) hash
    inline uint64_t fnvHash(uint64_t s)
    {
        uint64_t hash = INITIAL_FNV;
        for (uint64_t i = 0; i < sizeof(uint64_t); i++)
        {
            hash = hash ^ (reinterpret_cast<uint8_t*>(&s)[i]); // xor the low 8 bits
            hash = hash * FNV_MULTIPLE; // multiply by the magic number
        }
        return hash;
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 <Python.h>
#include <fstream>
#include <vector>

#include "paddle/framework/backward.h"
#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/op_registry.h"
#include "paddle/operators/cond_op.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
#include "paddle/platform/enforce.h"
#include "paddle/platform/place.h"
#include "paddle/pybind/pybind.h"
#include "paddle/pybind/tensor_py.h"
#include "paddle/string/to_string.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"

namespace py = pybind11;

namespace paddle {
namespace framework {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

static size_t UniqueIntegerGenerator() {
  static std::atomic<size_t> generator;
  return generator.fetch_add(1);
}

bool IsCompileGPU() {
#ifdef PADDLE_ONLY_CPU
  return false;
#else
  return true;
#endif
}

PYBIND11_PLUGIN(core) {
  py::module m("core", "C++ core of PaddlePaddle");

  py::class_<Tensor>(m, "Tensor", py::buffer_protocol())
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def("get_dims",
           [](const Tensor &self) { return vectorize(self.dims()); })
      .def("set_dims",
           [](Tensor &self, const std::vector<int64_t> &dim) {
             self.Resize(make_ddim(dim));
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("set", PyCPUTensorSetFromArray<float>)
      .def("set", PyCPUTensorSetFromArray<int>)
#ifndef PADDLE_ONLY_CPU
      .def("set", PyCUDATensorSetFromArray<float>)
      .def("set", PyCUDATensorSetFromArray<int>)
#endif
      .def("shape", [](Tensor &self) { return vectorize(self.dims()); })
      .def("set_float_element",
           [](Tensor &self, size_t offset, float f) {
             // TODO(yuyang18): Only support GPU now.
             self.data<float>()[offset] = f;
           })
      .def("get_float_element", [](Tensor &self, size_t offset) -> float {
        // TODO(yuyang18): Only support GPU now.
        return self.data<float>()[offset];
      });

  py::class_<LoDTensor, Tensor>(m, "LoDTensor")
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def(
          "__init__",
          [](LoDTensor &instance, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
            new (&instance) LoDTensor(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             new (&instance) LoDTensor(new_lod);
#endif
          })
      .def("set_lod",
           [](LoDTensor &self, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
             self.set_lod(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             self.set_lod(new_lod);
#endif
           })
      .def("lod", [](LoDTensor &self) -> std::vector<std::vector<size_t>> {
#ifdef PADDLE_ONLY_CPU
        return self.lod();
#else
           auto lod = self.lod();
           std::vector<std::vector<size_t>> new_lod;
           new_lod.reserve(lod.size());
           std::transform(lod.begin(), lod.end(), std::back_inserter(new_lod),
               [](paddle::framework::Vector<size_t> item) ->
                   std::vector<size_t> {
                 std::vector<size_t> v;
                 v.reserve(item.size());
                 std::copy(item.begin(), item.end(), std::back_inserter(v));
                 return v;
               });
           return new_lod;
#endif
      });

  py::class_<Variable>(m, "Variable", R"DOC(Variable Class.

All parameter, weight, gradient are variables in Paddle.
)DOC")
      .def("is_int", [](const Variable &var) { return var.IsType<int>(); })
      .def("set_int",
           [](Variable &var, int val) -> void { *var.GetMutable<int>() = val; })
      .def("get_int", [](const Variable &var) -> int { return var.Get<int>(); })
      .def("get_tensor",
           [](Variable &self) -> LoDTensor * {
             return self.GetMutable<LoDTensor>();
           },
           py::return_value_policy::reference)
      .def("get_net",
           [](Variable &self) -> operators::NetOp * {
             return self.GetMutable<operators::NetOp>();
           },
           py::return_value_policy::reference);

  py::class_<Scope>(m, "Scope", "")
      .def("new_var",
           [](Scope &self, const std::string &name) -> Variable * {
             return self.NewVar(name);
           },
           py::return_value_policy::reference)
      .def("find_var", &Scope::FindVar, py::return_value_policy::reference)
      .def(py::init<>())
      .def("new_scope",
           [](Scope &self) -> Scope * { return &self.NewScope(); },
           py::return_value_policy::reference)
      .def("drop_kids", &Scope::DropKids);

  //! @note: Be careful! PyBind will return std::string as an unicode, not
  //! Python str. If you want a str object, you should cast them in Python.
  m.def("get_all_op_protos", []() -> std::vector<py::bytes> {
    std::vector<py::bytes> ret_values;

    OpInfoMap::Instance().IterAllInfo([&ret_values](const std::string &type,
                                                    const OpInfo &info) {
      if (!info.HasOpProtoAndChecker()) return;
      std::string str;
      PADDLE_ENFORCE(info.Proto().SerializeToString(&str),
                     "Serialize OpProto Error. This could be a bug of Paddle.");
      ret_values.emplace_back(str);
    });
    return ret_values;
  });
  m.def_submodule(
       "var_names",
       "The module will return special predefined variable name in Paddle")
      .def("empty", []() { return kEmptyVarName; })
      .def("temp", []() { return kTempVarName; });
  // clang-format off
  py::class_<paddle::platform::DeviceContext>(m, "DeviceContext")
      .def_static("create",
                  [](paddle::platform::CPUPlace& place)
                      -> paddle::platform::DeviceContext* {
                    return new paddle::platform::CPUDeviceContext();
                  })
      .def_static("create",
                  [](paddle::platform::GPUPlace& place)
                      -> paddle::platform::DeviceContext* {
#ifdef PADDLE_ONLY_CPU
                    PADDLE_THROW("GPUPlace is not supported in CPU device.");
#else
                    return new paddle::platform::CUDADeviceContext(place);
#endif
                  });
  // clang-format on

  py::class_<platform::GPUPlace>(m, "GPUPlace")
      .def(py::init<int>())
      .def("__str__", string::to_string<const platform::GPUPlace &>);

  py::class_<paddle::platform::CPUPlace>(m, "CPUPlace")
      .def(py::init<>())
      .def("__str__", string::to_string<const platform::CPUPlace &>);

  py::class_<OperatorBase>(m, "Operator")
      .def_static("create",
                  [](py::bytes protobin) {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    return OpRegistry::CreateOp(desc);
                  })
      .def("backward",
           [](const OperatorBase &forwardOp,
              const std::unordered_set<std::string> &no_grad_vars) {
             return Backward(forwardOp, no_grad_vars).release();
           })
      .def("infer_shape", &OperatorBase::InferShape)
      .def("run", &OperatorBase::Run)
      .def("type",
           [](const OperatorBase &op) -> std::string { return op.Type(); })
      .def("outputs",
           [](const OperatorBase &op)
               -> std::map<std::string, std::vector<std::string>> {
                 return op.Outputs();
               })
      .def("output_vars",
           [](const OperatorBase &op) { return op.OutputVars(true); })
      .def("inputs", [](const OperatorBase &op) { return op.Inputs(); })
      .def("input_vars", [](const OperatorBase &op) { return op.InputVars(); })
      .def("__str__", &OperatorBase::DebugString)
      .def("no_intermediate_outputs",
           [](const OperatorBase &op) { return op.OutputVars(false); })
      .def("support_gpu", &OperatorBase::SupportGPU);

  py::class_<operators::NetOp, OperatorBase>(m, "Net")
      .def_static("create",
                  []() -> operators::NetOp * {
                    auto *retv = new operators::NetOp;
                    retv->SetType("plain_net");
                    return retv;
                  })
      .def("append_op",
           [](operators::NetOp &self, const OperatorBase &op) {
             self.AppendOp(op);
           })
      .def("complete_add_op", &operators::NetOp::CompleteAddOp)
      .def("complete_add_op", [](std::shared_ptr<operators::NetOp> &self) {
        self->CompleteAddOp();
      });

  // recurrent_op
  py::class_<operators::RecurrentOp, OperatorBase>(m, "RecurrentOp")
      .def_static(
          "create",
          [](py::bytes protobin) -> operators::RecurrentOp * {
            OpDesc desc;
            PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                           "Cannot parse user input to OpDesc");
            PADDLE_ENFORCE(desc.IsInitialized(),
                           "User OpDesc is not initialized, reason %s",
                           desc.InitializationErrorString());
            auto rnn_op = OpRegistry::CreateOp(desc);
            return static_cast<operators::RecurrentOp *>(rnn_op.release());
          })
      .def("set_stepnet",
           [](operators::RecurrentOp &self, const operators::NetOp &net)
               -> void { self.set_stepnet(net.Clone()); });

  // cond_op
  py::class_<operators::CondOp, OperatorBase>(m, "CondOp")
      .def_static("create",
                  [](py::bytes protobin) -> operators::CondOp * {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    auto cond_op = OpRegistry::CreateOp(desc);
                    return static_cast<operators::CondOp *>(cond_op.release());
                  })
      .def("set_truenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_truenet(net.Clone());
           })
      .def("set_falsenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_falsenet(net.Clone());
           });

  m.def("unique_integer", UniqueIntegerGenerator);

  m.def("is_compile_gpu", IsCompileGPU);

  py::class_<ProgramDesc>(m, "ProgramDesc", "")
      .def_static("instance", [] { return &GetProgramDesc(); })
      .def("append_block", [](ProgramDesc &self) {
        auto desc = self.mutable_blocks()->Add();
        desc->set_idx(self.mutable_blocks()->size() - 1);
        return desc;
      });
  py::class_<BlockDesc>(m, "BlockDesc", "")
      .def("idx", [](BlockDesc &self) { return self.idx(); })
      .def("set_parent",
           [](BlockDesc &self, int32_t idx) { self.set_parent_idx(idx); })
      .def("parent", [](BlockDesc &self) { return self.parent_idx(); });

  py::class_<VarDesc>(m, "VarDesc", "");

  py::class_<OpDesc>(m, "OpDesc", "");

  return m.ptr();
}
}  // namespace framework
}  // namespace paddle
<commit_msg>Expose VarDesc interface<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 <Python.h>
#include <fstream>
#include <vector>

#include "paddle/framework/backward.h"
#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/op_registry.h"
#include "paddle/operators/cond_op.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
#include "paddle/platform/enforce.h"
#include "paddle/platform/place.h"
#include "paddle/pybind/pybind.h"
#include "paddle/pybind/tensor_py.h"
#include "paddle/string/to_string.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"

namespace py = pybind11;

namespace paddle {
namespace framework {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using LoD = framework::LoD;

static size_t UniqueIntegerGenerator() {
  static std::atomic<size_t> generator;
  return generator.fetch_add(1);
}

bool IsCompileGPU() {
#ifdef PADDLE_ONLY_CPU
  return false;
#else
  return true;
#endif
}

PYBIND11_PLUGIN(core) {
  py::module m("core", "C++ core of PaddlePaddle");

  py::class_<Tensor>(m, "Tensor", py::buffer_protocol())
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def("get_dims",
           [](const Tensor &self) { return vectorize(self.dims()); })
      .def("set_dims",
           [](Tensor &self, const std::vector<int64_t> &dim) {
             self.Resize(make_ddim(dim));
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_float",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<float>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::CPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("alloc_int",
           [](Tensor &self, paddle::platform::GPUPlace &place) {
             self.mutable_data<int>(place);
           })
      .def("set", PyCPUTensorSetFromArray<float>)
      .def("set", PyCPUTensorSetFromArray<int>)
#ifndef PADDLE_ONLY_CPU
      .def("set", PyCUDATensorSetFromArray<float>)
      .def("set", PyCUDATensorSetFromArray<int>)
#endif
      .def("shape", [](Tensor &self) { return vectorize(self.dims()); })
      .def("set_float_element",
           [](Tensor &self, size_t offset, float f) {
             // TODO(yuyang18): Only support GPU now.
             self.data<float>()[offset] = f;
           })
      .def("get_float_element", [](Tensor &self, size_t offset) -> float {
        // TODO(yuyang18): Only support GPU now.
        return self.data<float>()[offset];
      });

  py::class_<LoDTensor, Tensor>(m, "LoDTensor")
      .def_buffer(
          [](Tensor &self) -> py::buffer_info { return CastToPyBuffer(self); })
      .def(
          "__init__",
          [](LoDTensor &instance, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
            new (&instance) LoDTensor(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             new (&instance) LoDTensor(new_lod);
#endif
          })
      .def("set_lod",
           [](LoDTensor &self, const std::vector<std::vector<size_t>> &lod) {
#ifdef PADDLE_ONLY_CPU
             self.set_lod(lod);
#else
             paddle::framework::LoD new_lod;
             new_lod.reserve(lod.size());
             std::copy(lod.begin(), lod.end(), std::back_inserter(new_lod));
             self.set_lod(new_lod);
#endif
           })
      .def("lod", [](LoDTensor &self) -> std::vector<std::vector<size_t>> {
#ifdef PADDLE_ONLY_CPU
        return self.lod();
#else
           auto lod = self.lod();
           std::vector<std::vector<size_t>> new_lod;
           new_lod.reserve(lod.size());
           std::transform(lod.begin(), lod.end(), std::back_inserter(new_lod),
               [](paddle::framework::Vector<size_t> item) ->
                   std::vector<size_t> {
                 std::vector<size_t> v;
                 v.reserve(item.size());
                 std::copy(item.begin(), item.end(), std::back_inserter(v));
                 return v;
               });
           return new_lod;
#endif
      });

  py::class_<Variable>(m, "Variable", R"DOC(Variable Class.

All parameter, weight, gradient are variables in Paddle.
)DOC")
      .def("is_int", [](const Variable &var) { return var.IsType<int>(); })
      .def("set_int",
           [](Variable &var, int val) -> void { *var.GetMutable<int>() = val; })
      .def("get_int", [](const Variable &var) -> int { return var.Get<int>(); })
      .def("get_tensor",
           [](Variable &self) -> LoDTensor * {
             return self.GetMutable<LoDTensor>();
           },
           py::return_value_policy::reference)
      .def("get_net",
           [](Variable &self) -> operators::NetOp * {
             return self.GetMutable<operators::NetOp>();
           },
           py::return_value_policy::reference);

  py::class_<Scope>(m, "Scope", "")
      .def("new_var",
           [](Scope &self, const std::string &name) -> Variable * {
             return self.NewVar(name);
           },
           py::return_value_policy::reference)
      .def("find_var", &Scope::FindVar, py::return_value_policy::reference)
      .def(py::init<>())
      .def("new_scope",
           [](Scope &self) -> Scope * { return &self.NewScope(); },
           py::return_value_policy::reference)
      .def("drop_kids", &Scope::DropKids);

  //! @note: Be careful! PyBind will return std::string as an unicode, not
  //! Python str. If you want a str object, you should cast them in Python.
  m.def("get_all_op_protos", []() -> std::vector<py::bytes> {
    std::vector<py::bytes> ret_values;

    OpInfoMap::Instance().IterAllInfo([&ret_values](const std::string &type,
                                                    const OpInfo &info) {
      if (!info.HasOpProtoAndChecker()) return;
      std::string str;
      PADDLE_ENFORCE(info.Proto().SerializeToString(&str),
                     "Serialize OpProto Error. This could be a bug of Paddle.");
      ret_values.emplace_back(str);
    });
    return ret_values;
  });
  m.def_submodule(
       "var_names",
       "The module will return special predefined variable name in Paddle")
      .def("empty", []() { return kEmptyVarName; })
      .def("temp", []() { return kTempVarName; });
  // clang-format off
  py::class_<paddle::platform::DeviceContext>(m, "DeviceContext")
      .def_static("create",
                  [](paddle::platform::CPUPlace& place)
                      -> paddle::platform::DeviceContext* {
                    return new paddle::platform::CPUDeviceContext();
                  })
      .def_static("create",
                  [](paddle::platform::GPUPlace& place)
                      -> paddle::platform::DeviceContext* {
#ifdef PADDLE_ONLY_CPU
                    PADDLE_THROW("GPUPlace is not supported in CPU device.");
#else
                    return new paddle::platform::CUDADeviceContext(place);
#endif
                  });
  // clang-format on

  py::class_<platform::GPUPlace>(m, "GPUPlace")
      .def(py::init<int>())
      .def("__str__", string::to_string<const platform::GPUPlace &>);

  py::class_<paddle::platform::CPUPlace>(m, "CPUPlace")
      .def(py::init<>())
      .def("__str__", string::to_string<const platform::CPUPlace &>);

  py::class_<OperatorBase>(m, "Operator")
      .def_static("create",
                  [](py::bytes protobin) {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    return OpRegistry::CreateOp(desc);
                  })
      .def("backward",
           [](const OperatorBase &forwardOp,
              const std::unordered_set<std::string> &no_grad_vars) {
             return Backward(forwardOp, no_grad_vars).release();
           })
      .def("infer_shape", &OperatorBase::InferShape)
      .def("run", &OperatorBase::Run)
      .def("type",
           [](const OperatorBase &op) -> std::string { return op.Type(); })
      .def("outputs",
           [](const OperatorBase &op)
               -> std::map<std::string, std::vector<std::string>> {
                 return op.Outputs();
               })
      .def("output_vars",
           [](const OperatorBase &op) { return op.OutputVars(true); })
      .def("inputs", [](const OperatorBase &op) { return op.Inputs(); })
      .def("input_vars", [](const OperatorBase &op) { return op.InputVars(); })
      .def("__str__", &OperatorBase::DebugString)
      .def("no_intermediate_outputs",
           [](const OperatorBase &op) { return op.OutputVars(false); })
      .def("support_gpu", &OperatorBase::SupportGPU);

  py::class_<operators::NetOp, OperatorBase>(m, "Net")
      .def_static("create",
                  []() -> operators::NetOp * {
                    auto *retv = new operators::NetOp;
                    retv->SetType("plain_net");
                    return retv;
                  })
      .def("append_op",
           [](operators::NetOp &self, const OperatorBase &op) {
             self.AppendOp(op);
           })
      .def("complete_add_op", &operators::NetOp::CompleteAddOp)
      .def("complete_add_op", [](std::shared_ptr<operators::NetOp> &self) {
        self->CompleteAddOp();
      });

  // recurrent_op
  py::class_<operators::RecurrentOp, OperatorBase>(m, "RecurrentOp")
      .def_static(
          "create",
          [](py::bytes protobin) -> operators::RecurrentOp * {
            OpDesc desc;
            PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                           "Cannot parse user input to OpDesc");
            PADDLE_ENFORCE(desc.IsInitialized(),
                           "User OpDesc is not initialized, reason %s",
                           desc.InitializationErrorString());
            auto rnn_op = OpRegistry::CreateOp(desc);
            return static_cast<operators::RecurrentOp *>(rnn_op.release());
          })
      .def("set_stepnet",
           [](operators::RecurrentOp &self, const operators::NetOp &net)
               -> void { self.set_stepnet(net.Clone()); });

  // cond_op
  py::class_<operators::CondOp, OperatorBase>(m, "CondOp")
      .def_static("create",
                  [](py::bytes protobin) -> operators::CondOp * {
                    OpDesc desc;
                    PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),
                                   "Cannot parse user input to OpDesc");
                    PADDLE_ENFORCE(desc.IsInitialized(),
                                   "User OpDesc is not initialized, reason %s",
                                   desc.InitializationErrorString());
                    auto cond_op = OpRegistry::CreateOp(desc);
                    return static_cast<operators::CondOp *>(cond_op.release());
                  })
      .def("set_truenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_truenet(net.Clone());
           })
      .def("set_falsenet",
           [](operators::CondOp &self, const operators::NetOp &net) -> void {
             self.set_falsenet(net.Clone());
           });

  m.def("unique_integer", UniqueIntegerGenerator);

  m.def("is_compile_gpu", IsCompileGPU);

  py::class_<ProgramDesc>(m, "ProgramDesc", "")
      .def_static("instance", [] { return &GetProgramDesc(); })
      .def("append_block", [](ProgramDesc &self) {
        auto desc = self.mutable_blocks()->Add();
        desc->set_idx(self.mutable_blocks()->size() - 1);
        return desc;
      });
  py::class_<BlockDesc>(m, "BlockDesc", "")
      .def("idx", [](BlockDesc &self) { return self.idx(); })
      .def("set_parent",
           [](BlockDesc &self, int32_t idx) { self.set_parent_idx(idx); })
      .def("parent", [](BlockDesc &self) { return self.parent_idx(); });

  py::class_<VarDesc>(m, "VarDesc", "")
      .def(py::init<>())
      .def("set_name",
           [](VarDesc &self, const std::string &name) { self.set_name(name); })
      .def("set_shape",
           [](VarDesc &self, const std::vector<int64_t> &dims) {
             LoDTensorDesc *lod_tensor_desc = self.mutable_lod_tensor();
             for (const int64_t &i : dims) {
               lod_tensor_desc->add_dims(i);
             }
           })
      .def("set_data_type",
           [](VarDesc &self, int type_id) {
             LoDTensorDesc *lod_tensor_desc = self.mutable_lod_tensor();
             lod_tensor_desc->set_data_type(static_cast<DataType>(type_id));
           })
      .def("shape", [](VarDesc &self) {
        const LoDTensorDesc &lod_tensor_desc = self.lod_tensor();
        int rank = lod_tensor_desc.dims_size();
        std::vector<int64_t> res(rank);
        for (int i = 0; i < rank; ++i) {
          res[i] = lod_tensor_desc.dims(i);
        }
        return res;
      });

  py::class_<OpDesc>(m, "OpDesc", "");

  return m.ptr();
}
}  // namespace framework
}  // namespace paddle
<|endoftext|>


<commit_before>/*
 * Copyright © 2012 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "main/core.h"
#include "ir.h"
#include "linker.h"
#include "ir_uniform.h"
#include "glsl_symbol_table.h"
#include "program/hash_table.h"

/* These functions are put in a "private" namespace instead of being marked
 * static so that the unit tests can access them.  See
 * http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code
 */
namespace linker {

gl_uniform_storage *
get_storage(gl_uniform_storage *storage, unsigned num_storage,
	    const char *name)
{
   for (unsigned int i = 0; i < num_storage; i++) {
      if (strcmp(name, storage[i].name) == 0)
	 return &storage[i];
   }

   return NULL;
}

void
copy_constant_to_storage(union gl_constant_value *storage,
			 const ir_constant *val,
			 const enum glsl_base_type base_type,
			 const unsigned int elements)
{
   for (unsigned int i = 0; i < elements; i++) {
      switch (base_type) {
      case GLSL_TYPE_UINT:
	 storage[i].u = val->value.u[i];
	 break;
      case GLSL_TYPE_INT:
      case GLSL_TYPE_SAMPLER:
	 storage[i].i = val->value.i[i];
	 break;
      case GLSL_TYPE_FLOAT:
	 storage[i].f = val->value.f[i];
	 break;
      case GLSL_TYPE_BOOL:
	 storage[i].b = int(val->value.b[i]);
	 break;
      default:
	 /* All other types should have already been filtered by other
	  * paths in the caller.
	  */
	 assert(!"Should not get here.");
	 break;
      }
   }
}

void
set_uniform_initializer(void *mem_ctx, gl_shader_program *prog,
			const char *name, const glsl_type *type,
			ir_constant *val)
{
   if (type->is_record()) {
      ir_constant *field_constant;

      field_constant = (ir_constant *)val->components.get_head();

      for (unsigned int i = 0; i < type->length; i++) {
	 const glsl_type *field_type = type->fields.structure[i].type;
	 const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
					    type->fields.structure[i].name);
	 set_uniform_initializer(mem_ctx, prog, field_name,
				 field_type, field_constant);
	 field_constant = (ir_constant *)field_constant->next;
      }
      return;
   } else if (type->is_array() && type->fields.array->is_record()) {
      const glsl_type *const element_type = type->fields.array;

      for (unsigned int i = 0; i < type->length; i++) {
	 const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);

	 set_uniform_initializer(mem_ctx, prog, element_name,
				 element_type, val->array_elements[i]);
      }
      return;
   }

   struct gl_uniform_storage *const storage =
      get_storage(prog->UniformStorage,
		  prog->NumUserUniformStorage,
		  name);
   if (storage == NULL) {
      assert(storage != NULL);
      return;
   }

   if (val->type->is_array()) {
      const enum glsl_base_type base_type =
	 val->array_elements[0]->type->base_type;
      const unsigned int elements = val->array_elements[0]->type->components();
      unsigned int idx = 0;

      assert(val->type->length >= storage->array_elements);
      for (unsigned int i = 0; i < storage->array_elements; i++) {
	 copy_constant_to_storage(& storage->storage[idx],
				  val->array_elements[i],
				  base_type,
				  elements);

	 idx += elements;
      }
   } else {
      copy_constant_to_storage(storage->storage,
			       val,
			       val->type->base_type,
			       val->type->components());
   }

   storage->initialized = true;
}
}

void
link_set_uniform_initializers(struct gl_shader_program *prog)
{
   void *mem_ctx = NULL;

   for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
      struct gl_shader *shader = prog->_LinkedShaders[i];

      if (shader == NULL)
	 continue;

      foreach_list(node, shader->ir) {
	 ir_variable *const var = ((ir_instruction *) node)->as_variable();

	 if (!var || var->mode != ir_var_uniform || !var->constant_value)
	    continue;

	 if (!mem_ctx)
	    mem_ctx = ralloc_context(NULL);

	 linker::set_uniform_initializer(mem_ctx, prog, var->name,
					 var->type, var->constant_value);
      }
   }

   ralloc_free(mem_ctx);
}
<commit_msg>glsl: Propagate sampler uniform initializers to gl_shader_program::SamplerUnits<commit_after>/*
 * Copyright © 2012 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "main/core.h"
#include "ir.h"
#include "linker.h"
#include "ir_uniform.h"
#include "glsl_symbol_table.h"
#include "program/hash_table.h"

/* These functions are put in a "private" namespace instead of being marked
 * static so that the unit tests can access them.  See
 * http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code
 */
namespace linker {

gl_uniform_storage *
get_storage(gl_uniform_storage *storage, unsigned num_storage,
	    const char *name)
{
   for (unsigned int i = 0; i < num_storage; i++) {
      if (strcmp(name, storage[i].name) == 0)
	 return &storage[i];
   }

   return NULL;
}

void
copy_constant_to_storage(union gl_constant_value *storage,
			 const ir_constant *val,
			 const enum glsl_base_type base_type,
			 const unsigned int elements)
{
   for (unsigned int i = 0; i < elements; i++) {
      switch (base_type) {
      case GLSL_TYPE_UINT:
	 storage[i].u = val->value.u[i];
	 break;
      case GLSL_TYPE_INT:
      case GLSL_TYPE_SAMPLER:
	 storage[i].i = val->value.i[i];
	 break;
      case GLSL_TYPE_FLOAT:
	 storage[i].f = val->value.f[i];
	 break;
      case GLSL_TYPE_BOOL:
	 storage[i].b = int(val->value.b[i]);
	 break;
      default:
	 /* All other types should have already been filtered by other
	  * paths in the caller.
	  */
	 assert(!"Should not get here.");
	 break;
      }
   }
}

void
set_uniform_initializer(void *mem_ctx, gl_shader_program *prog,
			const char *name, const glsl_type *type,
			ir_constant *val)
{
   if (type->is_record()) {
      ir_constant *field_constant;

      field_constant = (ir_constant *)val->components.get_head();

      for (unsigned int i = 0; i < type->length; i++) {
	 const glsl_type *field_type = type->fields.structure[i].type;
	 const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
					    type->fields.structure[i].name);
	 set_uniform_initializer(mem_ctx, prog, field_name,
				 field_type, field_constant);
	 field_constant = (ir_constant *)field_constant->next;
      }
      return;
   } else if (type->is_array() && type->fields.array->is_record()) {
      const glsl_type *const element_type = type->fields.array;

      for (unsigned int i = 0; i < type->length; i++) {
	 const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);

	 set_uniform_initializer(mem_ctx, prog, element_name,
				 element_type, val->array_elements[i]);
      }
      return;
   }

   struct gl_uniform_storage *const storage =
      get_storage(prog->UniformStorage,
		  prog->NumUserUniformStorage,
		  name);
   if (storage == NULL) {
      assert(storage != NULL);
      return;
   }

   if (val->type->is_array()) {
      const enum glsl_base_type base_type =
	 val->array_elements[0]->type->base_type;
      const unsigned int elements = val->array_elements[0]->type->components();
      unsigned int idx = 0;

      assert(val->type->length >= storage->array_elements);
      for (unsigned int i = 0; i < storage->array_elements; i++) {
	 copy_constant_to_storage(& storage->storage[idx],
				  val->array_elements[i],
				  base_type,
				  elements);

	 idx += elements;
      }

      if (base_type == GLSL_TYPE_SAMPLER) {
	 for (unsigned int i = 0; i < storage->array_elements; i++) {
	    prog->SamplerUnits[storage->sampler + i] = storage->storage[i].i;
	 }
      }
   } else {
      copy_constant_to_storage(storage->storage,
			       val,
			       val->type->base_type,
			       val->type->components());

      if (storage->type->is_sampler())
	 prog->SamplerUnits[storage->sampler] = storage->storage[0].i;
   }

   storage->initialized = true;
}
}

void
link_set_uniform_initializers(struct gl_shader_program *prog)
{
   void *mem_ctx = NULL;

   for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
      struct gl_shader *shader = prog->_LinkedShaders[i];

      if (shader == NULL)
	 continue;

      foreach_list(node, shader->ir) {
	 ir_variable *const var = ((ir_instruction *) node)->as_variable();

	 if (!var || var->mode != ir_var_uniform || !var->constant_value)
	    continue;

	 if (!mem_ctx)
	    mem_ctx = ralloc_context(NULL);

	 linker::set_uniform_initializer(mem_ctx, prog, var->name,
					 var->type, var->constant_value);
      }
   }

   ralloc_free(mem_ctx);
}
<|endoftext|>


<commit_before>// FeatureExtractionCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HaemoragingImage.hpp"
#include "HistogramNormalize.hpp"

namespace fs = boost::filesystem;

const char* keys =
{
    "{ref||| must specify reference image name}"
    "{target||| must specify image name}"
    "{in|inputDir||directory to read files from}"
    "{out|outDir||output directory}"
    "{size||128|output image dimensions}"
    "{d|debug||invoke debugging functionality}"
    "{t|threshold|12|Canny threshold}"

};

Mat src;
RNG rng(12345);
string sourceWindow("Reference");
string targetWindow("Target");
string transformedWindow("Transformed");
string enhancedWindow("Enhanced");
string contouredWindow("Contoured");

ParamBag params;
unique_ptr<HaemoragingImage> haemorage(new HaemoragingImage);

vector<vector<Point>> * FindHaemorages(unique_ptr<HaemoragingImage>&, Mat&, ParamBag&);

void thresh_callback(int, void *)
{
    unique_ptr<vector<vector<Point>>> contours(FindHaemorages(haemorage, src, params));

    Mat img;
    src.copyTo(img);
    TransformImage::DrawContours(*contours, vector<Vec4i>(), img);

    /// Draw contours
    /// Show in a window
    imshow(sourceWindow, img);
}

// color transfer experiments
void do_debug(CommandLineParser& parser)
{
    // keep for debugging
    string ref_file_name = parser.get<string>("ref");
    string file_name = parser.get<string>("target");
    int dim = parser.get<int>("size");
    int thresh = parser.get<int>("t");

    Size size(dim, dim);

    // debugging stuff
    // load the target image & show it
    Mat rgb;
    rgb = imread(file_name, IMREAD_COLOR);

    // create the image mask to be used last
    auto hi = HaemoragingImage(rgb);
    hi.PyramidDown();
    hi.getEnhanced().copyTo(src);

    hi.setImage(src);
    int i = 0;
    do
    {
        hi.CreateEyeContours(i == 0 ? thresh : 1);
        auto mask = hi.CreateMask(dim);
        i++;

        cout << "Eye area: " << hi.EyeAreaRatio() << endl;
        namedWindow("mask");
        imshow("mask", mask);
    } while (hi.EyeAreaRatio() < 0.48 && i <= 2);

    hi.DrawEyeContours(src, Scalar(0, 0, 255), 2);
    namedWindow(targetWindow, WINDOW_NORMAL);
    imshow(targetWindow, src);

    // load the reference image & show it
    rgb = imread(ref_file_name, IMREAD_COLOR);

    // show image contours and filter its background
    HaemoragingImage ref_haem(rgb);
    ref_haem.PyramidDown();
    Mat reference(ref_haem.getEnhanced());

    namedWindow(sourceWindow, WINDOW_NORMAL);
    imshow(sourceWindow, reference);

    Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE };
    vector<Channels> channels(_channels, _channels + 3);

    auto histSpec = HistogramNormalize(reference, channels);

    Mat dest;
    histSpec.HistogramSpecification(src, dest);
    namedWindow(transformedWindow, WINDOW_NORMAL);
    imshow(transformedWindow, dest);

    //3. CLAHE
    hi.setImage(dest);
    hi.MakeHsv();
    hi.GetOneChannelImages(Channels::V);
    hi.ApplyClahe();

    dest = hi.getEnhanced();

    cvtColor(dest, rgb, COLOR_HSV2BGR);
    Mat sized;
    resize(rgb, sized, size);

    //apply background filtering mask
    hi.setImage(sized);
    hi.MaskOffBackground();

    namedWindow(enhancedWindow, WINDOW_NORMAL);
    imshow(enhancedWindow, hi.getEnhanced());

    params.cannyThresh = 60;
    //createTrackbar("Track", sourceWindow, &(params.cannyThresh), 100, thresh_callback);
    //thresh_callback(0, &(params.cannyThresh));
    //ref_image.DisplayEnhanced(true);
    waitKey(0);

}

//1. Pyramid Down
//2. Find the eye and get the mask
//3. Histogram specification: 6535_left
//4. Histogram equalization (CLAHE) on V channel of the HSV image
//5. Resize to size x size
//6. Apply mask to filter background
//7. Write to out_path
void process_files(string& ref, fs::path& in_path, vector<string>& in_files, fs::path& out_path, Size& size)
{
    // process reference image
    Mat rgb = imread(ref, IMREAD_COLOR);

    auto ref_image = HaemoragingImage(rgb);
    ref_image.PyramidDown();
    Mat reference = ref_image.getEnhanced();

    Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE };
    vector<Channels> channels(_channels, _channels + 3);

    // create the class for histogram specification
    auto histSpec = HistogramNormalize(reference, channels);

    for (string& in_file : in_files)
    {
        // in-path
        fs::path filePath = in_path / fs::path(in_file);
        // out-path
        fs::path outFilePath = out_path / fs::path(in_file);

        // read it
        rgb = imread(filePath.string(), IMREAD_COLOR);
        HaemoragingImage hi(rgb);
        // 1. Pyramid down
        hi.PyramidDown();
        hi.getEnhanced().copyTo(src);
        hi.setImage(src);

        // 2. Find contours, get mask.
        // if we did not get the entire eye - reset the threhsold to 1 and repeat
        int i = 0;
        do
        {
            hi.CreateEyeContours(i == 0 ? params.cannyThresh : 1);
            hi.CreateMask(size.width);
            i++;

        } while (hi.EyeAreaRatio() < 0.45 && i <= 2);

        // 3. Histogram specification
        Mat dest;
        histSpec.HistogramSpecification(src, dest);

        // 4. CLAHE
        hi.setImage(dest);
        hi.MakeHsv();
        hi.GetOneChannelImages(Channels::V);
        hi.ApplyClahe();

        src = hi.getEnhanced();

        // 5. resize
        resize(src, dest, size);
        cvtColor(dest, rgb, COLOR_HSV2BGR);

        // 6. apply mask
        hi.setImage(rgb);
        hi.MaskOffBackground();

        // 7. write out
        imwrite(outFilePath.string(), hi.getEnhanced());
    }
}

int main(int argc, char** argv)
{
    CommandLineParser parser(argc, argv, keys);

    string in_dir = parser.get<string>("in");
    string out_dir = parser.get<string>("out");
    string ref = parser.get<string>("ref");
    params.cannyThresh = parser.get<int>("t");

    int dim = parser.get<int>("size");
    Size size(dim, dim);

    bool debug = parser.get<bool>("debug");

    if (debug)
    {
        do_debug(parser);
        return 0;
    }

    fs::path in_path(in_dir);
    fs::path out_path(out_dir);

    if (fs::exists(out_path))
    {
        fs::remove_all(out_path);
    }

    fs::create_directories(out_path);

    // print out GPU information
    gpu::printCudaDeviceInfo(0);
    fs::directory_iterator it(in_path), enumer(in_path);

    vector<string> in_files;

    DIR *dir;
    struct dirent *ent;

    // using dirent because it actually finishes (unlike boost)
    dir = opendir(in_dir.c_str());
    if (dir != NULL)
    {
        /* Print all files and directories within the directory */
        while ((ent = readdir(dir)) != NULL)
        {
            if (ent->d_type == DT_REG)
            {
                in_files.push_back(ent->d_name);
            }
        }
    }
    closedir(dir);

    process_files(ref, in_path, in_files, out_path, size);
    return(0);
}

<commit_msg>Fixing high threshold crash<commit_after>// FeatureExtractionCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HaemoragingImage.hpp"
#include "HistogramNormalize.hpp"

namespace fs = boost::filesystem;

const char* keys =
{
    "{ref||| must specify reference image name}"
    "{target||| must specify image name}"
    "{in|inputDir||directory to read files from}"
    "{out|outDir||output directory}"
    "{size||128|output image dimensions}"
    "{d|debug||invoke debugging functionality}"
    "{t|threshold|12|Canny threshold}"

};

Mat src;
RNG rng(12345);
string sourceWindow("Reference");
string targetWindow("Target");
string transformedWindow("Transformed");
string enhancedWindow("Enhanced");
string contouredWindow("Contoured");

ParamBag params;
unique_ptr<HaemoragingImage> haemorage(new HaemoragingImage);

vector<vector<Point>> * FindHaemorages(unique_ptr<HaemoragingImage>&, Mat&, ParamBag&);

void thresh_callback(int, void *)
{
    unique_ptr<vector<vector<Point>>> contours(FindHaemorages(haemorage, src, params));

    Mat img;
    src.copyTo(img);
    TransformImage::DrawContours(*contours, vector<Vec4i>(), img);

    /// Draw contours
    /// Show in a window
    imshow(sourceWindow, img);
}

// color transfer experiments
void do_debug(CommandLineParser& parser)
{
    // keep for debugging
    string ref_file_name = parser.get<string>("ref");
    string file_name = parser.get<string>("target");
    int dim = parser.get<int>("size");
    int thresh = parser.get<int>("t");

    Size size(dim, dim);

    // debugging stuff
    // load the target image & show it
    Mat rgb;
    rgb = imread(file_name, IMREAD_COLOR);

    // create the image mask to be used last
    auto hi = HaemoragingImage(rgb);
    hi.PyramidDown();
    hi.getEnhanced().copyTo(src);

    hi.setImage(src);
    int i = 0;
    int threshTemp = thresh;
    do
    {
        // in vast majority of cases this will only run once
        for (auto hull = hi.CreateEyeContours(i == 0 ? threshTemp : 1); hull.size() == 0 && threshTemp > 0; threshTemp--)
        {
            hull = hi.CreateEyeContours(i == 0 ? --threshTemp : 1);
        }

        auto mask = hi.CreateMask(dim);
        i++;

        cout << "Eye area: " << hi.EyeAreaRatio() << endl;
        namedWindow("mask");
        imshow("mask", mask);
    } while (hi.EyeAreaRatio() < 0.48 && i <= 2);

    hi.DrawEyeContours(src, Scalar(0, 0, 255), 2);
    namedWindow(targetWindow, WINDOW_NORMAL);
    imshow(targetWindow, src);

    // load the reference image & show it
    rgb = imread(ref_file_name, IMREAD_COLOR);

    // show image contours and filter its background
    HaemoragingImage ref_haem(rgb);
    ref_haem.PyramidDown();
    Mat reference(ref_haem.getEnhanced());

    namedWindow(sourceWindow, WINDOW_NORMAL);
    imshow(sourceWindow, reference);

    Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE };
    vector<Channels> channels(_channels, _channels + 3);

    auto histSpec = HistogramNormalize(reference, channels);

    Mat dest;
    histSpec.HistogramSpecification(src, dest);
    namedWindow(transformedWindow, WINDOW_NORMAL);
    imshow(transformedWindow, dest);

    //3. CLAHE
    hi.setImage(dest);
    hi.MakeHsv();
    hi.GetOneChannelImages(Channels::V);
    hi.ApplyClahe();

    dest = hi.getEnhanced();

    cvtColor(dest, rgb, COLOR_HSV2BGR);
    Mat sized;
    resize(rgb, sized, size);

    //apply background filtering mask
    hi.setImage(sized);
    hi.MaskOffBackground();

    namedWindow(enhancedWindow, WINDOW_NORMAL);
    imshow(enhancedWindow, hi.getEnhanced());

    params.cannyThresh = 60;
    //createTrackbar("Track", sourceWindow, &(params.cannyThresh), 100, thresh_callback);
    //thresh_callback(0, &(params.cannyThresh));
    //ref_image.DisplayEnhanced(true);
    waitKey(0);

}

//1. Pyramid Down
//2. Find the eye and get the mask
//3. Histogram specification: 6535_left
//4. Histogram equalization (CLAHE) on V channel of the HSV image
//5. Resize to size x size
//6. Apply mask to filter background
//7. Write to out_path
void process_files(string& ref, fs::path& in_path, vector<string>& in_files, fs::path& out_path, Size& size)
{
    // process reference image
    Mat rgb = imread(ref, IMREAD_COLOR);

    auto ref_image = HaemoragingImage(rgb);
    ref_image.PyramidDown();
    Mat reference = ref_image.getEnhanced();

    Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE };
    vector<Channels> channels(_channels, _channels + 3);

    // create the class for histogram specification
    auto histSpec = HistogramNormalize(reference, channels);

    for (string& in_file : in_files)
    {
        // in-path
        fs::path filePath = in_path / fs::path(in_file);
        // out-path
        fs::path outFilePath = out_path / fs::path(in_file);

        // read it
        rgb = imread(filePath.string(), IMREAD_COLOR);
        HaemoragingImage hi(rgb);
        // 1. Pyramid down
        hi.PyramidDown();
        hi.getEnhanced().copyTo(src);
        hi.setImage(src);

        // 2. Find contours, get mask.
        // if we did not get the entire eye - reset the threhsold to 1 and repeat
        int i = 0;
        int thresh = params.cannyThresh;
        do
        {
            // in vast majority of cases this will only run once
            for (auto hull = hi.CreateEyeContours(i == 0 ? thresh : 1); hull.size() == 0 && thresh > 0; )
            {
                hull = hi.CreateEyeContours(i == 0 ? --thresh : 1);
            }

            hi.CreateMask(size.width);
            i++;

        } while (hi.EyeAreaRatio() < 0.45 && i <= 2);

        // 3. Histogram specification
        Mat dest;
        histSpec.HistogramSpecification(src, dest);

        // 4. CLAHE
        hi.setImage(dest);
        hi.MakeHsv();
        hi.GetOneChannelImages(Channels::V);
        hi.ApplyClahe();

        src = hi.getEnhanced();

        // 5. resize
        resize(src, dest, size);
        cvtColor(dest, rgb, COLOR_HSV2BGR);

        // 6. apply mask
        hi.setImage(rgb);
        hi.MaskOffBackground();

        // 7. write out
        imwrite(outFilePath.string(), hi.getEnhanced());
    }
}

int main(int argc, char** argv)
{
    CommandLineParser parser(argc, argv, keys);

    string in_dir = parser.get<string>("in");
    string out_dir = parser.get<string>("out");
    string ref = parser.get<string>("ref");
    params.cannyThresh = parser.get<int>("t");

    int dim = parser.get<int>("size");
    Size size(dim, dim);

    bool debug = parser.get<bool>("debug");

    if (debug)
    {
        do_debug(parser);
        return 0;
    }

    fs::path in_path(in_dir);
    fs::path out_path(out_dir);

    if (fs::exists(out_path))
    {
        fs::remove_all(out_path);
    }

    fs::create_directories(out_path);

    // print out GPU information
    gpu::printCudaDeviceInfo(0);
    fs::directory_iterator it(in_path), enumer(in_path);

    vector<string> in_files;

    DIR *dir;
    struct dirent *ent;

    // using dirent because it actually finishes (unlike boost)
    dir = opendir(in_dir.c_str());
    if (dir != NULL)
    {
        /* Print all files and directories within the directory */
        while ((ent = readdir(dir)) != NULL)
        {
            if (ent->d_type == DT_REG)
            {
                in_files.push_back(ent->d_name);
            }
        }
    }
    closedir(dir);

    process_files(ref, in_path, in_files, out_path, size);
    return(0);
}

<|endoftext|>


<commit_before>// Copyright (c) 2013 Patrick Huck
#define BOOST_FILESYSTEM_NO_DEPRECATED

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>

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

#include "src/aux/utils.h"
#include "src/cmdline/cmdline.h"
#include "src/helpers/helpers.h"

using std::vector;
using std::string;
using std::cout;
using std::endl;
namespace fs = boost::filesystem;

int main(int argc, char *argv[]) {
  try {
    // init & parse options & arguments, fill container
    cmdline* clopts = new cmdline();
    if ( !clopts->parse(argc, argv) ) return 0;

    // init helpers w/ command line options
    helpers* hlp = new helpers(clopts);

    // get list of sub-directories in ckon_src_dir/ for which
    // to generate Makefile_insert and LinkDef.h
    vector<fs::path> subdirs;  // absolute paths to subdirs
    hlp->push_subdirs(&subdirs);

    // if Makefile.am doesn't exist, generate Makefile.am
    bool redoMakefileAm = !fs::exists("Makefile.am");
    fs::ofstream top_out;
    if ( redoMakefileAm ) {
      // create & init Makefile.am
      top_out.open("Makefile.am");
      top_out << hlp->writeMakefileAmHd();
    }

    // loop all subdirs
    BOOST_FOREACH(fs::path sd, subdirs) {
      // check if subdir "empty" (no header files). If so, skip.
      if ( utils::isEmptyDir(sd) ) continue;
      if ( clopts->bVerbose ) cout << sd << endl;

      // set subdir for helpers, set libname
      // increase subdir counter, set oprnd
      hlp->init_subdir(sd);

      // get list of all header, source and prog files in current subdir
      vector<fs::path> headers, sources, progs;
      hlp->push_src(&headers, &sources, &progs);

      // check time stamp for linkdef file
      fs::path linkdef(sd);
      linkdef /= "LinkDef.h";
      bool redoLinkDef = (
          !fs::exists(linkdef) ||
          !utils::checkTimeStamp(linkdef, headers) ||
          !utils::checkTimeStamp(linkdef, sources) ||
          !utils::checkTimeStamp(linkdef, progs));

      // write LinkDef.h for current subdir
      if ( redoLinkDef ) {
        // get lists of all classes & namespaces for current subdir
        vector<string> classes, namespaces;
        hlp->push_obj("class", &classes);
        hlp->push_obj("namespace", &namespaces);

        // write linkdef
        fs::ofstream out;
        out.open(linkdef);
        out << utils::writeLinkDefHd();
        string prgma = "#pragma link C++ ";
        BOOST_FOREACH(string ns, namespaces) {
          out << prgma << "namespace " << ns << ";" << endl;
        }
        BOOST_FOREACH(string cl, classes) {
          out << prgma << "class " << cl << hlp->getSuffix(cl) << ";" << endl;
        }
        out << "#endif" << endl;
        out.close();
      }

      // check time stamp for makefile_insert
      fs::path makefile(sd);
      makefile /= "Makefile_insert";
      bool redoMakefile = (
          !fs::exists(makefile) ||
          !utils::checkTimeStamp(makefile, headers) ||
          !utils::checkTimeStamp(makefile, sources) ||
          !utils::checkTimeStamp(makefile, progs));

      // write include statement into Makefile.am
      if ( redoMakefileAm ) {
        top_out << "include " << makefile.string() << endl;
      }

      // write Makefile_insert for current subdir
      if ( redoMakefile ) {
        // write makefile
        fs::ofstream out;
        out.open(makefile);
        out << hlp->writePkgDefs(linkdef, headers);
        out << hlp->writeLibDefs(sources);
        if ( hlp->genDict() ) { out << hlp->writeDict(linkdef, headers); }
        BOOST_FOREACH(fs::path p, progs) {
          hlp->genCoreLibStr(p);
          out << hlp->writeBinProg(p);
        }
        out.close();
      }
    }  // end of subdir loop

    cout << hlp->getNrSubdirs() << " sub-directories processed." << endl;

    if ( redoMakefileAm ) top_out.close();

    // run autoconf if configure script doesn't exist
    if ( !fs::exists("configure") ) system("autoreconf -v --force --install");

    // if builddir doesn't exist, create it and run configure
    // else, just switch to builddir
    fs::path cwd(fs::current_path());  // pwd
    cwd /= clopts->ckon_build_dir;  // append build dir
    if ( !fs::exists(cwd) ) {
      fs::create_directories(cwd);  // mkdir
      fs::current_path(cwd);  // chdir
      string export_build = "export top_builddir=" + cwd.string();
      putenv(const_cast<char*>(export_build.c_str()));
      fs::path prefix(fs::absolute(clopts->ckon_install_dir));
      string config_call = "../configure --prefix=" + prefix.string();
      system(config_call.c_str());
    }

    // always call make when invoking ckon
    const char* istr = (clopts->bInstall)?"install":"";
    string make_call = "make -j " + clopts->nCpu + istr;
    fs::current_path(cwd);  // chdir
    system(make_call.c_str());

    cout << "==> build process finished." << endl;
  }
  catch(const std::exception& e) {
    std::cerr << "Unhandled Exception reached the top of main: "
      << e.what() << ", application will now exit" << endl;
    return 1;
  }

  return 0;
}
<commit_msg>ckon.cc: make_call -Wall -Werror<commit_after>// Copyright (c) 2013 Patrick Huck
#define BOOST_FILESYSTEM_NO_DEPRECATED

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>

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

#include "src/aux/utils.h"
#include "src/cmdline/cmdline.h"
#include "src/helpers/helpers.h"

using std::vector;
using std::string;
using std::cout;
using std::endl;
namespace fs = boost::filesystem;

int main(int argc, char *argv[]) {
  try {
    // init & parse options & arguments, fill container
    cmdline* clopts = new cmdline();
    if ( !clopts->parse(argc, argv) ) return 0;

    // init helpers w/ command line options
    helpers* hlp = new helpers(clopts);

    // get list of sub-directories in ckon_src_dir/ for which
    // to generate Makefile_insert and LinkDef.h
    vector<fs::path> subdirs;  // absolute paths to subdirs
    hlp->push_subdirs(&subdirs);

    // if Makefile.am doesn't exist, generate Makefile.am
    bool redoMakefileAm = !fs::exists("Makefile.am");
    fs::ofstream top_out;
    if ( redoMakefileAm ) {
      // create & init Makefile.am
      top_out.open("Makefile.am");
      top_out << hlp->writeMakefileAmHd();
    }

    // loop all subdirs
    BOOST_FOREACH(fs::path sd, subdirs) {
      // check if subdir "empty" (no header files). If so, skip.
      if ( utils::isEmptyDir(sd) ) continue;
      if ( clopts->bVerbose ) cout << sd << endl;

      // set subdir for helpers, set libname
      // increase subdir counter, set oprnd
      hlp->init_subdir(sd);

      // get list of all header, source and prog files in current subdir
      vector<fs::path> headers, sources, progs;
      hlp->push_src(&headers, &sources, &progs);

      // check time stamp for linkdef file
      fs::path linkdef(sd);
      linkdef /= "LinkDef.h";
      bool redoLinkDef = (
          !fs::exists(linkdef) ||
          !utils::checkTimeStamp(linkdef, headers) ||
          !utils::checkTimeStamp(linkdef, sources) ||
          !utils::checkTimeStamp(linkdef, progs));

      // write LinkDef.h for current subdir
      if ( redoLinkDef ) {
        // get lists of all classes & namespaces for current subdir
        vector<string> classes, namespaces;
        hlp->push_obj("class", &classes);
        hlp->push_obj("namespace", &namespaces);

        // write linkdef
        fs::ofstream out;
        out.open(linkdef);
        out << utils::writeLinkDefHd();
        string prgma = "#pragma link C++ ";
        BOOST_FOREACH(string ns, namespaces) {
          out << prgma << "namespace " << ns << ";" << endl;
        }
        BOOST_FOREACH(string cl, classes) {
          out << prgma << "class " << cl << hlp->getSuffix(cl) << ";" << endl;
        }
        out << "#endif" << endl;
        out.close();
      }

      // check time stamp for makefile_insert
      fs::path makefile(sd);
      makefile /= "Makefile_insert";
      bool redoMakefile = (
          !fs::exists(makefile) ||
          !utils::checkTimeStamp(makefile, headers) ||
          !utils::checkTimeStamp(makefile, sources) ||
          !utils::checkTimeStamp(makefile, progs));

      // write include statement into Makefile.am
      if ( redoMakefileAm ) {
        top_out << "include " << makefile.string() << endl;
      }

      // write Makefile_insert for current subdir
      if ( redoMakefile ) {
        // write makefile
        fs::ofstream out;
        out.open(makefile);
        out << hlp->writePkgDefs(linkdef, headers);
        out << hlp->writeLibDefs(sources);
        if ( hlp->genDict() ) { out << hlp->writeDict(linkdef, headers); }
        BOOST_FOREACH(fs::path p, progs) {
          hlp->genCoreLibStr(p);
          out << hlp->writeBinProg(p);
        }
        out.close();
      }
    }  // end of subdir loop

    cout << hlp->getNrSubdirs() << " sub-directories processed." << endl;

    if ( redoMakefileAm ) top_out.close();

    // run autoconf if configure script doesn't exist
    if ( !fs::exists("configure") ) system("autoreconf -v --force --install");

    // if builddir doesn't exist, create it and run configure
    // else, just switch to builddir
    fs::path cwd(fs::current_path());  // pwd
    cwd /= clopts->ckon_build_dir;  // append build dir
    if ( !fs::exists(cwd) ) {
      fs::create_directories(cwd);  // mkdir
      fs::current_path(cwd);  // chdir
      string export_build = "export top_builddir=" + cwd.string();
      putenv(const_cast<char*>(export_build.c_str()));
      fs::path prefix(fs::absolute(clopts->ckon_install_dir));
      string config_call = "../configure --prefix=" + prefix.string();
      system(config_call.c_str());
    }

    // always call make when invoking ckon
    const char* istr = (clopts->bInstall)?"install":"";
    string make_call = "make -j " + clopts->nCpu + " CXXFLAGS=\"-Wall -Werror\" " + istr;
    fs::current_path(cwd);  // chdir
    system(make_call.c_str());

    cout << "==> build process finished." << endl;
  }
  catch(const std::exception& e) {
    std::cerr << "Unhandled Exception reached the top of main: "
      << e.what() << ", application will now exit" << endl;
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/common/package/xpk_package.h"

#include <string>

#include "base/file_util.h"
#include "base/files/scoped_file.h"
#include "crypto/signature_verifier.h"
#include "xwalk/application/common/id_util.h"

namespace xwalk {
namespace application {

const uint8 kSignatureAlgorithm[15] = {
  0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
  0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00
};

const char XPKPackage::kXPKPackageHeaderMagic[] = "CrWk";

XPKPackage::~XPKPackage() {
}

XPKPackage::XPKPackage(const base::FilePath& path)
    : Package(path, Manifest::TYPE_MANIFEST) {
  if (!base::PathExists(path))
    return;
  scoped_ptr<base::ScopedFILE> file(
      new base::ScopedFILE(base::OpenFile(path, "rb")));
  file_ = file.Pass();
  size_t len = fread(&header_, 1, sizeof(header_), file_->get());
  is_valid_ = false;
  if (len < sizeof(header_))
    return;
  if (!strncmp(XPKPackage::kXPKPackageHeaderMagic, header_.magic,
               sizeof(header_.magic)) &&
      header_.key_size > 0 &&
      header_.key_size <= XPKPackage::kMaxPublicKeySize &&
      header_.signature_size > 0 &&
      header_.signature_size <= XPKPackage::kMaxSignatureKeySize) {
    is_valid_ = true;
    zip_addr_ = sizeof(header_) + header_.key_size + header_.signature_size;
    fseek(file_->get(), sizeof(header_), SEEK_SET);
    key_.resize(header_.key_size);
    size_t len = fread(&key_.front(), sizeof(uint8), header_.key_size,
        file_->get());
    if (len < header_.key_size)
      is_valid_ = false;

    signature_.resize(header_.signature_size);
    len = fread(&signature_.front(), sizeof(uint8), header_.signature_size,
        file_->get());
    if (len < header_.signature_size)
      is_valid_ = false;

    if (!VerifySignature())
      is_valid_ = false;

    std::string public_key =
        std::string(reinterpret_cast<char*>(&key_.front()), key_.size());
    id_ = GenerateId(public_key);
  }
}

bool XPKPackage::VerifySignature() {
// Set the file read position to the beginning of compressed resource file,
// which is behind the magic header, public key and signature key.
  fseek(file_->get(), zip_addr_, SEEK_SET);
  crypto::SignatureVerifier verifier;
  if (!verifier.VerifyInit(kSignatureAlgorithm,
                           sizeof(kSignatureAlgorithm),
                           &signature_.front(),
                           signature_.size(),
                           &key_.front(),
                           key_.size()))
    return false;
  unsigned char buf[1 << 12];
  size_t len = 0;
  while ((len = fread(buf, 1, sizeof(buf), file_->get())) > 0)
    verifier.VerifyUpdate(buf, len);
  if (!verifier.VerifyFinal())
    return false;

  return true;
}

bool XPKPackage::ExtractToTemporaryDir(base::FilePath* target_path) {
  if (is_extracted_) {
    *target_path = temp_dir_.path();
    return true;
  }

  if (!IsValid()) {
    LOG(ERROR) << "The XPK file is not valid.";
    return false;
  }

  return Package::ExtractToTemporaryDir(target_path);
}

}  // namespace application
}  // namespace xwalk
<commit_msg>[Application] xpk_package: Add the check for fseek()'s return value and initialzie for |zip_addr_|.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/common/package/xpk_package.h"

#include <string>

#include "base/file_util.h"
#include "base/files/scoped_file.h"
#include "crypto/signature_verifier.h"
#include "xwalk/application/common/id_util.h"

namespace xwalk {
namespace application {

const uint8 kSignatureAlgorithm[15] = {
  0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
  0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00
};

const char XPKPackage::kXPKPackageHeaderMagic[] = "CrWk";

XPKPackage::~XPKPackage() {
}

XPKPackage::XPKPackage(const base::FilePath& path)
    : Package(path, Manifest::TYPE_MANIFEST),
      zip_addr_(0) {
  if (!base::PathExists(path))
    return;
  scoped_ptr<base::ScopedFILE> file(
      new base::ScopedFILE(base::OpenFile(path, "rb")));
  file_ = file.Pass();
  size_t len = fread(&header_, 1, sizeof(header_), file_->get());
  is_valid_ = false;
  if (len < sizeof(header_))
    return;
  if (!strncmp(XPKPackage::kXPKPackageHeaderMagic, header_.magic,
               sizeof(header_.magic)) &&
      header_.key_size > 0 &&
      header_.key_size <= XPKPackage::kMaxPublicKeySize &&
      header_.signature_size > 0 &&
      header_.signature_size <= XPKPackage::kMaxSignatureKeySize) {
    is_valid_ = true;
    zip_addr_ = sizeof(header_) + header_.key_size + header_.signature_size;
    if (fseek(file_->get(), sizeof(header_), SEEK_SET)) {
      is_valid_ = false;
      return;
    }
    key_.resize(header_.key_size);
    size_t len = fread(&key_.front(), sizeof(uint8), header_.key_size,
        file_->get());
    if (len < header_.key_size)
      is_valid_ = false;

    signature_.resize(header_.signature_size);
    len = fread(&signature_.front(), sizeof(uint8), header_.signature_size,
        file_->get());
    if (len < header_.signature_size)
      is_valid_ = false;

    if (!VerifySignature())
      is_valid_ = false;

    std::string public_key =
        std::string(reinterpret_cast<char*>(&key_.front()), key_.size());
    id_ = GenerateId(public_key);
  }
}

bool XPKPackage::VerifySignature() {
// Set the file read position to the beginning of compressed resource file,
// which is behind the magic header, public key and signature key.
  if (fseek(file_->get(), zip_addr_, SEEK_SET))
    return false;
  crypto::SignatureVerifier verifier;
  if (!verifier.VerifyInit(kSignatureAlgorithm,
                           sizeof(kSignatureAlgorithm),
                           &signature_.front(),
                           signature_.size(),
                           &key_.front(),
                           key_.size()))
    return false;
  unsigned char buf[1 << 12];
  size_t len = 0;
  while ((len = fread(buf, 1, sizeof(buf), file_->get())) > 0)
    verifier.VerifyUpdate(buf, len);
  if (!verifier.VerifyFinal())
    return false;

  return true;
}

bool XPKPackage::ExtractToTemporaryDir(base::FilePath* target_path) {
  if (is_extracted_) {
    *target_path = temp_dir_.path();
    return true;
  }

  if (!IsValid()) {
    LOG(ERROR) << "The XPK file is not valid.";
    return false;
  }

  return Package::ExtractToTemporaryDir(target_path);
}

}  // namespace application
}  // namespace xwalk
<|endoftext|>


<commit_before>#include <iostream>
#include "SDL/SDL.h"
#include "SDL_image.h"
#include "surface.h"

using namespace std;

const int TILE_SIZE = 32; // squared

Surface::Surface() {
}

SDL_Surface* Surface::load(std::string File) {
  SDL_Surface* temp = NULL;
  SDL_Surface* result = NULL;

  if((temp = IMG_Load(File.c_str())) == NULL) {
    return NULL;
  }

  result = SDL_DisplayFormat(temp);
  SDL_FreeSurface(temp);

  return result;
}

void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_BlitSurface(src, NULL, dest, &destRect);
}

void Surface::drawTrans(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  int r = 255, g = 0, b = 255;
  int result = SDL_SetColorKey(src, SDL_SRCCOLORKEY, SDL_MapRGB(src->format, r, g, b) );

  if (result != 0) {
    cout << "Error setting SDL Color key" << endl;
  }

  SDL_BlitSurface(src, &srcRect, dest, &destRect);

  // disable colorkey again
  SDL_SetColorKey(src, 0, 0);
}

// draw transparent surface (note: this is not the same as using a color key)
void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y, Uint32 alpha) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  Uint32 alphaFlag;

  if (alpha < SDL_ALPHA_OPAQUE) {
    alphaFlag = SDL_SRCALPHA;
  } else {
    // this will let SDL ignore alpha drawing
    alphaFlag = 0;
  }

  // Set alpha
  SDL_SetAlpha(src, alphaFlag, alpha);

  SDL_BlitSurface(src, &srcRect, dest, &destRect);
}

void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  SDL_BlitSurface(src, &srcRect, dest, &destRect);
}

void Surface::drawTile(SDL_Surface* tileset, SDL_Surface* dest, int src_x, int src_y, int dest_x, int dest_y) {
  if (tileset == NULL || dest == NULL) return;
  Surface::draw(tileset, dest, src_x * TILE_SIZE, src_y * TILE_SIZE, TILE_SIZE, TILE_SIZE, dest_x, dest_y);
}

void Surface::drawTile(SDL_Surface* tileset, SDL_Surface* dest, int tileIndex, int dest_x, int dest_y) {
  if (tileset == NULL || dest == NULL) return;
  int tiles_width = tileset->w / TILE_SIZE;
  int tiles_height = tileset->h / TILE_SIZE;

  int tileset_y = (tileIndex / tiles_width);
  int tileset_x = tileIndex - (tileset_y * tiles_height);

  Surface::drawTile(tileset, dest, tileset_x, tileset_y, dest_x, dest_y);
}
<commit_msg>it is unneeded to set/unset colorkey for this drawing. Actually should be moved to loading image and then leave it, it should make no difference when drawing then.<commit_after>#include <iostream>
#include "SDL/SDL.h"
#include "SDL_image.h"
#include "surface.h"

using namespace std;

const int TILE_SIZE = 32; // squared

Surface::Surface() {
}

SDL_Surface* Surface::load(std::string File) {
  SDL_Surface* temp = NULL;
  SDL_Surface* result = NULL;

  if((temp = IMG_Load(File.c_str())) == NULL) {
    return NULL;
  }

  result = SDL_DisplayFormat(temp);
  SDL_FreeSurface(temp);

  return result;
}

void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_BlitSurface(src, NULL, dest, &destRect);
}

void Surface::drawTrans(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  int r = 255, g = 0, b = 255;
  int result = SDL_SetColorKey(src, SDL_SRCCOLORKEY, SDL_MapRGB(src->format, r, g, b) );

  if (result != 0) {
    cout << "Error setting SDL Color key" << endl;
  }

  SDL_BlitSurface(src, &srcRect, dest, &destRect);
}

// draw transparent surface (note: this is not the same as using a color key)
void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y, Uint32 alpha) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  Uint32 alphaFlag;

  if (alpha < SDL_ALPHA_OPAQUE) {
    alphaFlag = SDL_SRCALPHA;
  } else {
    // this will let SDL ignore alpha drawing
    alphaFlag = 0;
  }

  // Set alpha
  SDL_SetAlpha(src, alphaFlag, alpha);

  SDL_BlitSurface(src, &srcRect, dest, &destRect);
}

void Surface::draw(SDL_Surface* src, SDL_Surface* dest, int src_x, int src_y, int width, int height, int dest_x, int dest_y) {
  if (src == NULL || dest == NULL) return;

  SDL_Rect destRect;

  destRect.x = dest_x;
  destRect.y = dest_y;

  SDL_Rect srcRect;

  srcRect.x = src_x;
  srcRect.y = src_y;
  srcRect.h = height;
  srcRect.w = width;

  SDL_BlitSurface(src, &srcRect, dest, &destRect);
}

void Surface::drawTile(SDL_Surface* tileset, SDL_Surface* dest, int src_x, int src_y, int dest_x, int dest_y) {
  if (tileset == NULL || dest == NULL) return;
  Surface::draw(tileset, dest, src_x * TILE_SIZE, src_y * TILE_SIZE, TILE_SIZE, TILE_SIZE, dest_x, dest_y);
}

void Surface::drawTile(SDL_Surface* tileset, SDL_Surface* dest, int tileIndex, int dest_x, int dest_y) {
  if (tileset == NULL || dest == NULL) return;
  int tiles_width = tileset->w / TILE_SIZE;
  int tiles_height = tileset->h / TILE_SIZE;

  int tileset_y = (tileIndex / tiles_width);
  int tileset_x = tileIndex - (tileset_y * tiles_height);

  Surface::drawTile(tileset, dest, tileset_x, tileset_y, dest_x, dest_y);
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <forestclaw2d.h>
#include <fclaw_options.h>
#include <fclaw_base.h>

#include <fclaw2d_clawpack.H>
#include <fclaw2d_map.h>
#include <fclaw2d_map_query.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <p4est_connectivity.h>

#include "torus_user.H"

static int fclaw_package_id;

static int
torus_checkparms (int example)
{
    if (example < 1 || example > 4) {
        fclaw_global_essentialf ("Option --example must be 1, 2, 3 or 4\n");
        return -1;
    }

    return 0;
}

int
main (int argc, char **argv)
{
  sc_MPI_Comm              mpicomm;
  sc_options_t             *options;
  fclaw_app_t *app;
  p4est_connectivity_t     *conn = NULL;
  fclaw2d_domain_t	   *domain;

  fclaw2d_map_context_t    *cont = NULL, *brick = NULL;
  amr_options_t             samr_options, *gparms = &samr_options;
  fclaw2d_clawpack_parms_t  sclawpack_parms, *clawpack_parms = &sclawpack_parms;
  fclaw2d_map_data_t        smap_data, *map_data = &smap_data;

  int example, retval;
  double pi = M_PI;

  /* Mapping variables */
  double rotate[2];
  double alpha, beta;  /* Ratio of torus inner radius to outer radius */
  const char* latitude_string, *longitude_string;
  double *latitude, *longitude;
  int mi, mj, a,b;
  int verbosity;

  /* initialize application */
  app = fclaw_app_new (&argc, &argv, NULL);
  options = fclaw_app_get_options (app);
  fclaw_package_id = fclaw_get_package_id ();
  mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

#if 0
  lp = SC_LP_PRODUCTION;
  mpicomm = sc_MPI_COMM_WORLD;
  fclaw_mpi_init (&argc, &argv, mpicomm, lp);

  options = sc_options_new (argv[0]);
#endif

  /* -------------------------------------------------------------
     - Register variables
     ------------------------------------------------------------- */
  sc_options_add_int (options, 0, "main:example", &example, 0,
                      "[main] 1 = cart; 2 = torus; 3 = lat-long; 4 = annulus [2]");

  sc_options_add_double (options, 0, "main:alpha", &alpha, 0.4,
                         "[main] Ratio r/R, r=outer radius, R=inner radius " \
                         "(used for torus) [0.4]");

  fclaw_options_add_double_array(options, 0, "main:latitude", &latitude_string,
                                 "-50 50", &latitude, 2,
                                 "[main] Latitude range (degrees) [-50 50]");

  fclaw_options_add_double_array(options, 0, "main:longitude", &longitude_string,
                                 "0 360", &longitude, 2,
                                 "[main] Longitude range (degrees) [0 360]");

  sc_options_add_double (options, 0, "main:beta", &beta, 0.4,
                         "[main] Inner radius of annulus [0.4]");

  /* [Options] Register general ForestClaw options */
  fclaw_options_register(options,gparms);

  /* [mapping] Register general mapping data */
  fclaw2d_register_map_data(options,map_data);

  /* [clawpack46] Register solver options */
  clawpack46_register_options(options,clawpack_parms);

  /* Set and register verbosity level */
  fclaw_set_verbosity(options,&verbosity,FCLAW_VERBOSITY_SILENT);

  /* -------------------------------------------------------------
     - Read options from fclaw_options.ini
     - Parse command line
     - postprocess array input
     - checkparms
     ------------------------------------------------------------- */
  retval = fclaw_options_read_from_file(options);
  retval = retval || fclaw_options_parse_command_line (options,argc, argv);

  fclaw_options_postprocess(gparms);
  clawpack46_postprocess_parms(clawpack_parms);
  fclaw2d_options_postprocess_map_data(map_data);

  if (example == 3)
  {
      fclaw_options_convert_double_array (latitude_string, &latitude,2);
      fclaw_options_convert_double_array (longitude_string, &longitude,2);
  }

  retval = retval || fclaw_options_check (options, gparms);
  retval = retval || clawpack46_checkparms(options,clawpack_parms,gparms);
  retval = retval || torus_checkparms (example);  /* Nothing more to check here */
  /* -------------------------------------------------------------
     - Run program
     ------------------------------------------------------------- */
  if (!retval)
  {
      /* set verbosity levels */
      sc_package_set_verbosity (sc_package_id, FCLAW_VERBOSITY_ESSENTIAL);
      sc_package_set_verbosity (p4est_package_id, FCLAW_VERBOSITY_ESSENTIAL);
      sc_package_set_verbosity (fclaw_package_id, verbosity);

      /* Only print options if verbosity >= info */
      fclaw_options_print_summary(options);

      if (gparms->trapfpe == 1)
      {
          fclaw_global_infof("Enabling floating point traps\n");
          feenableexcept(FE_INVALID);
      }

      if (gparms->mpi_debug == 1)
      {
          fclaw2d_mpi_debug();
      }

      /* ---------------------------------------------------------------
         Mapping geometry
         --------------------------------------------------------------- */
      mi = map_data->mi;
      mj = map_data->mj;
      rotate[0] = pi*map_data->theta/180.0;
      rotate[1] = pi*map_data->phi/180.0;
      a = map_data->periodic_x;
      b = map_data->periodic_y;

      switch (example)
      {
      case 1:
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_cart(brick,map_data->scale,map_data->shift,rotate);
          break;
      case 2:
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_torus(brick,map_data->scale,map_data->shift,rotate,alpha);
          break;
      case 3:
          /* Lat-long example */
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_latlong(brick,map_data->scale,map_data->shift,
                                         rotate,latitude,longitude,a,b);
          break;
      case 4:
          /* Annulus */
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_annulus(brick,map_data->scale,map_data->shift,
                                         rotate,beta);
          break;

      default:
          SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
      }

      domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

      /* ---------------------------------------------------------- */
#if 0
      /* TODO : Replace this with an updated version? */
      if (gparms->verbosity > 0)
      {
          fclaw2d_domain_list_levels(domain, lp);
          fclaw2d_domain_list_neighbors(domain, lp);
      }
#endif

      /* ---------------------------------------------------------------
         Set domain data.
         --------------------------------------------------------------- */
      init_domain_data(domain);

      set_domain_parms(domain,gparms);
      set_clawpack_parms(domain,clawpack_parms);

      link_problem_setup(domain,torus_problem_setup);

      torus_link_solvers(domain);

      link_regrid_functions(domain,
                            torus_patch_tag4refinement,
                            torus_patch_tag4coarsening);
      amrinit(&domain);
      amrrun(&domain);
      amrreset(&domain);

      fclaw2d_map_destroy(cont);
  }

  /* Destroy arrays used in options  */
  if (example == 3)
  {
      fclaw_options_destroy_array((void*) latitude);
      fclaw_options_destroy_array((void*) longitude);
  }

  fclaw2d_map_destroy_arrays(map_data);
  fclaw_options_destroy_arrays (gparms);
  fclaw2d_clawpack_parms_delete(clawpack_parms);

#if 0
  sc_options_destroy (options);
  fclaw_mpi_finalize ();
#endif

  fclaw_app_destroy (app);

  return 0;
}
<commit_msg>Updated verbosity settings and logging priorities<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <forestclaw2d.h>
#include <fclaw_options.h>
#include <fclaw_base.h>

#include <fclaw2d_clawpack.H>
#include <fclaw2d_map.h>
#include <fclaw2d_map_query.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <p4est_connectivity.h>

#include "torus_user.H"

static int fclaw_package_id;

static int
torus_checkparms (int example)
{
    if (example < 1 || example > 4) {
        fclaw_global_essentialf ("Option --example must be 1, 2, 3 or 4\n");
        return -1;
    }

    return 0;
}

int
main (int argc, char **argv)
{
  sc_MPI_Comm              mpicomm;
  sc_options_t             *options;
  fclaw_app_t *app;
  p4est_connectivity_t     *conn = NULL;
  fclaw2d_domain_t	   *domain;
  amr_options_t             samr_options, *gparms = &samr_options;

  /* Clawpack options */
  fclaw2d_clawpack_parms_t  sclawpack_parms, *clawpack_parms = &sclawpack_parms;

  /* Mapping options */
  fclaw2d_map_context_t    *cont = NULL, *brick = NULL;
  fclaw2d_map_data_t        smap_data, *map_data = &smap_data;

  /* Example options */
  int example, retval;
  double pi = M_PI;

  /* Mapping variables */
  double rotate[2];
  double alpha, beta;  /* Ratio of torus inner radius to outer radius */
  const char* latitude_string, *longitude_string;
  double *latitude, *longitude;
  int mi, mj, a,b;
  int verbosity;

  /* initialize application */
  app = fclaw_app_new (&argc, &argv, NULL);
  options = fclaw_app_get_options (app);
  fclaw_package_id = fclaw_get_package_id ();
  mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

#if 0
  lp = SC_LP_PRODUCTION;
  mpicomm = sc_MPI_COMM_WORLD;
  fclaw_mpi_init (&argc, &argv, mpicomm, lp);

  options = sc_options_new (argv[0]);
#endif

  /* -------------------------------------------------------------
     - Register variables from [main]
     ------------------------------------------------------------- */
  sc_options_add_int (options, 0, "main:example", &example, 0,
                      "[main] 1 = cart; 2 = torus; 3 = lat-long; 4 = annulus [2]");

  sc_options_add_double (options, 0, "main:alpha", &alpha, 0.4,
                         "[main] Ratio r/R, r=outer radius, R=inner radius " \
                         "(used for torus) [0.4]");

  fclaw_options_add_double_array(options, 0, "main:latitude", &latitude_string,
                                 "-50 50", &latitude, 2,
                                 "[main] Latitude range (degrees) [-50 50]");

  fclaw_options_add_double_array(options, 0, "main:longitude", &longitude_string,
                                 "0 360", &longitude, 2,
                                 "[main] Longitude range (degrees) [0 360]");

  sc_options_add_double (options, 0, "main:beta", &beta, 0.4,
                         "[main] Inner radius of annulus [0.4]");

  /* [Options] Register general ForestClaw options */
  fclaw_options_register(options,gparms);

  /* [mapping] Register general mapping data */
  fclaw2d_register_map_data(options,map_data);

  /* [clawpack46] Register solver options */
  clawpack46_options_register(options,clawpack_parms);

  /* Set verbosity options */
  fclaw_set_verbosity(options,&verbosity,FCLAW_VERBOSITY_SILENT);

  /* -------------------------------------------------------------
     - Read options from fclaw_options.ini
     - Parse command line
     - postprocess array input
     - checkparms
     ------------------------------------------------------------- */
  retval = fclaw_options_read_from_file(options);
  retval = retval || fclaw_options_parse_command_line (options,argc, argv);

  fclaw_options_postprocess(gparms);
  clawpack46_postprocess_parms(clawpack_parms);
  fclaw2d_options_postprocess_map_data(map_data);

  if (example == 3)
  {
      fclaw_options_convert_double_array (latitude_string, &latitude,2);
      fclaw_options_convert_double_array (longitude_string, &longitude,2);
  }

  retval = retval || fclaw_options_check (options, gparms);
  retval = retval || clawpack46_checkparms(options,clawpack_parms,gparms);
  retval = retval || torus_checkparms (example);  /* Nothing more to check here */
  /* -------------------------------------------------------------
     - Run program
     ------------------------------------------------------------- */
  if (!retval)
  {
      /* set verbosity levels */
      sc_package_set_verbosity (sc_package_id, FCLAW_VERBOSITY_ESSENTIAL);
      sc_package_set_verbosity (p4est_package_id, FCLAW_VERBOSITY_ESSENTIAL);
      sc_package_set_verbosity (fclaw_package_id, verbosity);

      /* Only print options if verbosity >= info */
      fclaw_options_print_summary(options);

      if (gparms->trapfpe == 1)
      {
          fclaw_global_infof("Enabling floating point traps\n");
          feenableexcept(FE_INVALID);
      }

      if (gparms->mpi_debug == 1)
      {
          fclaw2d_mpi_debug();
      }

      /* ---------------------------------------------------------------
         Mapping geometry
         --------------------------------------------------------------- */
      mi = map_data->mi;
      mj = map_data->mj;
      rotate[0] = pi*map_data->theta/180.0;
      rotate[1] = pi*map_data->phi/180.0;
      a = map_data->periodic_x;
      b = map_data->periodic_y;

      switch (example)
      {
      case 1:
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_cart(brick,map_data->scale,map_data->shift,rotate);
          break;
      case 2:
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_torus(brick,map_data->scale,map_data->shift,rotate,alpha);
          break;
      case 3:
          /* Lat-long example */
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_latlong(brick,map_data->scale,map_data->shift,
                                         rotate,latitude,longitude,a,b);
          break;
      case 4:
          /* Annulus */
          conn = p4est_connectivity_new_brick(mi,mj,a,b);
          brick = fclaw2d_map_new_brick(conn,mi,mj);
          cont = fclaw2d_map_new_annulus(brick,map_data->scale,map_data->shift,
                                         rotate,beta);
          break;

      default:
          SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
      }

      domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

      /* ---------------------------------------------------------- */
#if 0
      /* TODO : Replace this with an updated version? */
      if (gparms->verbosity > 0)
      {
          fclaw2d_domain_list_levels(domain, lp);
          fclaw2d_domain_list_neighbors(domain, lp);
      }
#endif

      /* ---------------------------------------------------------------
         Set domain data.
         --------------------------------------------------------------- */
      init_domain_data(domain);

      set_domain_parms(domain,gparms);
      set_clawpack_parms(domain,clawpack_parms);

      link_problem_setup(domain,torus_problem_setup);

      torus_link_solvers(domain);

      link_regrid_functions(domain,
                            torus_patch_tag4refinement,
                            torus_patch_tag4coarsening);
      amrinit(&domain);
      amrrun(&domain);
      amrreset(&domain);

      fclaw2d_map_destroy(cont);
  }

  /* Destroy arrays used in options  */
  if (example == 3)
  {
      fclaw_options_destroy_array((void*) latitude);
      fclaw_options_destroy_array((void*) longitude);
  }

  fclaw2d_map_destroy_arrays(map_data);
  fclaw_options_destroy_arrays (gparms);
  fclaw2d_clawpack_parms_delete(clawpack_parms);

#if 0
  sc_options_destroy (options);
  fclaw_mpi_finalize ();
#endif

  fclaw_app_destroy (app);

  return 0;
}
<|endoftext|>