hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d85065ed52c0a907164cb7450cd5652f31fdc2a | 5,596 | cpp | C++ | cpp/cpp_libs/src/eigen_lib.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | cpp/cpp_libs/src/eigen_lib.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | cpp/cpp_libs/src/eigen_lib.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | /**
* @file eigen_lib.cpp
* @author Maximilian Harr <maximilian.harr@daimler.com>
* @date 08.01.2016
*
* @brief Performs linear algebra calculations using Eigen library
*
*
*
* Coding Standard:
* wiki.ros.org/CppStyleGuide
* https://google.github.io/styleguide/cppguide.html
*
*
* @bug
*
*
* @todo
*
*
*/
// PRAGMA
// SYSTEM INCLUDES
#include <iostream> /* Header that defines the standard input/output stream objects */
#include <cstdlib> /* Header that defines several general purpose functions */
#include <string>
#include <eigen3/Eigen/Dense> /* template library for linear algebra http://eigen.tuxfamily.org */
#include <math.h> /* Defines M_PI for pi value */
#include <eigen3/Eigen/Eigenvalues>
// PROJECT INCLUDES
// LOCAL INCLUDES
// FORWARD REFERENCES
// FUNCTION PROTOTYPES
/** @brief Standard command line parameter processing.
* @param Pass command line parameters
* @return 0 if -h flag is set
*/
int cmd_check(int, char*[]);
// GLOBAL VARIABLES
using namespace Eigen;
using namespace std;
/** @brief Function that returns eigen vector
* @param
* @return
*/
void eigen_fun(Eigen::MatrixXd& mat)
{
mat = MatrixXd::Zero(2,2);
}
//// MAIN //////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
/* Check command line options. Stop execution if -h is set. */
if(!cmd_check(argc,argv)) return 0;
/* */
MatrixXd mat(3,3); // MatrixSizeType (d=double, f=float, i=int, ...)
Matrix2d mat2 = Matrix2d::Constant(0.1);
mat << 1, 2, 3,
4, 5, 6,
7, 8, 9;
cout << "Diagonal of mat2: \n" << mat.diagonal() << "\n";
mat(2,2) = 10; /* Start counting at 0 */
VectorXd vec(3);
vec << 1,2,3;
cout << "Here is mat*vec:\n" << mat*vec << endl;
cout << "Here is vec . vec:\n" << vec.dot(vec) << endl;
/* see also +,-,*,dot(),cross(),sum(),prod(),maxCoeff(),minCoeff(),mean(),trace(),diagonal(),
* rows(),cols(),size(),transpose(),
*/
cout << "This is mat:\n" << mat << "\n";
cout << "Take a block from mat:\n" << mat.block(1,1,2,2) << "\n"; // (pos,pos,size,size)
cout << "Take a block from vec:\n" << vec.head(2) << "\n";
mat.block(1,1,2,2)=mat2.block(0,0,2,2);
std::cout << "Insert mat2 in mat:\n" << mat << "\n";
// Norm computations
/* norm(),lpnorm(),lpNorm(),squaredNorm(),*/
// Boolean reducations
/* all(), any(), count() */
// Solving (http://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html)
/* colPivHouseholder(),fullPivHouseholder(),eigenvectors(),eigenvalues(),AdjointEigenSolver,
* determinant(),inverse(),solve(),SVD,QR,Cholesky,compute(),llt() ...
* See also: http://eigen.tuxfamily.org/dox/group__TopicLinearAlgebraDecompositions.html
*/
Matrix3f A;
Vector3f b;
A << 1,2,3, 4,5,6, 7,8,10;
b << 3, 3, 4;
cout << "Here is the matrix A:\n" << A << endl;
cout << "Index A(0,1): " << A(0,1) << endl;
cout << "Here is the vector b:\n" << b << endl;
Vector3f x = A.fullPivHouseholderQr().solve(b);
cout << "The solution is:\n" << x << endl;
double relative_error = (A*x - b).norm() / b.norm(); // norm() is L2 norm
cout << "The relative error is:\n" << relative_error << endl;
// Furthermore (Sparse matrix manipulation, sparse linear systems,
/* Jacobi Rotation, Householder transformation, */
/* Nonlinear optimization (see /usr/include/eigen3/unsupported/Eigen)
* (http://eigen.tuxfamily.org/dox/unsupported/group__NonLinearOptimization__Module.html)
* eg. LevenbergMarquardt */
/* TRANSFORMATIONS
* Rotation2D,AngleAxis (3D Rotation) Quaternion,Scaling,Translation,Affine Transformation,
* rotate(),tranlate(),
*/
Matrix2f m;
m = Rotation2Df(M_PI/2); /* roation in rad */
std::cout << "2d roation with 90 degree\n" << m << "\n";
/* Eigen Namespace: http://eigen.tuxfamily.org/dox/namespaceEigen.html */
MatrixXd mat4;
eigen_fun(mat4);
MatrixXd iden;
iden = MatrixXd::Identity(6,6);
cout << "iden is: \n" << iden << "\n";
cout << "This is A: \n" << A << "\n";
cout << "This is A squared: \n" << A.cwiseProduct(A) << "\n";
//VectorXcd eivals = A.eigenvalues();
cout << "Eigenvalues of A: \n" << A.eigenvalues() << "\n";
iden(5,5)=0;
FullPivLU<MatrixXd> lu(iden);
cout << "Rank of iden: " << lu.rank() << "\n";
Eigen::MatrixXd mat5 = Eigen::MatrixXd::Identity(3,3);
mat5(1,1) = 2;
mat5(2,2) = 4;
Eigen::MatrixXd mat_llt = Eigen::MatrixXd::Zero(3,3);
std::cout << "mat5:\n" << mat5 << std::endl;
mat_llt = mat5.llt().matrixL();
std::cout << "mat5.llt().matrixL():\n" << mat_llt << std::endl;
mat_llt = mat_llt.inverse();
std::cout << "mat5.inverse():\n" << mat_llt << std::endl;
return 0;
}
//// FUNCTION DEFINITIONS //////////////////////////////////////////////////////////////////////////
int cmd_check(int argc, char* argv[])
{
int option;
/* third argument of getopt specifies valid options and whether they need input(:) */
while((option = getopt(argc,argv,"hp:"))>=0)
{
switch (option)
{
case 'h': std::cout
<< "Usage: <filename> [options] \n\n"
<< "<desription> \n\n"
<< "Options: \n"
<< " -h show this help message and exit \n"
<< " -p <PARAMETER> <description> \n"
<< " \n";
return 0; /* do not execute main with this option */
case 'p': std::cout << "-p = " << optarg << "\n"; /* optarg is option argument */
break;
}
}
return 1;
}
| 30.917127 | 100 | 0.579164 | [
"vector",
"3d"
] |
0d88b6c9417b9608352ec31fba8d3712ca59b306 | 5,887 | cpp | C++ | Inheritance/Lesson1 abstract_interface_concrete/abstract_interface_concrete.cpp | Geek-a-Byte/Daily-Coding-Problems | d4c3147de4c345040c4b5dffebd72cd79bcfb8c4 | [
"MIT"
] | 1 | 2021-02-14T13:27:57.000Z | 2021-02-14T13:27:57.000Z | Inheritance/Lesson1 abstract_interface_concrete/abstract_interface_concrete.cpp | Geek-a-Byte/OOP | d4c3147de4c345040c4b5dffebd72cd79bcfb8c4 | [
"MIT"
] | null | null | null | Inheritance/Lesson1 abstract_interface_concrete/abstract_interface_concrete.cpp | Geek-a-Byte/OOP | d4c3147de4c345040c4b5dffebd72cd79bcfb8c4 | [
"MIT"
] | null | null | null | //very imp source: https://www.codesdope.com/cpp-virtual-and-abstract/
/*
//*Runtime polymorphism
Runtime polymorphism is also known as dynamic polymorphism.
In runtime polymorphism, the compiler matches the function call with the correct
function definition at runtime, it is also called late binding/dynamic binding/runtime binding
In C++, runtime polymorphism is implemented using method overriding.
in late binding, the compiler identifies the type of object at runtime and then matches the function
call with correct function definition.this can be achieved by virtual function in base class which is
overridden in one of the derived classes or variable overriding
//*compile time polymorphism
In compile time or static polymorphism or
early binding, the compiler matches the function call
with the function definition which has been called during compile time.
It is also known as Static Binding or Compile-time Binding.
i.e the compiler matches the function call considering the type of pointer
and not considering the type of object which it is pointing to
*/
/*
//*Function overriding
If derived class re-defines same function as defined in its base class,
it is known as function overriding in C++. It is used to achieve runtime polymorphism.
It enables you to provide specific implementation of the base class function.
The second thing is that the function from a base class that we are overriding
should have the same signature or prototype
i.e. it should have the same name, same return type and same argument list.
*/
/*
//*VIRTUAL FUNCTION
//*1.A virtual function is a member function which is declared/defined in the base class
using the keyword virtual
and is re-defined (Overriden) by the derived class.
//*2.SYNTAX: virtual<func_type><func_name>() {}
//*3.Classes having virtual functions are not abstract i.e it can be instantiated.Definition is given in base class.
//*4.All derived class may or may not redefine virtual function of base class.
//*virtual functions are called according to the type of the obj instance pointed to or referenced
not according to the type of the pointer or reference
//*5.example : https://www.programiz.com/cpp-programming/virtual-functions
//*here when base class pointer is pointing to derived class object then the print() of derived class is being called upon, so
it depends on the type of object which is pointed to , not the type of pointers
*/
/*
//*PURE VIRTUAL FUNCTION
//*1.A pure virtual function is a member function of base class
whose only declaration is provided in base class
and should be defined in derived class otherwise derived class also becomes abstract.
//*2.SYNTAX: virtual<func_type><func_name>() = 0;
//*3.Base class having pure virtual function becomes abstract i.e. it cannot be instantiated.No definition is given in base class.
//*4.If derived class do not redefine pure virtual function of base class,
then no compilation error but derived class also becomes abstract just like the base class.
//*5.a pure virtual function (or abstract function) has no body at all
*/
/*
//*ABSTRACT CLASS
//*1.An abstract class has at least one abstract function (pure virtual function).
//*2.Abstract class is also known as abstract base class.
//*3.In an abstract class, we can also have other functions and variables apart from pure virtual function.(diff with interface)
//*4.Subclasses of an abstract base class must define the abstract function(pure v.f of abstract base class), otherwise, they will also become abstract classes.
//*5.An abstract class is a class whose instances (objects) can't be made. We can only make objects of its subclass (if they are not abstract).
//*6.abstract classes can have constructors
//*7.we can create a reference variable of an abstract class,
that reference var can be used to refer to the objects of derived class
//*ex:Derived d1; base* b1; b1=&d1; BUT we cant write base b1; as base is an abstract class it will not have objects
//*8.abstract class is used to provide abstraction to the code
meaning to hide the implementation and show the function definition to the user only
*/
/*
//*INTERFACE
//*1.Interface or Interface class is an ABSTRACT CLASS which has no member variables
//*2.and all its functions are pure virtual and
//*3.Its derived classes must provide definition to each of the pure virtual functions of the base class.
//*4.Like an abstract class, we can't create objects of an interface.
//*Name of an interface class often begins with the letter I.example Ishape
//*interfaces cannot have constructors(as cons are member functions but not pvf)
*/
/*
//*CONCRETE CLASS
//*A concrete class is an ordinary class which has no purely virtual functions and hence can be instantiated(I.E CAN HAVE OBJECTS OF ITS OWN).
*/
#include <iostream>
using namespace std;
class base
{
public:
base()
{
cout << "base\n";
}
//if the base() is commented out this class would be an interface otherwise it is abstract
virtual void f1() = 0; // pure virtual function
virtual void f2() = 0; // pure virtual function
};
class derived1 : public base // abstract class - derived1 has no f2() definition
{
public:
derived1()
{
cout << "derived1 default constructor\n";
}
void f1()
{
cout << "f1 is defined\n";
}
};
class derived2 : public derived1 //concrete class .. because f1() was already defined in derived1
{
public:
derived2()
{
cout << "derived2 default constructor\n";
}
void f2()
{
cout << "f2 is defined" << endl;
}
};
int main()
{
//base b; //obj of an abstract base class is not allowed
//derived1 d1; not ok //derived1 is also abstract
derived2 d2;
d2.f1();
d2.f2();
return 0;
}
/*
base
derived1 default constructor
derived2 default constructor
f1 is defined
f2 is defined
*/ | 40.6 | 160 | 0.744692 | [
"object"
] |
0d89f44efdbb54fa85abc37aa30d860670358bb6 | 4,479 | cpp | C++ | src/main.cpp | tomaszmj/openglpress | 3e3f57197c185188f4fd2058c5b2b4dc7e4e85b9 | [
"MIT"
] | null | null | null | src/main.cpp | tomaszmj/openglpress | 3e3f57197c185188f4fd2058c5b2b4dc7e4e85b9 | [
"MIT"
] | null | null | null | src/main.cpp | tomaszmj/openglpress | 3e3f57197c185188f4fd2058c5b2b4dc7e4e85b9 | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include <ShaderProgram.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <Textures.h>
#include <SimpleCubeModel.h>
#include <CubeModel.h>
#include <CubeModelInside.h>
#include <CylinderModel.h>
#include <VAOWrapper.h>
#include <RenderedObject.h>
#include <Window.h>
#include <Scene.h>
#include <ModelMatrix.h>
#include <AnimationParameters.h>
#include <Piston.h>
#include <CrushedCylinder.h>
// This program a priori uses only C++11, so std::make_unique may not be supported.
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
void run()
{
Window window("gkom press", 800, 600);
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK)
throw std::runtime_error("GLEW Initialization failed");
ShaderProgram light_source_shader("resources/shaders/light_source.vert", "resources/shaders/light_source.frag");
ShaderProgram metal_shader("resources/shaders/object.vert", "resources/shaders/metal.frag");
ShaderProgram wood_shader("resources/shaders/object.vert", "resources/shaders/wood.frag");
ShaderProgram crushing_shader("resources/shaders/crushing.vert", "resources/shaders/metal.frag");
Textures textures({"resources/textures/wood.png", "resources/textures/metal.png"});
VAOWrapper vao_wrapper_simple_cube((SimpleCubeModel()));
VAOWrapper vao_wrapper_cube((CubeModel()));
VAOWrapper vao_wrapper_cube_inside((CubeModelInside()));
VAOWrapper vao_wrapper_cylinder(CylinderModel(200, 100));
ModelMatrix background, light_source, press_base_cube, press_back, press_top, press_base_cylinder;
background.setScale(glm::vec3(30.0f, 30.0f, 30.0f));
background.setTranslation(glm::vec3(0.0f, 14.9999f, 0.0f));
light_source.setTranslation(glm::vec3(14.49f, 29.49f, 14.49f));
press_base_cube.setScale(glm::vec3(2.0f, 0.5f, 2.0f));
press_base_cube.setTranslation(glm::vec3(0.0f, 0.25f, 0.0f));
press_base_cylinder.setScale(glm::vec3(1.5f, 0.25f, 1.5f));
press_base_cylinder.setTranslation(glm::vec3(0.0f, 0.625f, 0.0f));
press_back.setScale(glm::vec3(3.0f, 2.5f, 2.0f));
press_back.setTranslation(glm::vec3(-2.5f, 1.25f, 0.0f));
press_top.setScale(glm::vec3(5.0f, 1.5f, 2.0f));
press_top.setTranslation(glm::vec3(-1.5f, 3.25f, 0.0f));
AnimationParameters animation_parameters({1, 4, 5, 7}, {1.9, 1.7, 1.2});
std::unique_ptr<RenderedObject> piston(new Piston(metal_shader, vao_wrapper_cylinder,
textures[1], glm::vec3(1.0f, 2.0f, 1.0f), animation_parameters));
std::unique_ptr<RenderedObject> crushed_cylinder(new CrushedCylinder(crushing_shader, vao_wrapper_cylinder,
textures[1], glm::vec3(0.5f, 0.0f, 0.5f), animation_parameters, 0.75f));
Scene scene;
scene.setUpLightSource(glm::vec3(14.49f, 29.49f, 14.49f), glm::vec3(1.0));
scene.addObject(make_unique<RenderedObject>(light_source_shader, vao_wrapper_simple_cube, light_source, textures[-1]));
scene.addObject(make_unique<RenderedObject>(wood_shader, vao_wrapper_cube_inside, background, textures[0]));
scene.addObject(make_unique<RenderedObject>(metal_shader, vao_wrapper_cube, press_base_cube, textures[1]));
scene.addObject(make_unique<RenderedObject>(metal_shader, vao_wrapper_cube, press_back, textures[1]));
scene.addObject(make_unique<RenderedObject>(metal_shader, vao_wrapper_cube, press_top, textures[1]));
scene.addObject(make_unique<RenderedObject>(metal_shader, vao_wrapper_cylinder, press_base_cylinder, textures[1]));
scene.addObject(std::move(piston));
scene.addObject(std::move(crushed_cylinder));
glEnable(GL_DEPTH_TEST);
while(!window.shouldClose())
{
window.processInput();
scene.update(window);
window.clearColor(0.1f, 0.1f, 0.1f, 0.0f);
scene.render(window);
window.swapBuffers();
}
}
int main()
{
if(glfwInit() != GL_TRUE)
{
std::cout << "GLFW initialization failed" << std::endl;
return -1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
try
{
run();
}
catch(std::exception &ex)
{
std::cout << ex.what() << std::endl;
getchar();
}
glfwTerminate();
return 0;
}
| 38.947826 | 123 | 0.710203 | [
"render",
"object"
] |
0d8dc0177c9817ba66271bc65e8609d91ad4b0d9 | 19,853 | cpp | C++ | Cpp/Docker/Mangler.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 5 | 2019-08-19T18:18:08.000Z | 2019-12-13T19:26:03.000Z | Cpp/Docker/Mangler.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 3 | 2019-04-15T19:24:36.000Z | 2020-02-29T13:09:07.000Z | Cpp/Docker/Mangler.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 2 | 2019-10-08T23:16:05.000Z | 2019-12-18T22:58:04.000Z | #include "../../H/Docker/Mangler.h"
#include "../../H/Nodes/Node.h"
#include <iomanip>
#include <sstream>
vector<pair<string, vector<pair<string, pair<int, string>>>>> MANGLER::IDS;
bool Functoin_Name_Is_Before_End_Of_Namespace = false;
string MANGLER::Un_Mangle(string raw) {
//try to find if there are any prefixes and remove them into another string
string PreFix;
if ((int)raw.find_last_of(' ') >= 0) {
int pre_i = (int)raw.find_last_of(' ');
PreFix = raw.substr(0, (size_t)pre_i + 1);
raw = raw.substr((size_t)pre_i + 1, raw.size());
}
bool Func_Name = true;
bool Namespace = false;
string Function = "";
vector<string> Parenthesis;
string Return_Type = "";
string Current;
string Current_Variable = "";
string Current_PreFix = "";
string Current_Complex_Name = "";
vector<string> Scope_Path;
string STD = "";
vector<string> Current_Parameter_Inheritted;
bool Return_Type_Section = false;
//type ptr new type
if (raw[0] == '_' && raw[1] == 'Z') {
//C++ unmangler
//_Z3NEWi3ABC
STD = "cpp";
vector<pair<string, pair<int, string>>>& Current_IDS = *Find_STD_List(STD);
for (int i = 2; i < raw.size(); i++) {
Current = raw[i];
Current_Complex_Name += raw[i];
//for char based aliases.
if (Find(Current, &Current_IDS) != nullptr) {
if (Find(Current, &Current_IDS)->first == MANGLER::VARIABLE) {
//when a new variable starts appearing we want to push the previus into the function-
//parameters string.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
Current_PreFix = "";
}
Current_Complex_Name = "";
if (Current_PreFix != "")
Current_Variable = Current_PreFix + " ";
Current_Variable += Find(Current, &Current_IDS)->second + " ";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::POSTFIX) {
Current_Variable += Find(Current, &Current_IDS)->second + " ";
Current_Complex_Name = "";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::PREFIX) {
if (Current_Variable != "")
Parenthesis.push_back(Current_Variable);
Current_PreFix += Find(Current, &Current_IDS)->second + " ";
Current_Complex_Name = "";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::CLASS && Current_Complex_Name.size() == 1) {
Namespace = true;
if (Functoin_Name_Is_Before_End_Of_Namespace)
Func_Name = false;
}
else if (Find(Current, &Current_IDS)->first == MANGLER::END_CLASS && Current_Complex_Name.size() == 1) {
Namespace = false;
}
}
else if (Find(Current, &Current_IDS) != nullptr) {
//for multi char based aliases.
if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::VARIABLE) {
//when a new variable starts appearing we want to push the previus into the function-
//parameters string.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current = "";
if (Current_PreFix != "")
Current_Variable = Current_PreFix + " ";
Current_Variable += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
else if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::POSTFIX) {
Current = "";
Current_Variable += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
else if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::PREFIX) {
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current = "";
Current_PreFix += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
}
//TODO: add that if the current complex name is bigger than 2(.., current num) then dont do this.
else if (((raw[i] >= 48) && (raw[i] <= 57))) {
string tmp = "";
tmp += raw[i];
for (int j = i + 1; j < raw.size(); j++) {
if (((raw[j] >= 48) && (raw[j] <= 57)))
tmp += (char)raw[j];
else
break;
}
int size = atoi(tmp.c_str());
string name = "";
for (int j = i + (int)tmp.size(); (j < (size + i + (int)tmp.size())) && j < (int)raw.size(); j++) {
name += (char)raw[j];
}
if (Namespace) {
Scope_Path.push_back(name);
}
else if (Func_Name) {
Function = name;
Func_Name = false;
}
else {
//class based parameters.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current_Variable = Current_PreFix + " " + name;
}
i += size + (int)tmp.size() - 1;
}
}
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
}
}
//else if (raw[0] == '_' && raw[1] == 'E') {
// STD = "evie";
//}
else if (raw[0] == '_' && raw[1] == 'V') {
STD = "vivid";
vector<pair<string, pair<int, string>>>& Current_IDS = *Find_STD_List(STD);
for (int i = 2; i < raw.size(); i++) {
Current = raw[i];
Current_Complex_Name += raw[i];
//for char based aliases.
if (Find(Current, &Current_IDS) != nullptr) {
if (Find(Current, &Current_IDS)->first == MANGLER::VARIABLE) {
//when a new variable starts appearing we want to push the previus into the function-
//parameters string.
if (Current_Variable != "") {
if (Return_Type_Section) {
Return_Type += " " + Current_Variable;
Current_Variable = "";
Current_PreFix = "";
}
else {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
Current_PreFix = "";
}
}
Current_Complex_Name = "";
if (Current_PreFix != "")
Current_Variable = Current_PreFix + " ";
Current_Variable += Find(Current, &Current_IDS)->second + " ";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::POSTFIX) {
Current_Variable += Find(Current, &Current_IDS)->second + " ";
Current_Complex_Name = "";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::PREFIX) {
if (Current_Variable != "")
Parenthesis.push_back(Current_Variable);
Current_PreFix += Find(Current, &Current_IDS)->second + " ";
Current_Complex_Name = "";
Current_Variable = "";
}
else if (Find(Current, &Current_IDS)->first == MANGLER::CLASS && Current_Complex_Name.size() == 1) {
Namespace = true;
if (Functoin_Name_Is_Before_End_Of_Namespace)
Func_Name = false;
}
else if (Find(Current, &Current_IDS)->first == MANGLER::END_CLASS && Current_Complex_Name.size() == 1) {
Namespace = false;
}
}
else if (Find(Current, &Current_IDS) == nullptr && Current_Complex_Name.size() > 1 && Find(Current_Complex_Name, &Current_IDS) != nullptr) {
//for multi char based aliases.
if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::VARIABLE) {
//when a new variable starts appearing we want to push the previus into the function-
//parameters string.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current = "";
if (Current_PreFix != "")
Current_Variable = Current_PreFix + " ";
Current_Variable += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
else if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::POSTFIX) {
Current = "";
Current_Variable += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
else if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::PREFIX) {
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current = "";
Current_PreFix += Find(Current_Complex_Name, &Current_IDS)->second + " ";
}
else if (Find(Current_Complex_Name, &Current_IDS)->first == MANGLER::RETURN) {
//_rPh -> ptr char xxxx(xxxx)
Return_Type_Section = true;
//check if there is anything left before this return type decl.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
Current = "";
}
}
}
//TODO: add that if the current complex name is bigger than 2(.., current num) then dont do this.
else if (((raw[i] >= 48) && (raw[i] <= 57))) {
string tmp = "";
tmp += raw[i];
for (int j = i + 1; j < raw.size(); j++) {
if (((raw[j] >= 48) && (raw[j] <= 57)))
tmp += (char)raw[j];
else
break;
}
int size = atoi(tmp.c_str());
string name = "";
for (int j = i + (int)tmp.size(); (j < (size + i + (int)tmp.size())) && j < (int)raw.size(); j++) {
name += (char)raw[j];
}
if (Namespace) {
Scope_Path.push_back(name);
}
else if (Func_Name) {
Function = name;
Func_Name = false;
}
else if (Return_Type_Section) {
Return_Type += " " + name;
}
else {
//class based parameters.
if (Current_Variable != "") {
Parenthesis.push_back(Current_Variable);
Current_Variable = "";
}
Current_Variable = Current_PreFix + " " + name;
}
i += size + (int)tmp.size() - 1;
}
//else if (Current_Variable != "") {
// Parenthesis.push_back(Current_Variable);
//}
}
if (Current_Variable != "") {
if (Return_Type_Section)
Return_Type += " " + Current_Variable;
else
Parenthesis.push_back(Current_Variable);
}
if (Return_Type != "")
PreFix = "";
}
else {
//this lauches when no call type is identifyed.
Function = raw;
}
//if the return type only has ptr then add 'type' keyword for template returning
if (Return_Type == "ptr")
Return_Type = "type ptr";
string Result = Return_Type + " " + STD + " ";
if (Scope_Path.size() > 0 && Functoin_Name_Is_Before_End_Of_Namespace) {
Function = Scope_Path.back();
Scope_Path.pop_back();
}
for (auto s : Scope_Path)
Result += s + ".";
Result += Function + "( ";
for (int i = 0; i < ((int)Parenthesis.size()) - 1; i++) {
Result += Parenthesis[i] + ", ";
}
if (Parenthesis.size() > 0)
Result += Parenthesis.back();
Result += ")";
return PreFix + Result;
}
vector<string> Classes;
string MANGLER::Mangle(Node* raw, string Force_Complex)
{
string Result = "";
if (raw->is("vivid") || raw->Scope->is("vivid") || Force_Complex == "vivid") {
string STD = "vivid";
if (raw->is(FUNCTION_NODE) || raw->is(IMPORT) || raw->is(PROTOTYPE)) {
Classes.clear();
Result = "_V";
if (raw->Scope->is(CLASS_NODE) && raw->Scope->Name != "GLOBAL_SCOPE") {
Result += "N";
for (auto i : raw->Get_Scope_Path())
Result += to_string(i->Name.size()) + i->Name;
Result += to_string(raw->Name.size()) + raw->Name;
Result += "E";
}
else if (raw->Fetcher != nullptr) {
Result += "N";
for (auto i : raw->Get_All_Fetchers())
Result += to_string(i->Name.size()) + i->Name;
Result += to_string(raw->Name.size()) + raw->Name;
Result += "E";
}
else
Result += to_string(raw->Name.size()) + raw->Name;
if (raw->Parameters.size() < 1)
Result += "v";
for (auto i : raw->Parameters) {
Result += Mangle(i, "vivid");
}
bool Mark_Return_Type = false;
if (raw->Inheritted.size() > 0)
for (auto i : raw->Inheritted) {
if (Lexer::GetComponent(i).is(Flags::KEYWORD_COMPONENT)) {
if (i == "ptr")
Mark_Return_Type = true;
}
else
Mark_Return_Type = true;
}
if (Mark_Return_Type)
Result += "_r";
for (auto i : raw->Inheritted) {
if (Lexer::GetComponent(i).is(Flags::KEYWORD_COMPONENT)) {
if (i == "ptr")
Result += Get_Key(i, STD);
}
else if (Get_Key(i, STD) != "")
Result += Get_Key(i, STD);
else
Result += to_string(i.size()) + i;
}
}
else if (raw->is(CLASS_NODE)) {
string p = "";
string r;
if (raw->is("ptr")) {
for (auto i : raw->Inheritted) {
if (i == "ptr")
p += "P";
}
r = p + r;
}
if (Is_Base_Type(raw)) {
return p + Get_Key(raw->Name, STD);
}
else {
if (Find_Classes(raw->Name) != -1) {
stringstream stream;
stream << hex << Find_Classes(raw->Name);
r = "S" + string(stream.str()) + "_";
}
else
r = to_string(raw->Name.size()) + raw->Name;
return r;
}
}
else if (raw->is(OBJECT_DEFINTION_NODE) || raw->is(OBJECT_NODE) || raw->is(PARAMETER_NODE)) {
int I = 0;
string p = "";
if (raw->is("ptr")) {
for (auto i : raw->Inheritted) {
if (i == "ptr")
p += "P";
}
}
for (auto i : raw->Inheritted) {
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
I++;
if (I > 1) {
//PcIic = char int char ptr a
//Evie engine 3.0.0 cannot export multi inheritted variables yet.
//TODO: Make that happen.
throw::runtime_error("Exporting multi inheritted variables is not yet supported.");
}
}
if (Is_Template(raw)) {
//uugabuuga?
Result = p + "t";
}
else if (Is_Based_On_Base_Type(raw)) {
//int a;
string Type = "";
for (auto i : raw->Inheritted)
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
Type = i;
Result = p + string(Type.data(), 1);
}
else {
//banana a;
string Type = "";
for (auto i : raw->Inheritted)
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
Type = i;
Result = p + to_string(Type.size()) + Type;
}
}
}
else if (raw->is("evie") || raw->Scope->is("evie")){
//if the function call uses the Evie standard.
}
else if (raw->is("plain") || raw->Scope->is("plain")) {
//generic name labels for normal .
Result = raw->Name;
}
else /*((raw->is("cpp") != -1) || (raw->Scope->is("cpp") != -1) || Force_Complex == "cpp")*/ {
//if the function call uses the C standard.
//_import_func_cpp_internal_print__char__int to
//_Z14internal_printPci
if (raw->is(FUNCTION_NODE) || raw->is(IMPORT) || raw->is(PROTOTYPE)) {
Classes.clear();
Result = "_Z";
if (raw->Scope->is(CLASS_NODE) && raw->Scope->Name != "GLOBAL_SCOPE") {
Result += "N";
for (auto i : raw->Get_Scope_Path())
Result += to_string(i->Name.size()) + i->Name;
Result += to_string(raw->Name.size()) + raw->Name;
Result += "E";
}
else if (raw->Fetcher != nullptr) {
Result += "N";
for (auto i : raw->Get_All_Fetchers())
Result += to_string(i->Name.size()) + i->Name;
Result += to_string(raw->Name.size()) + raw->Name;
Result += "E";
}
else
Result += to_string(raw->Name.size()) + raw->Name;
if (raw->Parameters.size() < 1)
Result += "v";
for (auto i : raw->Parameters) {
Result += Mangle(i, "cpp");
}
}
else if (raw->is(CLASS_NODE)) {
string p = "";
string r;
if (raw->is("ptr")) {
for (auto i : raw->Inheritted) {
if (i == "ptr")
p += "P";
}
r = p + r;
}
if (Is_Base_Type(raw)) {
return p + string(raw->Name.data(), 1);
}
else {
if (Find_Classes(raw->Name) != -1) {
stringstream stream;
stream << hex << Find_Classes(raw->Name);
r = "S" + string(stream.str()) + "_";
}
else
r = to_string(raw->Name.size()) + raw->Name;
return r;
}
}
else if (raw->is(OBJECT_DEFINTION_NODE) || raw->is(OBJECT_NODE) || raw->is(PARAMETER_NODE)) {
int I = 0;
string p = "";
if (raw->is("ptr")) {
for (auto i : raw->Inheritted) {
if (i == "ptr")
p += "P";
}
}
for (auto i : raw->Inheritted) {
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
I++;
if (I > 1) {
//PcIic = char int char ptr a
//Evie engine 3.0.0 cannot export multi inheritted variables yet.
//TODO: Make that happen.
throw::runtime_error("Exporting multi inheritted variables is not yet supported.");
}
}
if (Is_Template(raw)) {
//uugabuuga?
Result = p + "t";
}
else if (Is_Based_On_Base_Type(raw)) {
//int a;
string Type = "";
for (auto i : raw->Inheritted)
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
Type = i;
Result = p + string(Type.data(), 1);
}
else {
//banana a;
string Type = "";
for (auto i : raw->Inheritted)
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
Type = i;
Result = p + to_string(Type.size()) + Type;
}
}
}
return Result;
}
string MANGLER::Get_Function_Name(string func)
{ //int ptr Start_Test()
int Paranthesis_Index = func.find_first_of('(');
int Name_Index = func.substr(0, Paranthesis_Index).find_last_of(" ") + 1;
return func.substr(Name_Index, Paranthesis_Index - Name_Index);
}
bool MANGLER::Is_Base_Type(Node* n)
{
if (n->is(NUMBER_NODE) || n->is(OPERATOR_NODE) || n->is(ASSIGN_OPERATOR_NODE) || n->is(CONDITION_OPERATOR_NODE) || n->is(BIT_OPERATOR_NODE) || n->is(ARRAY_NODE) || n->is(CALL_NODE))
return false;
bool Result = true;
for (auto i : n->Defined) {
if (i->Name == "size" && i->is("const"))
continue;
else if (i->Name == "format" && i->is("const"))
continue;
else if (i->is(FUNCTION_NODE))
continue;
Result = false;
break;
}
for (auto i : n->Inheritted) {
if (Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
continue;
Result = false; //because base types do not inherit other classes, only features.
break;
}
return Result;
}
bool MANGLER::Is_Based_On_Base_Type(Node* n)
{
bool Result = true;
//int a;
for (auto i : n->Inheritted) {
if (Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT))
continue;
if (!Is_Base_Type(n->Find(i, n->Scope)))
Result = false;
}
return Result;
}
bool MANGLER::Is_Template(Node* n)
{
bool Result = true;
for (auto i : n->Inheritted)
if (!Lexer::GetComponents(i)[0].is(Flags::KEYWORD_COMPONENT)) {
Result = false;
break;
}
return Result;
}
int MANGLER::Find_Classes(string s)
{
for (int i = 0; i < Classes.size(); i++)
if (Classes[i] == s)
return i;
Classes.push_back(s);
return -1;
}
void MANGLER::Add_ID(string Lang, pair<string, pair<int, string>> id) {
if (Find_STD_List(Lang) == nullptr) {
IDS.push_back(pair<string, vector<pair<string, pair<int, string>>>>());
IDS.back().first = Lang;
}
if (Find(id.first, Find_STD_List(Lang)) != nullptr) {
cout << "Warning: ID " << id.first << " already exist's" << endl;
return;
}
else
Find_STD_List(Lang)->push_back(id);
}
string MANGLER::Get_Key(string Val, string Lang)
{
if (!Lexer::GetComponent(Val).is(Flags::KEYWORD_COMPONENT))
if (Is_Base_Type(Global_Scope->Find(Val))) {
string New_Val = to_string(Global_Scope->Find(Val)->Size) + " " + Global_Scope->Find(Val)->Format;
Val = New_Val;
}
for (auto i : *Find_STD_List(Lang)) {
if (i.second.second == Val)
return i.first;
}
return "";
}
vector<pair<string, pair<int, string>>>* MANGLER::Find_STD_List(string Lang)
{
for (auto& i : IDS) {
if (i.first == Lang)
return &i.second;
}
return nullptr;
}
pair<int, string>* MANGLER::Find(string Key, vector<pair<string, pair<int, string>>>* Current_IDS)
{
for (auto& i : *Current_IDS)
if (i.first == Key)
return &i.second;
return nullptr;
}
void MANGLER::Clear_Class_Zipping_List()
{
Classes.clear();
}
| 28.898108 | 183 | 0.573465 | [
"vector"
] |
0d99d29a2aa6179825ea8ac6a4a4b0af2566d6fe | 5,178 | cc | C++ | RAVL2/PatternRec/IO/FunctionIO.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/PatternRec/IO/FunctionIO.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/PatternRec/IO/FunctionIO.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2003, OmniPerception Ltd.
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: FunctionIO.cc 3073 2003-06-13 07:18:32Z craftit $"
//! lib=RavlPatternRecIO
//! file="Ravl/PatternRec/IO/FunctionIO.cc"
#include "Ravl/Vector.hh"
#include "Ravl/PatternRec/Classifier.hh"
#include "Ravl/DP/FileFormatStream.hh"
#include "Ravl/DP/FileFormatBinStream.hh"
#include "Ravl/DP/Converter.hh"
#include "Ravl/Types.hh"
#include "Ravl/PatternRec/Function1.hh"
#include "Ravl/PatternRec/FuncMeanProjection.hh"
#include "Ravl/PatternRec/FuncLinear.hh"
#include "Ravl/PatternRec/FuncQuadratic.hh"
#include "Ravl/PatternRec/FuncOrthPolynomial.hh"
#include "Ravl/PatternRec/FuncLinearCoeff.hh"
#include "Ravl/PatternRec/FuncPDFNormal.hh"
#include "Ravl/DP/Converter.hh"
namespace RavlN {
void InitRavlFunctionIO()
{}
//:- FunctionC -------------------------------------------------------------------------
static TypeNameC type1(typeid(FunctionC),"RavlN::FunctionC");
FileFormatStreamC <FunctionC> FileFormatStream_Function;
FileFormatBinStreamC <FunctionC> FileFormatBinStream_Function;
//:- Function1C -------------------------------------------------------------------------
static TypeNameC type2(typeid(Function1C),"RavlN::Function1C");
FunctionC Function1C2Function(const FunctionC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(Function1C2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::Function1C &)");
FileFormatStreamC <Function1C> FileFormatStream_Function1;
FileFormatBinStreamC <Function1C> FileFormatBinStream_Function1;
//:- FuncMeanProjectionC --------------------------------------------------------------
FunctionC FuncMeanProjection2Function(const FuncMeanProjectionC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncMeanProjection2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncMeanProjectionC &)");
static TypeNameC type3(typeid(FuncMeanProjectionC),"RavlN::FuncMeanProjectionC");
FileFormatStreamC <FuncMeanProjectionC> FileFormatStream_FuncMeanProjection;
FileFormatBinStreamC <FuncMeanProjectionC> FileFormatBinStream_FuncMeanProjection;
//:- FuncLinearC ------------------------------------------------------------------------
FunctionC FuncLinear2Function(const FuncLinearC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncLinear2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncLinearC &)");
static TypeNameC type4(typeid(FuncLinearC),"RavlN::FuncLinearC");
FileFormatStreamC <FuncLinearC> FileFormatStream_FuncLinear;
FileFormatBinStreamC <FuncLinearC> FileFormatBinStream_FuncLinear;
//:- FuncQuadraticC ------------------------------------------------------------------------
FunctionC FuncQuadratic2Function(const FuncQuadraticC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncQuadratic2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncQuadraticC &)");
static TypeNameC type5(typeid(FuncQuadraticC),"RavlN::FuncQuadraticC");
FileFormatStreamC <FuncQuadraticC> FileFormatStream_FuncQuadratic;
FileFormatBinStreamC <FuncQuadraticC> FileFormatBinStream_FuncQuadratic;
//:- FuncOrthPolynomialC ------------------------------------------------------------------------
FunctionC FuncOrthPolynomial2Function(const FuncOrthPolynomialC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncOrthPolynomial2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncOrthPolynomialC &)");
static TypeNameC type6(typeid(FuncOrthPolynomialC),"RavlN::FuncOrthPolynomialC");
FileFormatStreamC <FuncOrthPolynomialC> FileFormatStream_FuncOrthPolynomial;
FileFormatBinStreamC <FuncOrthPolynomialC> FileFormatBinStream_FuncOrthPolynomial;
//:- FuncLinearCoeffC ------------------------------------------------------------------------
FunctionC FuncLinearCoeff2Function(const FuncLinearCoeffC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncLinearCoeff2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncLinearCoeffC &)");
static TypeNameC type7(typeid(FuncLinearCoeffC),"RavlN::FuncLinearCoeffC");
FileFormatStreamC <FuncLinearCoeffC> FileFormatStream_FuncLinearCoeff;
FileFormatBinStreamC <FuncLinearCoeffC> FileFormatBinStream_FuncLinearCoeff;
//:- FuncPDFNormalC ------------------------------------------------------------------------
FunctionC FuncPDFNormal2Function(const FuncPDFNormalC &func)
{ return func; }
DP_REGISTER_CONVERSION_NAMED(FuncPDFNormal2Function ,1,
"RavlN::FunctionC RavlN::Convert(const RavlN::FuncPDFNormalC &)");
static TypeNameC type8(typeid(FuncPDFNormalC),"RavlN::FuncPDFNormalC");
FileFormatStreamC <FuncPDFNormalC> FileFormatStream_FuncPDFNormal;
FileFormatBinStreamC <FuncPDFNormalC> FileFormatBinStream_FuncPDFNormal;
}
| 42.442623 | 99 | 0.694477 | [
"vector"
] |
0d9e186a9f59726b598cd37c60195a8b8ec7898f | 15,540 | cpp | C++ | assignment10/assignment10/game.cpp | mvillafranca0/HWassignmentsDirectX | d9019bd77c0f7380cb980baf4127c5c3d389de13 | [
"MIT"
] | null | null | null | assignment10/assignment10/game.cpp | mvillafranca0/HWassignmentsDirectX | d9019bd77c0f7380cb980baf4127c5c3d389de13 | [
"MIT"
] | null | null | null | assignment10/assignment10/game.cpp | mvillafranca0/HWassignmentsDirectX | d9019bd77c0f7380cb980baf4127c5c3d389de13 | [
"MIT"
] | null | null | null | #include "MyDirectX.h"
LPD3DXSPRITE sprite_obj;
//font
LPDIRECT3DTEXTURE9 font;
LPD3DXSPRITE sprite_handler;
struct TRANSFORM
{
D3DXVECTOR3 position;
float xrot, yrot, zrot;
float scale;
};
const string APPTITLE = "Paddle 3D Game";
const int SCREENWIDTH = 640;
const int SCREENHEIGHT = 480;
int block_count = 0;
// One global variable is used to record
// the number of hit blocks
int score = 0;
#define BALL_SPEED 2
#define PADDLE_SPEED 0.25f
#define LEFT -18
#define RIGHT 18
#define BOTTOM -12
#define TOP 12
#define FRONT 0
#define BACK 60
#define BLOCK_WIDTH 3.9f
#define BLOCK_HEIGHT 2.4f
#define BLOCK_DEPTH 2.4f
#define BLOCK_START_Z 30 // location in z axis
#define BLOCKS_ACROSS 9 // 9 columns
#define BLOCKS_DOWN 10 // 10 rows
#define BLOCKS_DEEP 3 // 3 levels
#define NUM_BLOCKS BLOCKS_ACROSS*BLOCKS_DOWN* BLOCKS_DEEP
//game area
QUAD* back;
QUAD* leftwall;
QUAD* rightwall;
QUAD* bottom;
QUAD* top;
//sound effects
CSound* startgame;
CSound* launch;
CSound* missed;
CSound* hitwall;
CSound* hitblock;
CSound* hitpaddle;
struct OBJ
{
D3DXVECTOR3 pos; // location
D3DXVECTOR3 dir; // movement speed and direction
int alive; // whether the object active
};
MODEL* ball_model; OBJ ball;
MODEL* paddle_model; OBJ paddle;
MODEL* block_model[NUM_BLOCKS]; OBJ blocks[NUM_BLOCKS];
enum GAMESTATE
{
PAUSE = 0,
RUNNING = 1,
GAMEOVER = 2
};
GAMESTATE state = PAUSE;
#define CAMERA_X 0.0f
#define CAMERA_Y 0.0f
#define CAMERA_Z -21.0f
float RandomBallSpeedX()
{
//half normal speed for Z
return (float)(1 + rand() % BALL_SPEED / 2) / 10;
}
float RandomBallSpeedY()
{
//half normal speed for Z
return (float)(1 + rand() % BALL_SPEED / 2) / 10;
}
float RandomBallSpeedZ()
{
return (float)(2 + rand() % BALL_SPEED) / 10.0f;
}
int LoadBall() // should be called in game_init
{
ball_model = LoadModel("ball.x");
if (ball_model == NULL) return 0;
ball.pos = D3DXVECTOR3((float)(rand() % 20 - 10),
(float)(rand() % 20 - 10), 0.0f);
ball.dir = D3DXVECTOR3(RandomBallSpeedX(),
RandomBallSpeedY(),
RandomBallSpeedZ());
return 1;
}
int LoadPaddle() // should be called in game_init
{
paddle_model = LoadModel("paddle.x");
if (paddle_model == NULL) return 0;
paddle.pos = D3DXVECTOR3(0, 0, 3.0f);
return 1;
}
int LoadSounds()
{
startgame = LoadSound("startgame.wav");
launch = LoadSound("launch.wav");
missed = LoadSound("missed.wav");
hitwall = LoadSound("hitwall.wav");
hitblock = LoadSound("hitblock.wav");
hitpaddle = LoadSound("hitpaddle.wav");
if (hitwall == NULL || startgame == NULL
|| hitblock == NULL || missed == NULL
|| launch == NULL || hitpaddle == NULL)
return 0;
return 1;
}
int LoadFont()
{
HRESULT result;
//create the sprite handler
result = D3DXCreateSprite(d3ddev, &sprite_handler);
if (result != D3D_OK) return 0;
//load the font
font = LoadTexture("smallfont.bmp", D3DCOLOR_XRGB(0, 0, 0));
if (font == NULL) return 0;
return 1;
}
void MoveBall()
{
const int BORDER = 2;
if (state == PAUSE)
{
//ball follows paddle when game starts
ball.pos.x = paddle.pos.x;
ball.pos.y = paddle.pos.y;
ball.pos.z = paddle.pos.z + 6;
}
else
{
//move the ball
ball.pos.x += ball.dir.x;
ball.pos.y += ball.dir.y;
ball.pos.z += ball.dir.z;
//left and right walls
if (ball.pos.x < LEFT + BORDER
|| ball.pos.x > RIGHT - BORDER)
{
ball.dir.x *= -1;
ball.pos.x += ball.dir.x;
PlaySound(hitwall);
}
//floor and roof
if (ball.pos.y < BOTTOM + BORDER
|| ball.pos.y > TOP - BORDER)
{
ball.dir.y *= -1;
ball.pos.y += ball.dir.y;
PlaySound(hitwall);
}
// back wall
if (ball.pos.z > BACK)
{
ball.dir.z *= -1;
ball.pos.z += ball.dir.z;
PlaySound(hitwall);
}
//did the player miss the ball? must be if this occurs.
if (ball.pos.z < paddle.pos.z)
{
PlaySound(missed);
ball.dir.z = RandomBallSpeedZ();
state = PAUSE; // launch another ball
}
}
}
void MovePaddle()
{
//update paddle x position
if (Mouse_X() > 0) paddle.pos.x += PADDLE_SPEED;
else if (Mouse_X() < 0) paddle.pos.x -= PADDLE_SPEED;
//update paddle y position
if (Mouse_Y() > 0) paddle.pos.y -= PADDLE_SPEED;
else if (Mouse_Y() < 0) paddle.pos.y += PADDLE_SPEED;
if (paddle.pos.x < LEFT + 2)
paddle.pos.x = LEFT + 2;
else if (paddle.pos.x > RIGHT - 2)
paddle.pos.x = RIGHT - 2;
if (paddle.pos.y < BOTTOM + 1)
paddle.pos.y = BOTTOM + 1;
else if (paddle.pos.y > TOP - 1)
paddle.pos.y = TOP - 1;
//check for collision with ball
D3DXMATRIX ballMatrix, paddleMatrix;
D3DXMatrixTranslation(&paddleMatrix, paddle.pos.x, paddle.pos.y, paddle.pos.z);
D3DXMatrixTranslation(&ballMatrix, ball.pos.x, ball.pos.y, ball.pos.z);
if (Collided(ball_model, ballMatrix, paddle_model, paddleMatrix))
{
PlaySound(hitpaddle);
ball.dir.z = -1 * ball.dir.z;
}
}
void LoadBlocks()
{
int n = 0;
for (int z = 0; z < BLOCKS_DEEP; z++)
for (int y = 0; y < BLOCKS_DOWN; y++)
for (int x = 0; x < BLOCKS_ACROSS; x++)
{
blocks[n].alive = 1;
if (rand() % 3) block_model[n] = LoadModel("greenblock.x");
else if (rand() % 2) block_model[n] = LoadModel("blueblock.x");
else block_model[n] = LoadModel("redblock.x");
blocks[n].pos = D3DXVECTOR3(
LEFT + BLOCK_WIDTH / 2 + x * BLOCK_WIDTH,
TOP - BLOCK_HEIGHT / 2 - y * BLOCK_HEIGHT,
BLOCK_START_Z + z * BLOCK_DEPTH);
n++;
}
}
void Translate(D3DXVECTOR3 vec)
{
D3DXMATRIXA16 mat;
D3DXMatrixTranslation(&mat, vec.x, vec.y, vec.z);
d3ddev->SetTransform(D3DTS_WORLD, &mat);
}
void DrawBlocks()
{
int x, y, z, n = 0;
D3DXMATRIX ballMatrix, blockMatrix;
//active blocks are rendered as solid
d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
//draw the active blocks.
n = 0; block_count = 0;
for (z = 0; z < BLOCKS_DEEP; z++)
for (y = 0; y < BLOCKS_DOWN; y++)
for (x = 0; x < BLOCKS_ACROSS; x++)
{
//only render the live blocks
if (blocks[n].alive)
{
//draw the block
Translate(blocks[n].pos);
DrawModel(block_model[n]);
block_count++;
D3DXMatrixTranslation(&ballMatrix, ball.pos.x, ball.pos.y, ball.pos.z);
D3DXMatrixTranslation(&blockMatrix, blocks[n].pos.x, blocks[n].pos.y,
blocks[n].pos.z);
if (Collided(ball_model, ballMatrix, block_model[n], blockMatrix))
{
PlaySound(hitblock);
blocks[n].alive = 0; score++;
//check the collision position, front or back?
//game room deep 60, blocks at position 30
if (ball.pos.z < blocks[n].pos.z) // hit front of block
ball.dir.z = -1 * ball.dir.z; // bounce back
else if (ball.pos.z >= blocks[n].pos.z) // hit back
ball.dir.z = (float)(5 + rand() % 9) / 10.0f; // random bounce
}
}
n++;
}
// if all blocks are not active, game over
if (block_count == 0)
state = GAMEOVER;
}
void DrawChar(int x, int y, char c, LPDIRECT3DTEXTURE9 lpfont, int cols, int width, int height)
{
sprite_handler->Begin(D3DXSPRITE_ALPHABLEND);
//create vector to update sprite position
D3DXVECTOR3 position((float)x, (float)y, 0);
//ASCII code of ocrfont.bmp starts with 32 (space)
int index = c - 32;
//configure the rect
RECT srcRect;
srcRect.left = (index % cols) * width;
srcRect.top = (index / cols) * height;
srcRect.right = srcRect.left + width;
srcRect.bottom = srcRect.top + height;
//draw the sprite
sprite_handler->Draw(lpfont, &srcRect, NULL,
&position, D3DCOLOR_XRGB(255, 255, 255));
sprite_handler->End();
}
void DrawText(int x, int y, char* text, LPDIRECT3DTEXTURE9 lpfont, int cols, int width, int height)
{
for (unsigned int n = 0; n < strlen(text); n++)
{
DrawChar(x + n * 8, y, text[n], lpfont, cols, width, height);
}
}
void DisplayStatus()
{
static char s[80] = "";
//ball position
sprintf_s(s, "Ball Pos (%d,%d,%d)", (int)ball.pos.x, (int)ball.pos.y, (int)ball.pos.z);
DrawText(1, SCREENHEIGHT - 15, s, font, 20, 8, 12);
//ball direction
sprintf_s(s, "Ball Dir (%1.2f,%1.2f,%1.2f)", ball.dir.x, ball.dir.y, ball.dir.z);
DrawText(1, SCREENHEIGHT - 30, s, font, 20, 8, 12);
//score
sprintf_s(s, "Score (%d)", score);
DrawText(SCREENWIDTH - strlen(s) * 8 - 1, 1, s, font, 20, 8, 12);
}
void CreateBoundary()
{
// back wall
back = CreateQuad("background.bmp");
back->vertices[0].x = LEFT;
back->vertices[0].y = TOP;
back->vertices[0].z = BACK;
back->vertices[1].x = RIGHT;
back->vertices[1].y = TOP;
back->vertices[1].z = BACK;
back->vertices[2].x = LEFT;
back->vertices[2].y = BOTTOM;
back->vertices[2].z = BACK;
back->vertices[3].x = RIGHT;
back->vertices[3].y = BOTTOM;
back->vertices[3].z = BACK;
// left wall
leftwall = CreateQuad("background.bmp");
leftwall->vertices[0].x = LEFT;
leftwall->vertices[0].y = TOP;
leftwall->vertices[0].z = FRONT;
leftwall->vertices[1].x = LEFT;
leftwall->vertices[1].y = TOP;
leftwall->vertices[1].z = BACK;
leftwall->vertices[2].x = LEFT;
leftwall->vertices[2].y = BOTTOM;
leftwall->vertices[2].z = FRONT;
leftwall->vertices[3].x = LEFT;
leftwall->vertices[3].y = BOTTOM;
leftwall->vertices[3].z = BACK;
// right wall
rightwall = CreateQuad("background.bmp");
rightwall->vertices[0].x = RIGHT;
rightwall->vertices[0].y = TOP;
rightwall->vertices[0].z = BACK;
rightwall->vertices[1].x = RIGHT;
rightwall->vertices[1].y = TOP;
rightwall->vertices[1].z = FRONT;
rightwall->vertices[2].x = RIGHT;
rightwall->vertices[2].y = BOTTOM;
rightwall->vertices[2].z = BACK;
rightwall->vertices[3].x = RIGHT;
rightwall->vertices[3].y = BOTTOM;
rightwall->vertices[3].z = FRONT;
// top wall
top = CreateQuad("background.bmp");
top->vertices[0].x = LEFT;
top->vertices[0].y = TOP;
top->vertices[0].z = FRONT;
top->vertices[1].x = RIGHT;
top->vertices[1].y = TOP;
top->vertices[1].z = FRONT;
top->vertices[2].x = LEFT;
top->vertices[2].y = TOP;
top->vertices[2].z = BACK;
top->vertices[3].x = RIGHT;
top->vertices[3].y = TOP;
top->vertices[3].z = BACK;
// bottom wall
bottom = CreateQuad("background.bmp");
bottom->vertices[0].x = LEFT;
bottom->vertices[0].y = BOTTOM;
bottom->vertices[0].z = BACK;
bottom->vertices[1].x = RIGHT;
bottom->vertices[1].y = BOTTOM;
bottom->vertices[1].z = BACK;
bottom->vertices[2].x = LEFT;
bottom->vertices[2].y = BOTTOM;
bottom->vertices[2].z = FRONT;
bottom->vertices[3].x = RIGHT;
bottom->vertices[3].y = BOTTOM;
bottom->vertices[3].z = FRONT;
// use the similar method to create
// left wall, right wall, top wall and bottom wall
}
bool Game_Init(HWND hwnd)
{
Direct3D_Init(hwnd, SCREENWIDTH, SCREENHEIGHT, false);
DirectInput_Init(hwnd);
DirectSound_Init(hwnd);
float ratio = (float)SCREENWIDTH / (float)SCREENHEIGHT;
SetPerspective(D3DX_PI / 3, ratio, 0.1f, 10000.0f);
SetCamera(CAMERA_X, CAMERA_Y, CAMERA_Z, paddle.pos.x,
paddle.pos.y, paddle.pos.z);
d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_LIGHTING, TRUE);
d3ddev->SetRenderState(D3DRS_AMBIENT, WHITE);
//play starting sound while loading
if (!LoadSounds()) return false;
PlaySound(startgame);
CreateBoundary();
LoadBall();
LoadPaddle();
LoadBlocks();
LoadFont();
return true;
}
void Game_Run(HWND hwnd)
{
if (!d3ddev) return;
DirectInput_Update();
if (Mouse_Button(0) && state == PAUSE)
state = RUNNING; //mouse click starts the ball
MoveBall(); MovePaddle();
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
if (d3ddev->BeginScene())
{
Translate(ball.pos); DrawModel(ball_model);
Translate(paddle.pos); DrawModel(paddle_model);
d3ddev->EndScene();
}
d3ddev->Present(NULL, NULL, NULL, NULL);
if (d3ddev->BeginScene())
{
Translate(ball.pos); DrawModel(ball_model);
Translate(paddle.pos); DrawModel(paddle_model);
Translate(D3DXVECTOR3(0, 0, 0));
DrawQuad(back);
DrawQuad(leftwall);
DrawQuad(rightwall);
DrawQuad(bottom);
DrawQuad(top);
d3ddev->EndScene();
}
d3ddev->Present(NULL, NULL, NULL, NULL);
if (d3ddev->BeginScene())
{
Translate(D3DXVECTOR3(0, 0, 0));
//draw the blocks
DrawBlocks();
DisplayStatus();
d3ddev->EndScene();
}
d3ddev->Present(NULL, NULL, NULL, NULL);
/*
if (d3ddev->BeginScene())
{
DisplayStatus();
d3ddev->EndScene();
}
d3ddev->Present(NULL, NULL, NULL, NULL);
*/
if (Key_Down(DIK_ESCAPE))
gameover = true;
}
void Game_End()
{
//delete sounds
if (startgame != NULL) delete startgame;
if (launch != NULL) delete launch;
if (missed != NULL) delete missed;
if (hitwall != NULL) delete hitwall;
if (hitblock != NULL) delete hitblock;
if (hitpaddle != NULL) delete hitpaddle;
if (font != NULL)
font->Release();
if (sprite_handler != NULL)
sprite_handler->Release();
DeleteQuad(leftwall);
DeleteQuad(rightwall);
DeleteQuad(top);
DeleteQuad(bottom);
DeleteQuad(back);
//delete the block models
for (int n = 0; n < NUM_BLOCKS; n++)
DeleteModel(block_model[n]);
//delete models and quads
DeleteModel(ball_model);
DeleteModel(paddle_model);
DirectSound_Shutdown();
DirectInput_Shutdown();
Direct3D_Shutdown();
} | 27.167832 | 100 | 0.553668 | [
"render",
"object",
"vector",
"model",
"transform",
"3d",
"solid"
] |
d3fdf422dbf59b3da3984c3418c0eed687dd9068 | 2,468 | cpp | C++ | CVUI/CVUI/main.cpp | LeiYangJustin/CVUI4CellularSolid | 6fd13dfaf494d9e3800e95827502c4fd8a4f8210 | [
"MIT"
] | null | null | null | CVUI/CVUI/main.cpp | LeiYangJustin/CVUI4CellularSolid | 6fd13dfaf494d9e3800e95827502c4fd8a4f8210 | [
"MIT"
] | null | null | null | CVUI/CVUI/main.cpp | LeiYangJustin/CVUI4CellularSolid | 6fd13dfaf494d9e3800e95827502c4fd8a4f8210 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
// INCLUDE OPENCV DIR
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <CGAL/bounding_box.h>
#define THRESHOLD 1.0
#define MAXITER 3
//
#include "../DataColle/img_data.h"
#include "../AlgColle/extraction.h"
#include "../AlgColle/synthesis.h"
#include "reader.h"
#include "cv_viewer.h"
#define TEST_EXAMPLE
//#define TEST_SYNTHSS
int main()
{
// read some gray-scale image from the given path
std::string filename = "D:\\MyProjects\\CVUI4CellularSolid\\CVUI\\img_data\\example6.png";
cv::Mat src_img = cv::imread(filename);
if (src_img.data == NULL)
return EXIT_FAILURE;
// //
//#ifdef _DEBUG
// int height = 201;
// std::cout << "We are in the debugging mode" << std::endl;
//#else
// int height = 401;
//#endif
int height = 101;
int width = double(height) / double(src_img.rows)*double(src_img.cols);
cv::resize(src_img, src_img, cv::Size(width, height));
CImgData* img_data = new CImgData(src_img, true);
img_data->save_solid("example6_reversed.png");
//
std::cout << "\n-compute distance field from image" << std::endl;
int rows, cols;
std::vector<double> solid_field, void_field;
img_data->get_two_distance_transform_fields(rows, cols, solid_field, void_field);
std::vector<std::vector<double>> edge_pts;
img_data->find_void_contours(edge_pts);
//
std::cout << "\n-optimize the triangulation" << std::endl;
RT * example_net = new RT;
RT * synthss_net = new RT;
#ifdef TEST_EXAMPLE
CMeshExtractor net_extractor(example_net);
net_extractor.setup_background(rows, cols, solid_field, void_field, edge_pts);
net_extractor.run_extraction();
std::cout << "\n-output data" << std::endl;
std::cout << "#verts = " << example_net->number_of_vertices() << std::endl;
#endif
#ifdef TEST_SYNTHSS
//
std::cout << "\n-do synthesis..." << std::endl;
double height_ss = 100;
double width_ss = 100;
std::vector<Point_2> pts;
CReader::read_data_array_file("D:\\MyProjects\\CVUI4CellularSolid\\CVUI\\img_data\\samples_40.txt", pts);
RT * synthss_net = new RT;
CMeshSynthesizer net_synthesizer(synthss_net);
#endif
std::cout << "finished" << std::endl;
example_net->clear();
synthss_net->clear();
delete example_net;
delete synthss_net;
}
//#include "../AlgColle/dGBOD12_test.h"
//int main()
//{
// CTest_dGBOD12 test;
// test.run_test(200);
//}
| 26.255319 | 106 | 0.711102 | [
"vector"
] |
311c8c57a16a821a09373080b8a5f9a8a8e45ac9 | 6,979 | cpp | C++ | src/UnitTest/unit_test.cpp | Jim61C/GMD_Tracker | 6c522b26f664c259bd371214e44c9c2cd32c51d0 | [
"MIT"
] | 2 | 2018-04-14T14:33:30.000Z | 2018-06-19T21:49:19.000Z | src/UnitTest/unit_test.cpp | Jim61C/GMD_Tracker | 6c522b26f664c259bd371214e44c9c2cd32c51d0 | [
"MIT"
] | null | null | null | src/UnitTest/unit_test.cpp | Jim61C/GMD_Tracker | 6c522b26f664c259bd371214e44c9c2cd32c51d0 | [
"MIT"
] | null | null | null | // shared_ptr::reset example
#include <iostream>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <helper/bounding_box.h>
#include <helper/CommonCV.h>
#include <Eigen/Dense>
#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_utils.hpp"
#include <assert.h>
#include <string.h>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::Map;
using Eigen::MatrixXf;
using Eigen::Matrix;
using namespace rapidxml;
class A {
public:
virtual void foo() {
cout << "A's foo" << endl;
}
virtual void foo_invoker() {
cout << "A's foo_invoker, about to call foo()" << endl;
foo();
}
};
class B: public A {
public:
virtual void foo() {
cout << "B's foo" << endl;
}
virtual void foo_invoker() {
A::foo_invoker();
}
};
void doSomethingMat(Mat & mat) {
Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
M.copyTo(mat);
}
void populateTestEigenMap() {
// Test Eigen Map
vector<vector<float> > src;
for (int i = 0; i < 4; i ++) {
vector<float> temp;
for (int j = 0; j < 5; j ++) {
temp.push_back(j);
}
src.push_back(temp);
}
Map<Matrix<float,1,5,Eigen::RowMajor> > mf(src[0].data());
for (int j = 0; j < 5; j ++) {
cout << mf(0, j) << " ";
}
cout << endl;
}
void populateTestEigenFunctions() {
MatrixXd test(3, 3);
test << 4,-1,2, -1,6,0, 2,0,5;
cout << test << endl;
cout << "test.col(1).mean():" << test.col(1).mean() << endl;
Eigen::LLT<MatrixXd> llt(test); // compute the Cholesky decomposition of A
MatrixXd L = llt.matrixL();
cout << L << endl;
cout << L * L.transpose() << endl;
Eigen::EigenSolver<MatrixXd>eigen_solver(test, true);
MatrixXd ones = MatrixXd::Ones(3,3);
Eigen::EigenSolver<MatrixXd> es(ones);
cout << "The first eigenvector of the 3x3 matrix of ones is:"
<< endl << es.eigenvectors() << endl;
cout << es.eigenvalues().cols() << endl;
}
void populateTestRapidXml () {
rapidxml::file<> xmlFile("/home/jimxing/Downloads/Tracking_Sequences/ILSVRC2015/Annotations/VID/train/ILSVRC2015_VID_train_0004/ILSVRC2015_val_00069001/000000.xml"); // Default template is char
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
cout << "first node name:" << doc.first_node()->name() << endl;
assert(strcmp(doc.first_node()->name(), "annotation") == 0);
xml_node<> *annotation_node = doc.first_node();
for (xml_node<> *child = annotation_node->first_node(); child; child = child->next_sibling()) {
// do stuff with child
cout << child->name() << endl;
if (strcmp(child->name(), "object") == 0) {
for (xml_node<> *track_obj_node = child->first_node(); track_obj_node; track_obj_node = track_obj_node->next_sibling()) {
if (strcmp(track_obj_node->name(), "trackid") == 0) {
cout << "\t" << "trackid: " << track_obj_node->value() << endl;
}
else if (strcmp(track_obj_node->name(), "name") == 0) {
cout << "\t" << "name: " << track_obj_node->value() << endl;
}
else if (strcmp(track_obj_node->name(), "occluded") == 0) {
cout << "\t" << "occluded: " << track_obj_node->value() << endl;
}
else if (strcmp(track_obj_node->name(), "generated") == 0) {
cout << "\t" << "generated: " << track_obj_node->value() << endl;
}
else if (strcmp(track_obj_node->name(), "bndbox") == 0) {
xml_node<> *xmax_node = track_obj_node->first_node();
xml_node<> *xmin_node = xmax_node->next_sibling();
xml_node<> *ymax_node = xmin_node->next_sibling();
xml_node<> *ymin_node = ymax_node->next_sibling();
cout << "\t\tx1: " << xmin_node->value() << endl
<< "\t\ty1: " << ymin_node->value() << endl
<< "\t\tx2: " << xmax_node->value() << endl
<< "\t\ty2: " << ymax_node->value() << endl;
}
}
}
}
}
int main (int argc, char *argv[]) {
boost::shared_ptr<BoundingBox> sp; // empty
sp.reset (new BoundingBox(1,1,1,1)); // takes ownership of pointer
std::cout << sp->x1_ << '\n';
std::cout << sp->y1_ << '\n';
std::cout << sp->x2_ << '\n';
std::cout << sp->y2_ << '\n';
boost::shared_ptr<BoundingBox> sp_2;
sp_2 = sp;
cout << "before reset, sp_2:" << endl;
std::cout << sp_2->x1_ << '\n';
std::cout << sp_2->y1_ << '\n';
std::cout << sp_2->x2_ << '\n';
std::cout << sp_2->y2_ << '\n';
sp.reset (new BoundingBox(3,3,3,3)); // deletes managed object, acquires new pointer
std::cout << sp->x1_ << '\n';
std::cout << sp->y1_ << '\n';
std::cout << sp->x2_ << '\n';
std::cout << sp->y2_ << '\n';
cout << "after reset sp, sp_2:" << endl;
std::cout << sp_2->x1_ << '\n';
std::cout << sp_2->y1_ << '\n';
std::cout << sp_2->x2_ << '\n';
std::cout << sp_2->y2_ << '\n';
// sp.reset(); // deletes managed object
vector<int> temp = {1,2,3,4,5,6,7,8,9,10};
// auto engine = std::default_random_engine{};
cout << "time(NULL) " << time(NULL) << endl;
// std::mt19937 engine(time(NULL));
std::mt19937 engine;
engine.seed(time(NULL));
for (int i = 0; i < 5 ; i ++) {
vector<int> this_temp(temp);
std::shuffle(this_temp.begin(), this_temp.end(), engine);
for (int j = 0; j < this_temp.size() ; j ++) {
cout << this_temp[j] << " ";
}
cout << endl;
}
cout << std::min(1,2) << endl;
// TODO: unit test assign &Bbox to a bbox, creates a copy!
BoundingBox box_a(0, 0, 255, 255);
BoundingBox &box_b = box_a;
BoundingBox box_c;
box_c = box_b;
box_a.x1_ = 10;
box_a.y1_ = 10;
cout << "box_a:" << box_a.x1_ << ", "<< box_a.y1_ << ", " << box_a.x2_ << ", " << box_a.y2_ << endl;
cout << "box_b:" << box_b.x1_ << ", "<< box_b.y1_ << ", " << box_b.x2_ << ", " << box_b.y2_ << endl;
cout << "box_c:" << box_c.x1_ << ", "<< box_c.y1_ << ", " << box_c.x2_ << ", " << box_c.y2_ << endl;
// TODO: unit test dynamic binding for tracker_->Init, which function to call will be based on the dynamic type, virtual table looked up during runtime
A a;
B b;
cout << "a.foo_invoker():" << endl;
a.foo_invoker();
cout << "b.foo_invoker():" << endl;
b.foo_invoker();
// Test memcpy
vector<float> src = {1, 2, 3, 4};
vector<float> dst (src);
// memcpy(&dst, &src, 4);
cout << "dst.size(): " << dst.size() << endl;
for (int i =0 ; i < 4; i ++) { // note that beyond will be undefined
cout << dst[i] << " ";
}
cout << endl;
Mat temp_mat = (Mat_<double>(3,3) << 0, 0, 0, 0, 0, 0, 0, 0, 0);
doSomethingMat(temp_mat);
cout << "after doSomethingMat: \n" << temp_mat << endl;
temp_mat.at<double>(2,2) = 10;
cout << "after assign (2, 2): \n" << temp_mat << endl;
doSomethingMat(temp_mat);
cout << "after doSomethingMat: \n" << temp_mat << endl;
// populateTestEigenMap();
// populateTestEigenFunctions();
populateTestRapidXml();
return 0;
} | 29.95279 | 197 | 0.565411 | [
"object",
"vector"
] |
311e5441c95322b62d242cfcef97dfdebd65fbe1 | 67,200 | cpp | C++ | source/blender/vr/intern/vr_widget_loopcut.cpp | sigmike/blender | f7f4c42a71d5c69362d9ef0b757216accebf56f3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/vr/intern/vr_widget_loopcut.cpp | sigmike/blender | f7f4c42a71d5c69362d9ef0b757216accebf56f3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/vr/intern/vr_widget_loopcut.cpp | sigmike/blender | f7f4c42a71d5c69362d9ef0b757216accebf56f3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2018 by Blender Foundation.
* All rights reserved.
*
* Contributor(s): MARUI-PlugIn
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/vr/intern/vr_widget_loopcut.cpp
* \ingroup vr
*
*/
#include "vr_types.h"
#include <list>
#include "vr_main.h"
#include "vr_ui.h"
#include "vr_widget_loopcut.h"
#include "vr_widget_transform.h"
#include "vr_math.h"
#include "vr_draw.h"
#include "BLI_alloca.h"
#include "BLI_math.h"
#include "BLI_memarena.h"
#include "BLI_linklist_stack.h"
#include "BLI_string.h"
#include "BLI_utildefines_stack.h"
#include "BLT_translation.h"
#include "BKE_context.h"
#include "BKE_editmesh.h"
#include "BKE_editmesh_bvh.h"
#include "BKE_global.h"
#include "BKE_layer.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
#include "BKE_unit.h"
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_query.h"
#include "DNA_mesh_types.h"
#include "ED_mesh.h"
#include "ED_screen.h"
#include "ED_space_api.h"
#include "ED_numinput.h"
#include "ED_undo.h"
#include "GPU_immediate.h"
#include "GPU_state.h"
#include "GPU_matrix.h"
#include "MEM_guardedalloc.h"
#include "mesh_intern.h"
#include "transform.h"
#include "UI_resources.h"
#include "WM_api.h"
#include "WM_types.h"
/* Multiplier for one and two-handed scaling transformations. */
#define WIDGET_TRANSFORM_SCALING_SENSITIVITY 0.5f
/* Precision multipliers. */
#define WIDGET_TRANSFORM_TRANS_PRECISION 0.1f
#define WIDGET_TRANSFORM_ROT_PRECISION (PI / 36.0f)
#define WIDGET_TRANSFORM_SCALE_PRECISION 0.005f
/* Sensitivity multiplier for interactions. */
#define WIDGET_LOOPCUT_SENSITIVITY 3.0f
#include "vr_util.h"
/***********************************************************************************************/ /**
* \class Widget_LoopCut
***************************************************************************************************
* Interaction widget for the Loop Cut tool.
*
**************************************************************************************************/
Widget_LoopCut Widget_LoopCut::obj;
Coord3Df Widget_LoopCut::p0;
Coord3Df Widget_LoopCut::p1;
Coord3Df Widget_LoopCut::p0_b;
Coord3Df Widget_LoopCut::p1_b;
bool Widget_LoopCut::selection_empty(true);
bool Widget_LoopCut::edge_slide(false);
int Widget_LoopCut::base_index(0);
int Widget_LoopCut::edge_index(0);
float Widget_LoopCut::percent(0.0f);
int Widget_LoopCut::cuts(1);
bool Widget_LoopCut::double_side(true);
bool Widget_LoopCut::even(false);
bool Widget_LoopCut::flipped(false);
bool Widget_LoopCut::clamp(true);
/* TransInfo struct for edge slide operation. */
static TransInfo loopcut_info;
/* Dummy op */
static wmOperator loopcut_dummy_op;
/* From edimesh_preselect_edgering.c */
struct EditMesh_PreSelEdgeRing {
float (*edges)[2][3];
int edges_len;
float (*verts)[3];
int verts_len;
};
/* From editmesh_loopcut.c */
#define SUBD_SMOOTH_MAX 4.0f
#define SUBD_CUTS_MAX 500
/* ringsel operator */
/* struct for properties used while drawing */
typedef struct RingSelOpData {
ARegion *ar; /* region that ringsel was activated in */
void *draw_handle; /* for drawing preview loop */
struct EditMesh_PreSelEdgeRing *presel_edgering;
ViewContext vc;
Depsgraph *depsgraph;
Base **bases;
uint bases_len;
/* These values switch objects based on the object under the cursor. */
uint base_index;
Object *ob;
BMEditMesh *em;
BMEdge *eed;
NumInput num;
bool extend;
bool do_cut;
float cuts; /* cuts as float so smooth mouse pan works in small increments */
float smoothness;
} RingSelOpData;
static void edgering_select(RingSelOpData *lcd)
{
if (!lcd->eed) {
return;
}
if (!lcd->extend) {
for (uint base_index = 0; base_index < lcd->bases_len; base_index++) {
Object *ob_iter = lcd->bases[base_index]->object;
BMEditMesh *em = BKE_editmesh_from_object(ob_iter);
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
DEG_id_tag_update((ID *)ob_iter->data, ID_RECALC_SELECT);
WM_main_add_notifier(NC_GEOM | ND_SELECT, ob_iter->data);
}
}
BMEditMesh *em = lcd->em;
BMEdge *eed_start = lcd->eed;
BMWalker walker;
BMEdge *eed;
BMW_init(&walker,
em->bm,
BMW_EDGERING,
BMW_MASK_NOP,
BMW_MASK_NOP,
BMW_MASK_NOP,
BMW_FLAG_TEST_HIDDEN,
BMW_NIL_LAY);
for (eed = (BMEdge *)BMW_begin(&walker, eed_start); eed; eed = (BMEdge *)BMW_step(&walker)) {
BM_edge_select_set(em->bm, eed, true);
}
BMW_end(&walker);
}
static void ringsel_find_edge(RingSelOpData *lcd, const int previewlines)
{
if (lcd->eed) {
const float(*coords)[3] = NULL;
{
Mesh *me_eval = (Mesh *)DEG_get_evaluated_id(lcd->depsgraph, (ID *)lcd->ob->data);
if (me_eval->runtime.edit_data) {
coords = me_eval->runtime.edit_data->vertexCos;
}
}
EDBM_preselect_edgering_update_from_edge(
lcd->presel_edgering, lcd->em->bm, lcd->eed, previewlines, coords);
}
else {
EDBM_preselect_edgering_clear(lcd->presel_edgering);
}
}
/* called when modal loop selection gets set up... */
static int ringsel_init(bContext *C, wmOperator *op, bool do_cut)
{
RingSelOpData *lcd;
Scene *scene = CTX_data_scene(C);
/* alloc new customdata */
op->customdata = MEM_callocN(sizeof(RingSelOpData), "ringsel Modal Op Data");
lcd = (RingSelOpData *)op->customdata;
em_setup_viewcontext(C, &lcd->vc);
lcd->depsgraph = CTX_data_depsgraph(C);
/* assign the drawing handle for drawing preview line... */
lcd->ar = CTX_wm_region(C);
// lcd->draw_handle = ED_region_draw_cb_activate(lcd->ar->type, ringsel_draw, lcd,
// REGION_DRAW_POST_VIEW);
lcd->presel_edgering = EDBM_preselect_edgering_create();
/* Initialize once the cursor is over a mesh. */
lcd->ob = NULL;
lcd->em = NULL;
/* TODO_XR */
lcd->extend = do_cut ? false : true; // RNA_boolean_get(op->ptr, "extend");
lcd->do_cut = do_cut;
lcd->cuts = Widget_LoopCut::cuts;
lcd->smoothness = 0.0f; // RNA_float_get(op->ptr, "smoothness");
initNumInput(&lcd->num);
lcd->num.idx_max = 1;
lcd->num.val_flag[0] |= NUM_NO_NEGATIVE | NUM_NO_FRACTION;
/* No specific flags for smoothness. */
lcd->num.unit_sys = scene->unit.system;
lcd->num.unit_type[0] = B_UNIT_NONE;
lcd->num.unit_type[1] = B_UNIT_NONE;
ED_region_tag_redraw(lcd->ar);
return 1;
}
static void ringsel_finish(bContext *C, wmOperator *op)
{
RingSelOpData *lcd = (RingSelOpData *)op->customdata;
/* TODO_XR */
const float smoothness = 0.0f; // RNA_float_get(op->ptr, "smoothness");
const int smooth_falloff = 7; // RNA_enum_get(op->ptr, "falloff");
#ifdef BMW_EDGERING_NGON
const bool use_only_quads = false;
#else
const bool use_only_quads = false;
#endif
if (lcd->eed) {
BMEditMesh *em = lcd->em;
BMVert *v_eed_orig[2] = {lcd->eed->v1, lcd->eed->v2};
edgering_select(lcd);
if (lcd->do_cut) {
const bool is_macro = (op->opm != NULL);
/* a single edge (rare, but better support) */
const bool is_single = (BM_edge_is_wire(lcd->eed));
const int seltype = is_single ? SUBDIV_SELECT_INNER : SUBDIV_SELECT_LOOPCUT;
/* Enable gridfill, so that intersecting loopcut works as one would expect.
* Note though that it will break edgeslide in this specific case.
* See [#31939]. */
BM_mesh_esubdivide(em->bm,
BM_ELEM_SELECT,
smoothness,
smooth_falloff,
true,
0.0f,
0.0f,
Widget_LoopCut::cuts,
seltype,
SUBD_CORNER_PATH,
0,
true,
use_only_quads,
0);
/* when used in a macro the tessfaces will be recalculated anyway,
* this is needed here because modifiers depend on updated tessellation, see T45920 */
EDBM_update_generic(em, true, true);
if (is_single) {
/* de-select endpoints */
BM_vert_select_set(em->bm, v_eed_orig[0], false);
BM_vert_select_set(em->bm, v_eed_orig[1], false);
EDBM_selectmode_flush_ex(lcd->em, SCE_SELECT_VERTEX);
}
/* we cant slide multiple edges in vertex select mode */
else if (is_macro && (Widget_LoopCut::cuts > 1) && (em->selectmode & SCE_SELECT_VERTEX)) {
EDBM_selectmode_disable(lcd->vc.scene, em, SCE_SELECT_VERTEX, SCE_SELECT_EDGE);
}
/* force edge slide to edge select mode in in face select mode */
else if (EDBM_selectmode_disable(lcd->vc.scene, em, SCE_SELECT_FACE, SCE_SELECT_EDGE)) {
/* pass, the change will flush selection */
}
else {
/* else flush explicitly */
EDBM_selectmode_flush(lcd->em);
}
}
else {
/* XXX Is this piece of code ever used now? Simple loop select is now
* in editmesh_select.c (around line 1000)... */
/* sets as active, useful for other tools */
if (em->selectmode & SCE_SELECT_VERTEX)
BM_select_history_store(em->bm,
lcd->eed->v1); /* low priority TODO, get vertrex close to mouse */
if (em->selectmode & SCE_SELECT_EDGE)
BM_select_history_store(em->bm, lcd->eed);
EDBM_selectmode_flush(lcd->em);
DEG_id_tag_update((ID *)lcd->ob->data, ID_RECALC_SELECT);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, lcd->ob->data);
}
}
}
/* called when modal loop selection is done... */
static void ringsel_exit(bContext *UNUSED(C), wmOperator *op)
{
RingSelOpData *lcd = (RingSelOpData *)op->customdata;
/* deactivate the extra drawing stuff in 3D-View */
ED_region_draw_cb_exit(lcd->ar->type, lcd->draw_handle);
EDBM_preselect_edgering_destroy(lcd->presel_edgering);
if (lcd->bases) {
MEM_freeN(lcd->bases);
}
ED_region_tag_redraw(lcd->ar);
/* free the custom data */
MEM_freeN(lcd);
op->customdata = NULL;
}
static void loopcut_update_edge(RingSelOpData *lcd,
uint base_index,
BMEdge *e,
const int previewlines)
{
if (e != lcd->eed) {
lcd->eed = e;
lcd->ob = lcd->vc.obedit;
lcd->base_index = base_index;
lcd->em = lcd->vc.em;
ringsel_find_edge(lcd, previewlines);
}
else if (e == NULL) {
lcd->ob = NULL;
lcd->em = NULL;
lcd->base_index = UINT_MAX;
}
}
static void loopcut_mouse_move(RingSelOpData *lcd, const int previewlines)
{
struct {
Object *ob;
BMEdge *eed;
float dist;
int base_index;
} best;
best.ob = NULL;
best.eed = NULL;
best.dist = ED_view3d_select_dist_px();
best.base_index = 0;
uint base_index;
BMEdge *eed_test = EDBM_edge_find_nearest_ex(
&lcd->vc, &best.dist, NULL, false, false, NULL, lcd->bases, lcd->bases_len, &base_index);
if (eed_test) {
best.ob = lcd->bases[base_index]->object;
best.eed = eed_test;
best.base_index = base_index;
}
if (best.eed) {
ED_view3d_viewcontext_init_object(&lcd->vc, best.ob);
}
loopcut_update_edge(lcd, best.base_index, best.eed, previewlines);
}
static int loopcut_init(bContext *C, wmOperator *op, const wmEvent *event)
{
const bool is_interactive = (event != NULL);
/* Use for redo - intentionally wrap int to uint. */
struct {
uint base_index;
uint e_index;
} exec_data;
exec_data.base_index = (uint)Widget_LoopCut::base_index;
exec_data.e_index = (uint)Widget_LoopCut::edge_index;
ViewLayer *view_layer = CTX_data_view_layer(C);
uint bases_len;
static ObjectsInModeParams params = {OB_MODE_EDIT, true};
Base **bases = BKE_view_layer_array_from_bases_in_mode_params(
view_layer, CTX_wm_view3d(C), &bases_len, ¶ms);
if (is_interactive) {
for (uint base_index = 0; base_index < bases_len; base_index++) {
Object *ob_iter = bases[base_index]->object;
if (modifiers_isDeformedByLattice(ob_iter) || modifiers_isDeformedByArmature(ob_iter)) {
// BKE_report(op->reports, RPT_WARNING, "Loop cut does not work well on deformed edit mesh
// display");
break;
}
}
}
view3d_operator_needs_opengl(C);
/* for re-execution, check edge index is in range before we setup ringsel */
bool ok = true;
if (is_interactive == false) {
if (exec_data.base_index >= bases_len) {
return OPERATOR_CANCELLED;
ok = false;
}
else {
Object *ob_iter = bases[exec_data.base_index]->object;
BMEditMesh *em = BKE_editmesh_from_object(ob_iter);
if (exec_data.e_index >= em->bm->totedge) {
ok = false;
}
}
}
if (!ok || !ringsel_init(C, op, true)) {
MEM_freeN(bases);
return OPERATOR_CANCELLED;
}
/* add a modal handler for this operator - handles loop selection */
if (is_interactive) {
op->flag |= OP_IS_MODAL_CURSOR_REGION;
WM_event_add_modal_handler(C, op);
}
RingSelOpData *lcd = (RingSelOpData *)op->customdata;
lcd->bases = bases;
lcd->bases_len = bases_len;
// if (is_interactive) {
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = (RegionView3D *)ar->regiondata;
float projmat[4][4];
mul_m4_m4m4(projmat, (float(*)[4])rv3d->winmat, (float(*)[4])rv3d->viewmat);
float v1[3] = {Widget_LoopCut::p1.x, Widget_LoopCut::p1.y, Widget_LoopCut::p1.z};
mul_project_m4_v3(projmat, v1);
lcd->vc.mval[0] = (int)((ar->winx / 2.0f) + (ar->winx / 2.0f) * v1[0]);
lcd->vc.mval[1] = (int)((ar->winy / 2.0f) + (ar->winy / 2.0f) * v1[1]);
loopcut_mouse_move(lcd, is_interactive ? 1 : 0);
/*}
else {
Object *ob_iter = bases[exec_data.base_index]->object;
ED_view3d_viewcontext_init_object(&lcd->vc, ob_iter);
BMEdge *e;
BM_mesh_elem_table_ensure(lcd->vc.em->bm, BM_EDGE);
e = BM_edge_at_index(lcd->vc.em->bm, exec_data.e_index);
loopcut_update_edge(lcd, exec_data.base_index, e, 0);
}*/
#ifdef USE_LOOPSLIDE_HACK
/* for use in macro so we can restore, HACK */
/*{
Scene *scene = CTX_data_scene(C);
ToolSettings *settings = scene->toolsettings;
const bool mesh_select_mode[3] = {
(settings->selectmode & SCE_SELECT_VERTEX) != 0,
(settings->selectmode & SCE_SELECT_EDGE) != 0,
(settings->selectmode & SCE_SELECT_FACE) != 0,
};
RNA_boolean_set_array(op->ptr, "mesh_select_mode_init", mesh_select_mode);
}*/
#endif
if (is_interactive) {
ED_workspace_status_text(
C,
TIP_("Select a ring to be cut, use mouse-wheel or page-up/down for number of cuts, "
"hold Alt for smooth"));
return OPERATOR_RUNNING_MODAL;
}
else {
ringsel_finish(C, op);
ringsel_exit(C, op);
return OPERATOR_FINISHED;
}
}
/* Adapted from loopcut_init() in editmesh_loopcut.c */
static int ringsel_update(bContext *C, wmOperator *op)
{
/* Use for redo - intentionally wrap int to uint. */
struct {
uint base_index;
uint e_index;
} exec_data;
exec_data.base_index = (uint)Widget_LoopCut::base_index;
exec_data.e_index = (uint)Widget_LoopCut::edge_index;
ViewLayer *view_layer = CTX_data_view_layer(C);
uint bases_len;
static ObjectsInModeParams params = {OB_MODE_EDIT, true};
Base **bases = BKE_view_layer_array_from_bases_in_mode_params(
view_layer, CTX_wm_view3d(C), &bases_len, ¶ms);
view3d_operator_needs_opengl(C);
/* for re-execution, check edge index is in range before we setup ringsel */
bool ok = true;
if (exec_data.base_index >= bases_len) {
return OPERATOR_CANCELLED;
ok = false;
}
else {
Object *ob_iter = bases[exec_data.base_index]->object;
BMEditMesh *em = BKE_editmesh_from_object(ob_iter);
if (exec_data.e_index >= em->bm->totedge) {
ok = false;
}
}
if (!ok) {
MEM_freeN(bases);
return OPERATOR_CANCELLED;
}
RingSelOpData *lcd = (RingSelOpData *)op->customdata;
lcd->bases = bases;
lcd->bases_len = bases_len;
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = (RegionView3D *)ar->regiondata;
float projmat[4][4];
mul_m4_m4m4(projmat, (float(*)[4])rv3d->winmat, (float(*)[4])rv3d->viewmat);
float v1[3] = {Widget_LoopCut::p1.x, Widget_LoopCut::p1.y, Widget_LoopCut::p1.z};
mul_project_m4_v3(projmat, v1);
lcd->vc.mval[0] = (int)((ar->winx / 2.0f) + (ar->winx / 2.0f) * v1[0]);
lcd->vc.mval[1] = (int)((ar->winy / 2.0f) + (ar->winy / 2.0f) * v1[1]);
loopcut_mouse_move(lcd, Widget_LoopCut::cuts); // 1);
return OPERATOR_RUNNING_MODAL;
}
/* From transform.c */
static void slide_origdata_init_flag(TransInfo *t, TransDataContainer *tc, SlideOrigData *sod)
{
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
const bool has_layer_math = CustomData_has_math(&bm->ldata);
const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
if ((t->settings->uvcalc_flag & UVCALC_TRANSFORM_CORRECT) &&
/* don't do this at all for non-basis shape keys, too easy to
* accidentally break uv maps or vertex colors then */
(bm->shapenr <= 1) && (has_layer_math || (cd_loop_mdisp_offset != -1))) {
sod->use_origfaces = true;
sod->cd_loop_mdisp_offset = cd_loop_mdisp_offset;
}
else {
sod->use_origfaces = false;
sod->cd_loop_mdisp_offset = -1;
}
}
static void slide_origdata_init_data(TransDataContainer *tc, SlideOrigData *sod)
{
if (sod->use_origfaces) {
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
sod->origfaces = BLI_ghash_ptr_new(__func__);
BMeshCreateParams params = {0};
params.use_toolflags = false;
sod->bm_origfaces = BM_mesh_create(&bm_mesh_allocsize_default, ¶ms);
/* we need to have matching customdata */
BM_mesh_copy_init_customdata(sod->bm_origfaces, bm, NULL);
}
}
static void slide_origdata_create_data_vert(BMesh *bm,
SlideOrigData *sod,
TransDataGenericSlideVert *sv)
{
BMIter liter;
int j, l_num;
float *loop_weights;
/* copy face data */
// BM_ITER_ELEM (l, &liter, sv->v, BM_LOOPS_OF_VERT) {
BM_iter_init(&liter, bm, BM_LOOPS_OF_VERT, sv->v);
l_num = liter.count;
loop_weights = (float *)BLI_array_alloca(loop_weights, l_num);
for (j = 0; j < l_num; j++) {
BMLoop *l = (BMLoop *)BM_iter_step(&liter);
BMLoop *l_prev, *l_next;
void **val_p;
if (!BLI_ghash_ensure_p(sod->origfaces, l->f, &val_p)) {
BMFace *f_copy = BM_face_copy(sod->bm_origfaces, bm, l->f, true, true);
*val_p = f_copy;
}
if ((l_prev = BM_loop_find_prev_nodouble(l, l->next, FLT_EPSILON)) &&
(l_next = BM_loop_find_next_nodouble(l, l_prev, FLT_EPSILON))) {
loop_weights[j] = angle_v3v3v3(l_prev->v->co, l->v->co, l_next->v->co);
}
else {
loop_weights[j] = 0.0f;
}
}
/* store cd_loop_groups */
if (sod->layer_math_map_num && (l_num != 0)) {
sv->cd_loop_groups = (LinkNode **)BLI_memarena_alloc(sod->arena,
sod->layer_math_map_num * sizeof(void *));
for (j = 0; j < sod->layer_math_map_num; j++) {
const int layer_nr = sod->layer_math_map[j];
sv->cd_loop_groups[j] = BM_vert_loop_groups_data_layer_create(
bm, sv->v, layer_nr, loop_weights, sod->arena);
}
}
else {
sv->cd_loop_groups = NULL;
}
BLI_ghash_insert(sod->origverts, sv->v, sv);
}
static void slide_origdata_create_data(TransInfo *t,
TransDataContainer *tc,
SlideOrigData *sod,
TransDataGenericSlideVert *sv_array,
unsigned int v_stride,
unsigned int v_num)
{
if (sod->use_origfaces) {
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
unsigned int i;
TransDataGenericSlideVert *sv;
int layer_index_dst;
int j;
layer_index_dst = 0;
if (CustomData_has_math(&bm->ldata)) {
/* over alloc, only 'math' layers are indexed */
sod->layer_math_map = (int *)MEM_mallocN(bm->ldata.totlayer * sizeof(int), __func__);
for (j = 0; j < bm->ldata.totlayer; j++) {
if (CustomData_layer_has_math(&bm->ldata, j)) {
sod->layer_math_map[layer_index_dst++] = j;
}
}
BLI_assert(layer_index_dst != 0);
}
sod->layer_math_map_num = layer_index_dst;
sod->arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
sod->origverts = BLI_ghash_ptr_new_ex(__func__, v_num);
for (i = 0, sv = sv_array; i < v_num;
i++, sv = (TransDataGenericSlideVert *)POINTER_OFFSET(sv, v_stride)) {
slide_origdata_create_data_vert(bm, sod, sv);
}
if (tc->mirror.axis_flag) {
TransData *td = tc->data;
TransDataGenericSlideVert *sv_mirror;
sod->sv_mirror = (TransDataGenericSlideVert *)MEM_callocN(sizeof(*sv_mirror) * tc->data_len,
__func__);
sod->totsv_mirror = tc->data_len;
sv_mirror = sod->sv_mirror;
for (i = 0; i < tc->data_len; i++, td++) {
BMVert *eve = (BMVert *)td->extra;
if (eve) {
sv_mirror->v = eve;
copy_v3_v3(sv_mirror->co_orig_3d, eve->co);
slide_origdata_create_data_vert(bm, sod, sv_mirror);
sv_mirror++;
}
else {
sod->totsv_mirror--;
}
}
if (sod->totsv_mirror == 0) {
MEM_freeN(sod->sv_mirror);
sod->sv_mirror = NULL;
}
}
}
}
static void calcEdgeSlideCustomPoints(struct TransInfo *t)
{
EdgeSlideData *sld = (EdgeSlideData *)TRANS_DATA_CONTAINER_FIRST_OK(t)->custom.mode.data;
setCustomPoints(t, &t->mouse, sld->mval_end, sld->mval_start);
/* setCustomPoints isn't normally changing as the mouse moves,
* in this case apply mouse input immediately so we don't refresh
* with the value from the previous points */
applyMouseInput(t, &t->mouse, t->mval, t->values);
}
static BMEdge *get_other_edge(BMVert *v, BMEdge *e)
{
BMIter iter;
BMEdge *e_iter;
BM_ITER_ELEM (e_iter, &iter, v, BM_EDGES_OF_VERT) {
if (BM_elem_flag_test(e_iter, BM_ELEM_SELECT) && e_iter != e) {
return e_iter;
}
}
return NULL;
}
/* interpoaltes along a line made up of 2 segments (used for edge slide) */
static void interp_line_v3_v3v3v3(
float p[3], const float v1[3], const float v2[3], const float v3[3], float t)
{
float t_mid, t_delta;
/* could be pre-calculated */
t_mid = line_point_factor_v3(v2, v1, v3);
t_delta = t - t_mid;
if (t_delta < 0.0f) {
if (UNLIKELY(fabsf(t_mid) < FLT_EPSILON)) {
copy_v3_v3(p, v2);
}
else {
interp_v3_v3v3(p, v1, v2, t / t_mid);
}
}
else {
t = t - t_mid;
t_mid = 1.0f - t_mid;
if (UNLIKELY(fabsf(t_mid) < FLT_EPSILON)) {
copy_v3_v3(p, v3);
}
else {
interp_v3_v3v3(p, v2, v3, t / t_mid);
}
}
}
/**
* Find the closest point on the ngon on the opposite side.
* used to set the edge slide distance for ngons.
*/
static bool bm_loop_calc_opposite_co(BMLoop *l_tmp, const float plane_no[3], float r_co[3])
{
/* skip adjacent edges */
BMLoop *l_first = l_tmp->next;
BMLoop *l_last = l_tmp->prev;
BMLoop *l_iter;
float dist = FLT_MAX;
bool found = false;
l_iter = l_first;
do {
float tvec[3];
if (isect_line_plane_v3(tvec, l_iter->v->co, l_iter->next->v->co, l_tmp->v->co, plane_no)) {
const float fac = line_point_factor_v3(tvec, l_iter->v->co, l_iter->next->v->co);
/* allow some overlap to avoid missing the intersection because of float precision */
if ((fac > -FLT_EPSILON) && (fac < 1.0f + FLT_EPSILON)) {
/* likelihood of multiple intersections per ngon is quite low,
* it would have to loop back on its self, but better support it
* so check for the closest opposite edge */
const float tdist = len_v3v3(l_tmp->v->co, tvec);
if (tdist < dist) {
copy_v3_v3(r_co, tvec);
dist = tdist;
found = true;
}
}
}
} while ((l_iter = l_iter->next) != l_last);
return found;
}
/**
* Given 2 edges and a loop, step over the loops
* and calculate a direction to slide along.
*
* \param r_slide_vec: the direction to slide,
* the length of the vector defines the slide distance.
*/
static BMLoop *get_next_loop(
BMVert *v, BMLoop *l, BMEdge *e_prev, BMEdge *e_next, float r_slide_vec[3])
{
BMLoop *l_first;
float vec_accum[3] = {0.0f, 0.0f, 0.0f};
float vec_accum_len = 0.0f;
int i = 0;
BLI_assert(BM_edge_share_vert(e_prev, e_next) == v);
BLI_assert(BM_vert_in_edge(l->e, v));
l_first = l;
do {
l = BM_loop_other_edge_loop(l, v);
if (l->e == e_next) {
if (i) {
normalize_v3_length(vec_accum, vec_accum_len / (float)i);
}
else {
/* When there is no edge to slide along,
* we must slide along the vector defined by the face we're attach to */
BMLoop *l_tmp = BM_face_vert_share_loop(l_first->f, v);
BLI_assert(ELEM(l_tmp->e, e_prev, e_next) && ELEM(l_tmp->prev->e, e_prev, e_next));
if (l_tmp->f->len == 4) {
/* we could use code below, but in this case
* sliding diagonally across the quad works well */
sub_v3_v3v3(vec_accum, l_tmp->next->next->v->co, v->co);
}
else {
float tdir[3];
BM_loop_calc_face_direction(l_tmp, tdir);
cross_v3_v3v3(vec_accum, l_tmp->f->no, tdir);
#if 0
/* rough guess, we can do better! */
normalize_v3_length(vec_accum, (BM_edge_calc_length(e_prev) + BM_edge_calc_length(e_next)) / 2.0f);
#else
/* be clever, check the opposite ngon edge to slide into.
* this gives best results */
{
float tvec[3];
float dist;
if (bm_loop_calc_opposite_co(l_tmp, tdir, tvec)) {
dist = len_v3v3(l_tmp->v->co, tvec);
}
else {
dist = (BM_edge_calc_length(e_prev) + BM_edge_calc_length(e_next)) / 2.0f;
}
normalize_v3_length(vec_accum, dist);
}
#endif
}
}
copy_v3_v3(r_slide_vec, vec_accum);
return l;
}
else {
/* accumulate the normalized edge vector,
* normalize so some edges don't skew the result */
float tvec[3];
sub_v3_v3v3(tvec, BM_edge_other_vert(l->e, v)->co, v->co);
vec_accum_len += normalize_v3(tvec);
add_v3_v3(vec_accum, tvec);
i += 1;
}
if (BM_loop_other_edge_loop(l, v)->e == e_next) {
if (i) {
normalize_v3_length(vec_accum, vec_accum_len / (float)i);
}
copy_v3_v3(r_slide_vec, vec_accum);
return BM_loop_other_edge_loop(l, v);
}
} while ((l != l->radial_next) && ((l = l->radial_next) != l_first));
if (i) {
normalize_v3_length(vec_accum, vec_accum_len / (float)i);
}
copy_v3_v3(r_slide_vec, vec_accum);
return NULL;
}
/**
* Calculate screenspace `mval_start` / `mval_end`, optionally slide direction.
*/
static void calcEdgeSlide_mval_range(TransInfo *t,
TransDataContainer *tc,
EdgeSlideData *sld,
const int *sv_table,
const int loop_nr,
const float mval[2],
const bool use_occlude_geometry,
const bool use_calc_direction)
{
TransDataEdgeSlideVert *sv_array = sld->sv;
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
ARegion *ar = t->ar;
View3D *v3d = NULL;
RegionView3D *rv3d = NULL;
float projectMat[4][4];
BMBVHTree *bmbvh;
/* only for use_calc_direction */
float(*loop_dir)[3] = NULL, *loop_maxdist = NULL;
float mval_start[2], mval_end[2];
float mval_dir[3], dist_best_sq;
BMIter iter;
BMEdge *e;
if (t->spacetype == SPACE_VIEW3D) {
/* background mode support */
v3d = (View3D *)(t->sa ? t->sa->spacedata.first : NULL);
rv3d = (RegionView3D *)(t->ar ? t->ar->regiondata : NULL);
}
if (!rv3d) {
/* ok, let's try to survive this */
unit_m4(projectMat);
}
else {
ED_view3d_ob_project_mat_get(rv3d, tc->obedit, projectMat);
}
if (use_occlude_geometry) {
bmbvh = BKE_bmbvh_new_from_editmesh(em, BMBVH_RESPECT_HIDDEN, NULL, false);
}
else {
bmbvh = NULL;
}
/* find mouse vectors, the global one, and one per loop in case we have
* multiple loops selected, in case they are oriented different */
zero_v3(mval_dir);
dist_best_sq = -1.0f;
if (use_calc_direction) {
loop_dir = (float(*)[3])MEM_callocN(sizeof(float[3]) * loop_nr, "sv loop_dir");
loop_maxdist = (float *)MEM_mallocN(sizeof(float) * loop_nr, "sv loop_maxdist");
copy_vn_fl(loop_maxdist, loop_nr, -1.0f);
}
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
int i;
/* search cross edges for visible edge to the mouse cursor,
* then use the shared vertex to calculate screen vector*/
for (i = 0; i < 2; i++) {
BMIter iter_other;
BMEdge *e_other;
BMVert *v = i ? e->v1 : e->v2;
BM_ITER_ELEM (e_other, &iter_other, v, BM_EDGES_OF_VERT) {
/* screen-space coords */
float sco_a[3], sco_b[3];
float dist_sq;
int j, l_nr;
if (BM_elem_flag_test(e_other, BM_ELEM_SELECT))
continue;
/* This test is only relevant if object is not wire-drawn! See [#32068]. */
if (use_occlude_geometry &&
!BMBVH_EdgeVisible(bmbvh, e_other, t->depsgraph, ar, v3d, tc->obedit)) {
continue;
}
BLI_assert(sv_table[BM_elem_index_get(v)] != -1);
j = sv_table[BM_elem_index_get(v)];
if (sv_array[j].v_side[1]) {
ED_view3d_project_float_v3_m4(ar, sv_array[j].v_side[1]->co, sco_b, projectMat);
}
else {
add_v3_v3v3(sco_b, v->co, sv_array[j].dir_side[1]);
ED_view3d_project_float_v3_m4(ar, sco_b, sco_b, projectMat);
}
if (sv_array[j].v_side[0]) {
ED_view3d_project_float_v3_m4(ar, sv_array[j].v_side[0]->co, sco_a, projectMat);
}
else {
add_v3_v3v3(sco_a, v->co, sv_array[j].dir_side[0]);
ED_view3d_project_float_v3_m4(ar, sco_a, sco_a, projectMat);
}
/* global direction */
dist_sq = dist_squared_to_line_segment_v2(mval, sco_b, sco_a);
if ((dist_best_sq == -1.0f) ||
/* intentionally use 2d size on 3d vector */
(dist_sq < dist_best_sq && (len_squared_v2v2(sco_b, sco_a) > 0.1f))) {
dist_best_sq = dist_sq;
sub_v3_v3v3(mval_dir, sco_b, sco_a);
}
if (use_calc_direction) {
/* per loop direction */
l_nr = sv_array[j].loop_nr;
if (loop_maxdist[l_nr] == -1.0f || dist_sq < loop_maxdist[l_nr]) {
loop_maxdist[l_nr] = dist_sq;
sub_v3_v3v3(loop_dir[l_nr], sco_b, sco_a);
}
}
}
}
}
}
if (use_calc_direction) {
int i;
sv_array = sld->sv;
for (i = 0; i < sld->totsv; i++, sv_array++) {
/* switch a/b if loop direction is different from global direction */
int l_nr = sv_array->loop_nr;
if (dot_v3v3(loop_dir[l_nr], mval_dir) < 0.0f) {
swap_v3_v3(sv_array->dir_side[0], sv_array->dir_side[1]);
SWAP(BMVert *, sv_array->v_side[0], sv_array->v_side[1]);
}
}
MEM_freeN(loop_dir);
MEM_freeN(loop_maxdist);
}
/* possible all of the edge loops are pointing directly at the view */
if (UNLIKELY(len_squared_v2(mval_dir) < 0.1f)) {
mval_dir[0] = 0.0f;
mval_dir[1] = 100.0f;
}
/* zero out start */
zero_v2(mval_start);
/* dir holds a vector along edge loop */
copy_v2_v2(mval_end, mval_dir);
mul_v2_fl(mval_end, 0.5f);
sld->mval_start[0] = t->mval[0] + mval_start[0];
sld->mval_start[1] = t->mval[1] + mval_start[1];
sld->mval_end[0] = t->mval[0] + mval_end[0];
sld->mval_end[1] = t->mval[1] + mval_end[1];
if (bmbvh) {
BKE_bmbvh_free(bmbvh);
}
}
static void calcEdgeSlide_even(TransInfo *t,
TransDataContainer *tc,
EdgeSlideData *sld,
const float mval[2])
{
TransDataEdgeSlideVert *sv = sld->sv;
if (sld->totsv > 0) {
ARegion *ar = t->ar;
RegionView3D *rv3d = NULL;
float projectMat[4][4];
int i = 0;
float v_proj[2];
float dist_sq = 0;
float dist_min_sq = FLT_MAX;
if (t->spacetype == SPACE_VIEW3D) {
/* background mode support */
rv3d = (RegionView3D *)(t->ar ? t->ar->regiondata : NULL);
}
if (!rv3d) {
/* ok, let's try to survive this */
unit_m4(projectMat);
}
else {
ED_view3d_ob_project_mat_get(rv3d, tc->obedit, projectMat);
}
for (i = 0; i < sld->totsv; i++, sv++) {
/* Set length */
sv->edge_len = len_v3v3(sv->dir_side[0], sv->dir_side[1]);
ED_view3d_project_float_v2_m4(ar, sv->v->co, v_proj, projectMat);
dist_sq = len_squared_v2v2(mval, v_proj);
if (dist_sq < dist_min_sq) {
dist_min_sq = dist_sq;
sld->curr_sv_index = i;
}
}
}
else {
sld->curr_sv_index = 0;
}
}
static bool createEdgeSlideVerts_double_side(TransInfo *t, TransDataContainer *tc)
{
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
BMIter iter;
BMEdge *e;
BMVert *v;
TransDataEdgeSlideVert *sv_array;
int sv_tot;
int *sv_table; /* BMVert -> sv_array index */
EdgeSlideData *sld = (EdgeSlideData *)MEM_callocN(sizeof(*sld), "sld");
float mval[2] = {(float)t->mval[0], (float)t->mval[1]};
int numsel, i, loop_nr;
bool use_occlude_geometry = false;
View3D *v3d = NULL;
RegionView3D *rv3d = NULL;
slide_origdata_init_flag(t, tc, &sld->orig_data);
sld->curr_sv_index = 0;
/*ensure valid selection*/
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
BMIter iter2;
numsel = 0;
BM_ITER_ELEM (e, &iter2, v, BM_EDGES_OF_VERT) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
/* BMESH_TODO: this is probably very evil,
* set v->e to a selected edge*/
v->e = e;
numsel++;
}
}
if (numsel == 0 || numsel > 2) {
MEM_freeN(sld);
return false; /* invalid edge selection */
}
}
}
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
/* note, any edge with loops can work, but we won't get predictable results, so bail out */
if (!BM_edge_is_manifold(e) && !BM_edge_is_boundary(e)) {
/* can edges with at least once face user */
MEM_freeN(sld);
return false;
}
}
}
sv_table = (int *)MEM_mallocN(sizeof(*sv_table) * bm->totvert, __func__);
#define INDEX_UNSET -1
#define INDEX_INVALID -2
{
int j = 0;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
BM_elem_flag_enable(v, BM_ELEM_TAG);
sv_table[i] = INDEX_UNSET;
j += 1;
}
else {
BM_elem_flag_disable(v, BM_ELEM_TAG);
sv_table[i] = INDEX_INVALID;
}
BM_elem_index_set(v, i); /* set_inline */
}
bm->elem_index_dirty &= ~BM_VERT;
if (!j) {
MEM_freeN(sld);
MEM_freeN(sv_table);
return false;
}
sv_tot = j;
}
sv_array = (TransDataEdgeSlideVert *)MEM_callocN(sizeof(TransDataEdgeSlideVert) * sv_tot,
"sv_array");
loop_nr = 0;
STACK_DECLARE(sv_array);
STACK_INIT(sv_array, sv_tot);
while (1) {
float vec_a[3], vec_b[3];
BMLoop *l_a, *l_b;
BMLoop *l_a_prev, *l_b_prev;
BMVert *v_first;
/* If this succeeds call get_next_loop()
* which calculates the direction to slide based on clever checks.
*
* otherwise we simply use 'e_dir' as an edge-rail.
* (which is better when the attached edge is a boundary, see: T40422)
*/
#define EDGESLIDE_VERT_IS_INNER(v, e_dir) \
((BM_edge_is_boundary(e_dir) == false) && (BM_vert_edge_count_nonwire(v) == 2))
v = NULL;
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_TAG))
break;
}
if (!v)
break;
if (!v->e)
continue;
v_first = v;
/*walk along the edge loop*/
e = v->e;
/*first, rewind*/
do {
e = get_other_edge(v, e);
if (!e) {
e = v->e;
break;
}
if (!BM_elem_flag_test(BM_edge_other_vert(e, v), BM_ELEM_TAG))
break;
v = BM_edge_other_vert(e, v);
} while (e != v_first->e);
BM_elem_flag_disable(v, BM_ELEM_TAG);
l_a = e->l;
l_b = e->l->radial_next;
/* regarding e_next, use get_next_loop()'s improved interpolation where possible */
{
BMEdge *e_next = get_other_edge(v, e);
if (e_next) {
get_next_loop(v, l_a, e, e_next, vec_a);
}
else {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_a, v);
if (EDGESLIDE_VERT_IS_INNER(v, l_tmp->e)) {
get_next_loop(v, l_a, e, l_tmp->e, vec_a);
}
else {
sub_v3_v3v3(vec_a, BM_edge_other_vert(l_tmp->e, v)->co, v->co);
}
}
}
/* !BM_edge_is_boundary(e); */
if (l_b != l_a) {
BMEdge *e_next = get_other_edge(v, e);
if (e_next) {
get_next_loop(v, l_b, e, e_next, vec_b);
}
else {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_b, v);
if (EDGESLIDE_VERT_IS_INNER(v, l_tmp->e)) {
get_next_loop(v, l_b, e, l_tmp->e, vec_b);
}
else {
sub_v3_v3v3(vec_b, BM_edge_other_vert(l_tmp->e, v)->co, v->co);
}
}
}
else {
l_b = NULL;
}
l_a_prev = NULL;
l_b_prev = NULL;
#define SV_FROM_VERT(v) \
((sv_table[BM_elem_index_get(v)] == INDEX_UNSET) ? \
((void)(sv_table[BM_elem_index_get(v)] = STACK_SIZE(sv_array)), \
STACK_PUSH_RET_PTR(sv_array)) : \
(&sv_array[sv_table[BM_elem_index_get(v)]]))
/*iterate over the loop*/
v_first = v;
do {
bool l_a_ok_prev;
bool l_b_ok_prev;
TransDataEdgeSlideVert *sv;
BMVert *v_prev;
BMEdge *e_prev;
/* XXX, 'sv' will initialize multiple times, this is suspicious. see [#34024] */
BLI_assert(v != NULL);
BLI_assert(sv_table[BM_elem_index_get(v)] != INDEX_INVALID);
sv = SV_FROM_VERT(v);
sv->v = v;
copy_v3_v3(sv->v_co_orig, v->co);
sv->loop_nr = loop_nr;
if (l_a || l_a_prev) {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_a ? l_a : l_a_prev, v);
sv->v_side[0] = BM_edge_other_vert(l_tmp->e, v);
copy_v3_v3(sv->dir_side[0], vec_a);
}
if (l_b || l_b_prev) {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_b ? l_b : l_b_prev, v);
sv->v_side[1] = BM_edge_other_vert(l_tmp->e, v);
copy_v3_v3(sv->dir_side[1], vec_b);
}
v_prev = v;
v = BM_edge_other_vert(e, v);
e_prev = e;
e = get_other_edge(v, e);
if (!e) {
BLI_assert(v != NULL);
BLI_assert(sv_table[BM_elem_index_get(v)] != INDEX_INVALID);
sv = SV_FROM_VERT(v);
sv->v = v;
copy_v3_v3(sv->v_co_orig, v->co);
sv->loop_nr = loop_nr;
if (l_a) {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_a, v);
sv->v_side[0] = BM_edge_other_vert(l_tmp->e, v);
if (EDGESLIDE_VERT_IS_INNER(v, l_tmp->e)) {
get_next_loop(v, l_a, e_prev, l_tmp->e, sv->dir_side[0]);
}
else {
sub_v3_v3v3(sv->dir_side[0], sv->v_side[0]->co, v->co);
}
}
if (l_b) {
BMLoop *l_tmp = BM_loop_other_edge_loop(l_b, v);
sv->v_side[1] = BM_edge_other_vert(l_tmp->e, v);
if (EDGESLIDE_VERT_IS_INNER(v, l_tmp->e)) {
get_next_loop(v, l_b, e_prev, l_tmp->e, sv->dir_side[1]);
}
else {
sub_v3_v3v3(sv->dir_side[1], sv->v_side[1]->co, v->co);
}
}
BM_elem_flag_disable(v, BM_ELEM_TAG);
BM_elem_flag_disable(v_prev, BM_ELEM_TAG);
break;
}
l_a_ok_prev = (l_a != NULL);
l_b_ok_prev = (l_b != NULL);
l_a_prev = l_a;
l_b_prev = l_b;
if (l_a) {
l_a = get_next_loop(v, l_a, e_prev, e, vec_a);
}
else {
zero_v3(vec_a);
}
if (l_b) {
l_b = get_next_loop(v, l_b, e_prev, e, vec_b);
}
else {
zero_v3(vec_b);
}
if (l_a && l_b) {
/* pass */
}
else {
if (l_a || l_b) {
/* find the opposite loop if it was missing previously */
if (l_a == NULL && l_b && (l_b->radial_next != l_b))
l_a = l_b->radial_next;
else if (l_b == NULL && l_a && (l_a->radial_next != l_a))
l_b = l_a->radial_next;
}
else if (e->l != NULL) {
/* if there are non-contiguous faces, we can still recover the loops of the new edges
* faces */
/* note!, the behavior in this case means edges may move in opposite directions,
* this could be made to work more usefully. */
if (l_a_ok_prev) {
l_a = e->l;
l_b = (l_a->radial_next != l_a) ? l_a->radial_next : NULL;
}
else if (l_b_ok_prev) {
l_b = e->l;
l_a = (l_b->radial_next != l_b) ? l_b->radial_next : NULL;
}
}
if (!l_a_ok_prev && l_a) {
get_next_loop(v, l_a, e, e_prev, vec_a);
}
if (!l_b_ok_prev && l_b) {
get_next_loop(v, l_b, e, e_prev, vec_b);
}
}
BM_elem_flag_disable(v, BM_ELEM_TAG);
BM_elem_flag_disable(v_prev, BM_ELEM_TAG);
} while ((e != v_first->e) && (l_a || l_b));
#undef SV_FROM_VERT
#undef INDEX_UNSET
#undef INDEX_INVALID
loop_nr++;
#undef EDGESLIDE_VERT_IS_INNER
}
/* EDBM_flag_disable_all(em, BM_ELEM_SELECT); */
BLI_assert(STACK_SIZE(sv_array) == sv_tot);
sld->sv = sv_array;
sld->totsv = sv_tot;
/* use for visibility checks */
if (t->spacetype == SPACE_VIEW3D) {
v3d = (View3D *)(t->sa ? t->sa->spacedata.first : NULL);
rv3d = (RegionView3D *)(t->ar ? t->ar->regiondata : NULL);
use_occlude_geometry = (v3d && TRANS_DATA_CONTAINER_FIRST_OK(t)->obedit->dt > OB_WIRE &&
v3d->shading.type > OB_WIRE);
}
calcEdgeSlide_mval_range(t, tc, sld, sv_table, loop_nr, mval, use_occlude_geometry, true);
/* create copies of faces for customdata projection */
bmesh_edit_begin(bm, BMO_OPTYPE_FLAG_UNTAN_MULTIRES);
slide_origdata_init_data(tc, &sld->orig_data);
slide_origdata_create_data(
t, tc, &sld->orig_data, (TransDataGenericSlideVert *)sld->sv, sizeof(*sld->sv), sld->totsv);
if (rv3d) {
calcEdgeSlide_even(t, tc, sld, mval);
}
sld->em = em;
tc->custom.mode.data = sld;
MEM_freeN(sv_table);
return true;
}
/**
* A simple version of #createEdgeSlideVerts_double_side
* Which assumes the longest unselected.
*/
static bool createEdgeSlideVerts_single_side(TransInfo *t, TransDataContainer *tc)
{
BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
BMesh *bm = em->bm;
BMIter iter;
BMEdge *e;
TransDataEdgeSlideVert *sv_array;
int sv_tot;
int *sv_table; /* BMVert -> sv_array index */
EdgeSlideData *sld = (EdgeSlideData *)MEM_callocN(sizeof(*sld), "sld");
float mval[2] = {(float)t->mval[0], (float)t->mval[1]};
int loop_nr;
bool use_occlude_geometry = false;
View3D *v3d = NULL;
RegionView3D *rv3d = NULL;
if (t->spacetype == SPACE_VIEW3D) {
/* background mode support */
v3d = (View3D *)(t->sa ? t->sa->spacedata.first : NULL);
rv3d = (RegionView3D *)(t->ar ? t->ar->regiondata : NULL);
}
slide_origdata_init_flag(t, tc, &sld->orig_data);
sld->curr_sv_index = 0;
/* ensure valid selection */
{
int i = 0, j = 0;
BMVert *v;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
float len_sq_max = -1.0f;
BMIter iter2;
BM_ITER_ELEM (e, &iter2, v, BM_EDGES_OF_VERT) {
if (!BM_elem_flag_test(e, BM_ELEM_SELECT)) {
float len_sq = BM_edge_calc_length_squared(e);
if (len_sq > len_sq_max) {
len_sq_max = len_sq;
v->e = e;
}
}
}
if (len_sq_max != -1.0f) {
j++;
}
}
BM_elem_index_set(v, i); /* set_inline */
}
bm->elem_index_dirty &= ~BM_VERT;
if (!j) {
MEM_freeN(sld);
return false;
}
sv_tot = j;
}
BLI_assert(sv_tot != 0);
/* over alloc */
sv_array = (TransDataEdgeSlideVert *)MEM_callocN(sizeof(TransDataEdgeSlideVert) * bm->totvertsel,
"sv_array");
/* same loop for all loops, weak but we dont connect loops in this case */
loop_nr = 1;
sv_table = (int *)MEM_mallocN(sizeof(*sv_table) * bm->totvert, __func__);
{
int i = 0, j = 0;
BMVert *v;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
sv_table[i] = -1;
if ((v->e != NULL) && (BM_elem_flag_test(v, BM_ELEM_SELECT))) {
if (BM_elem_flag_test(v->e, BM_ELEM_SELECT) == 0) {
TransDataEdgeSlideVert *sv;
sv = &sv_array[j];
sv->v = v;
copy_v3_v3(sv->v_co_orig, v->co);
sv->v_side[0] = BM_edge_other_vert(v->e, v);
sub_v3_v3v3(sv->dir_side[0], sv->v_side[0]->co, v->co);
sv->loop_nr = 0;
sv_table[i] = j;
j += 1;
}
}
}
}
/* check for wire vertices,
* interpolate the directions of wire verts between non-wire verts */
if (sv_tot != bm->totvert) {
const int sv_tot_nowire = sv_tot;
TransDataEdgeSlideVert *sv_iter = sv_array;
for (int i = 0; i < sv_tot_nowire; i++, sv_iter++) {
BMIter eiter;
BM_ITER_ELEM (e, &eiter, sv_iter->v, BM_EDGES_OF_VERT) {
/* walk over wire */
TransDataEdgeSlideVert *sv_end = NULL;
BMEdge *e_step = e;
BMVert *v = sv_iter->v;
int j;
j = sv_tot;
while (1) {
BMVert *v_other = BM_edge_other_vert(e_step, v);
int endpoint = ((sv_table[BM_elem_index_get(v_other)] != -1) +
(BM_vert_is_edge_pair(v_other) == false));
if ((BM_elem_flag_test(e_step, BM_ELEM_SELECT) &&
BM_elem_flag_test(v_other, BM_ELEM_SELECT)) &&
(endpoint == 0)) {
/* scan down the list */
TransDataEdgeSlideVert *sv;
BLI_assert(sv_table[BM_elem_index_get(v_other)] == -1);
sv_table[BM_elem_index_get(v_other)] = j;
sv = &sv_array[j];
sv->v = v_other;
copy_v3_v3(sv->v_co_orig, v_other->co);
copy_v3_v3(sv->dir_side[0], sv_iter->dir_side[0]);
j++;
/* advance! */
v = v_other;
e_step = BM_DISK_EDGE_NEXT(e_step, v_other);
}
else {
if ((endpoint == 2) && (sv_tot != j)) {
BLI_assert(BM_elem_index_get(v_other) != -1);
sv_end = &sv_array[sv_table[BM_elem_index_get(v_other)]];
}
break;
}
}
if (sv_end) {
int sv_tot_prev = sv_tot;
const float *co_src = sv_iter->v->co;
const float *co_dst = sv_end->v->co;
const float *dir_src = sv_iter->dir_side[0];
const float *dir_dst = sv_end->dir_side[0];
sv_tot = j;
while (j-- != sv_tot_prev) {
float factor;
factor = line_point_factor_v3(sv_array[j].v->co, co_src, co_dst);
interp_v3_v3v3(sv_array[j].dir_side[0], dir_src, dir_dst, factor);
}
}
}
}
}
/* EDBM_flag_disable_all(em, BM_ELEM_SELECT); */
sld->sv = sv_array;
sld->totsv = sv_tot;
/* use for visibility checks */
if (t->spacetype == SPACE_VIEW3D) {
v3d = (View3D *)(t->sa ? t->sa->spacedata.first : NULL);
rv3d = (RegionView3D *)(t->ar ? t->ar->regiondata : NULL);
use_occlude_geometry = (v3d && TRANS_DATA_CONTAINER_FIRST_OK(t)->obedit->dt > OB_WIRE &&
v3d->shading.type > OB_WIRE);
}
calcEdgeSlide_mval_range(t, tc, sld, sv_table, loop_nr, mval, use_occlude_geometry, false);
/* create copies of faces for customdata projection */
bmesh_edit_begin(bm, BMO_OPTYPE_FLAG_UNTAN_MULTIRES);
slide_origdata_init_data(tc, &sld->orig_data);
slide_origdata_create_data(
t, tc, &sld->orig_data, (TransDataGenericSlideVert *)sld->sv, sizeof(*sld->sv), sld->totsv);
if (rv3d) {
calcEdgeSlide_even(t, tc, sld, mval);
}
sld->em = em;
tc->custom.mode.data = sld;
MEM_freeN(sv_table);
return true;
}
static void drawEdgeSlide(TransInfo *t)
{
if ((t->mode == TFM_EDGE_SLIDE) && TRANS_DATA_CONTAINER_FIRST_OK(t)->custom.mode.data) {
const EdgeSlideParams *slp = (EdgeSlideParams *)t->custom.mode.data;
EdgeSlideData *sld = (EdgeSlideData *)TRANS_DATA_CONTAINER_FIRST_OK(t)->custom.mode.data;
const bool is_clamp = !(t->flag & T_ALT_TRANSFORM);
/* Even mode */
if ((slp->use_even == true) || (is_clamp == false)) {
const float line_size = UI_GetThemeValuef(TH_OUTLINE_WIDTH) + 0.5f;
GPU_depth_test(false);
GPU_blend(true);
GPU_blend_set_func_separate(
GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
GPU_matrix_push();
GPU_matrix_mul(TRANS_DATA_CONTAINER_FIRST_OK(t)->obedit->obmat);
uint pos = GPU_vertformat_attr_add(
immVertexFormat(), "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
if (slp->use_even == true) {
float co_a[3], co_b[3], co_mark[3];
TransDataEdgeSlideVert *curr_sv = &sld->sv[sld->curr_sv_index];
const float fac = (slp->perc + 1.0f) / 2.0f;
const float ctrl_size = UI_GetThemeValuef(TH_FACEDOT_SIZE) + 1.5f;
const float guide_size = ctrl_size - 0.5f;
const int alpha_shade = -30;
add_v3_v3v3(co_a, curr_sv->v_co_orig, curr_sv->dir_side[0]);
add_v3_v3v3(co_b, curr_sv->v_co_orig, curr_sv->dir_side[1]);
GPU_line_width(line_size);
immUniformThemeColorShadeAlpha(TH_EDGE_SELECT, 80, alpha_shade);
immBeginAtMost(GPU_PRIM_LINES, 4);
if (curr_sv->v_side[0]) {
immVertex3fv(pos, curr_sv->v_side[0]->co);
immVertex3fv(pos, curr_sv->v_co_orig);
}
if (curr_sv->v_side[1]) {
immVertex3fv(pos, curr_sv->v_side[1]->co);
immVertex3fv(pos, curr_sv->v_co_orig);
}
immEnd();
immUniformThemeColorShadeAlpha(TH_SELECT, -30, alpha_shade);
GPU_point_size(ctrl_size);
immBegin(GPU_PRIM_POINTS, 1);
if (slp->flipped) {
if (curr_sv->v_side[1])
immVertex3fv(pos, curr_sv->v_side[1]->co);
}
else {
if (curr_sv->v_side[0])
immVertex3fv(pos, curr_sv->v_side[0]->co);
}
immEnd();
immUniformThemeColorShadeAlpha(TH_SELECT, 255, alpha_shade);
GPU_point_size(guide_size);
immBegin(GPU_PRIM_POINTS, 1);
interp_line_v3_v3v3v3(co_mark, co_b, curr_sv->v_co_orig, co_a, fac);
immVertex3fv(pos, co_mark);
immEnd();
}
else {
if (is_clamp == false) {
const int side_index = sld->curr_side_unclamp;
TransDataEdgeSlideVert *sv;
int i;
const int alpha_shade = -160;
GPU_line_width(line_size);
immUniformThemeColorShadeAlpha(TH_EDGE_SELECT, 80, alpha_shade);
immBegin(GPU_PRIM_LINES, sld->totsv * 2);
/* TODO(campbell): Loop over all verts */
sv = sld->sv;
for (i = 0; i < sld->totsv; i++, sv++) {
float a[3], b[3];
if (!is_zero_v3(sv->dir_side[side_index])) {
copy_v3_v3(a, sv->dir_side[side_index]);
}
else {
copy_v3_v3(a, sv->dir_side[!side_index]);
}
mul_v3_fl(a, 100.0f);
negate_v3_v3(b, a);
add_v3_v3(a, sv->v_co_orig);
add_v3_v3(b, sv->v_co_orig);
immVertex3fv(pos, a);
immVertex3fv(pos, b);
}
immEnd();
}
else {
BLI_assert(0);
}
}
immUnbindProgram();
GPU_matrix_pop();
GPU_blend(false);
GPU_depth_test(true);
}
}
}
static void doEdgeSlide(TransInfo *t, float perc)
{
EdgeSlideParams *slp = (EdgeSlideParams *)t->custom.mode.data;
EdgeSlideData *sld_active = (EdgeSlideData *)TRANS_DATA_CONTAINER_FIRST_OK(t)->custom.mode.data;
slp->perc = perc;
if (slp->use_even == false) {
const bool is_clamp = !(t->flag & T_ALT_TRANSFORM);
if (is_clamp) {
const int side_index = (perc < 0.0f);
const float perc_final = fabsf(perc);
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
EdgeSlideData *sld = (EdgeSlideData *)tc->custom.mode.data;
if (!sld)
continue;
TransDataEdgeSlideVert *sv = sld->sv;
for (int i = 0; i < sld->totsv; i++, sv++) {
madd_v3_v3v3fl(sv->v->co, sv->v_co_orig, sv->dir_side[side_index], perc_final);
}
sld->curr_side_unclamp = side_index;
}
}
else {
if (!sld_active)
return;
const float perc_init = fabsf(perc) *
((sld_active->curr_side_unclamp == (perc < 0.0f)) ? 1 : -1);
const int side_index = sld_active->curr_side_unclamp;
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
EdgeSlideData *sld = (EdgeSlideData *)tc->custom.mode.data;
TransDataEdgeSlideVert *sv = sld->sv;
for (int i = 0; i < sld->totsv; i++, sv++) {
float dir_flip[3];
float perc_final = perc_init;
if (!is_zero_v3(sv->dir_side[side_index])) {
copy_v3_v3(dir_flip, sv->dir_side[side_index]);
}
else {
copy_v3_v3(dir_flip, sv->dir_side[!side_index]);
perc_final *= -1;
}
madd_v3_v3v3fl(sv->v->co, sv->v_co_orig, dir_flip, perc_final);
}
}
}
}
else {
/**
* Implementation note, even mode ignores the starting positions and uses only the
* a/b verts, this could be changed/improved so the distance is still met but the verts are
* moved along their original path (which may not be straight), however how it works now is OK
* and matches 2.4x - Campbell
*
* \note len_v3v3(curr_sv->dir_side[0], curr_sv->dir_side[1])
* is the same as the distance between the original vert locations, same goes for the lines
* below.
*/
if (!sld_active)
return;
TransDataEdgeSlideVert *curr_sv = &sld_active->sv[sld_active->curr_sv_index];
const float curr_length_perc = curr_sv->edge_len *
(((slp->flipped ? perc : -perc) + 1.0f) / 2.0f);
float co_a[3];
float co_b[3];
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
EdgeSlideData *sld = (EdgeSlideData *)tc->custom.mode.data;
TransDataEdgeSlideVert *sv = sld->sv;
for (int i = 0; i < sld->totsv; i++, sv++) {
if (sv->edge_len > FLT_EPSILON) {
const float fac = min_ff(sv->edge_len, curr_length_perc) / sv->edge_len;
add_v3_v3v3(co_a, sv->v_co_orig, sv->dir_side[0]);
add_v3_v3v3(co_b, sv->v_co_orig, sv->dir_side[1]);
if (slp->flipped) {
interp_line_v3_v3v3v3(sv->v->co, co_b, sv->v_co_orig, co_a, fac);
}
else {
interp_line_v3_v3v3v3(sv->v->co, co_a, sv->v_co_orig, co_b, fac);
}
}
}
}
}
}
static void initEdgeSlide_ex(
TransInfo *t, bool use_double_side, bool use_even, bool flipped, bool use_clamp)
{
EdgeSlideData *sld;
bool ok = false;
t->mode = TFM_EDGE_SLIDE;
{
EdgeSlideParams *slp = (EdgeSlideParams *)MEM_callocN(sizeof(*slp), __func__);
slp->use_even = use_even;
slp->flipped = flipped;
/* happens to be best for single-sided */
if (use_double_side == false) {
slp->flipped = !flipped;
}
slp->perc = 0.0f;
if (!use_clamp) {
t->flag |= T_ALT_TRANSFORM;
}
t->custom.mode.data = slp;
t->custom.mode.use_free = true;
}
if (use_double_side) {
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
ok |= createEdgeSlideVerts_double_side(t, tc);
}
}
else {
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
ok |= createEdgeSlideVerts_single_side(t, tc);
}
}
if (!ok) {
t->state = TRANS_CANCEL;
return;
}
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
sld = (EdgeSlideData *)tc->custom.mode.data;
if (!sld) {
continue;
}
tc->custom.mode.free_cb = freeEdgeSlideVerts;
}
/* set custom point first if you want value to be initialized by init */
calcEdgeSlideCustomPoints(t);
initMouseInputMode(t, &t->mouse, INPUT_CUSTOM_RATIO_FLIP);
t->idx_max = 0;
t->num.idx_max = 0;
t->snap[0] = 0.0f;
t->snap[1] = 0.1f;
t->snap[2] = t->snap[1] * 0.1f;
copy_v3_fl(t->num.val_inc, t->snap[1]);
t->num.unit_sys = t->scene->unit.system;
t->num.unit_type[0] = B_UNIT_NONE;
t->flag |= T_NO_CONSTRAINT | T_NO_PROJECT;
}
bool Widget_LoopCut::has_click(VR_UI::Cursor &c) const
{
return true;
}
void Widget_LoopCut::click(VR_UI::Cursor &c)
{
bContext *C = vr_get_obj()->ctx;
Object *obedit = CTX_data_edit_object(C);
if (!obedit) {
return;
}
const Mat44f &m = c.position.get();
if (CTX_data_edit_object(vr_get_obj()->ctx)) {
VR_Util::raycast_select_single_edit(
*(Coord3Df *)m.m[3], VR_UI::shift_key_get(), VR_UI::ctrl_key_get());
}
/* Update manipulators */
Widget_Transform::update_manipulator();
}
void Widget_LoopCut::drag_start(VR_UI::Cursor &c)
{
bContext *C = vr_get_obj()->ctx;
Object *obedit = CTX_data_edit_object(C);
if (!obedit) {
return;
}
if (c.bimanual) {
return;
}
if (edge_slide) {
/* Test for empty selection. */
selection_empty = true;
Scene *scene = CTX_data_scene(C);
ToolSettings *ts = scene->toolsettings;
BMesh *bm = ((Mesh *)obedit->data)->edit_mesh->bm;
if (!bm) {
return;
}
BMIter iter;
if (ts->selectmode & SCE_SELECT_VERTEX) {
BMVert *v;
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
selection_empty = false;
break;
}
}
}
else if (ts->selectmode & SCE_SELECT_EDGE) {
BMEdge *e;
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
selection_empty = false;
break;
}
}
}
else if (ts->selectmode & SCE_SELECT_FACE) {
BMFace *f;
BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
selection_empty = false;
break;
}
}
}
if (selection_empty) {
return;
}
p1 = p0 = *(Coord3Df *)c.interaction_position.get(VR_SPACE_REAL).m[3];
p1_b = p0_b = *(Coord3Df *)c.interaction_position.get(VR_SPACE_BLENDER).m[3];
/* Execute edge slide operation */
loopcut_info.context = C;
loopcut_info.mode = TFM_EDGE_SLIDE;
loopcut_info.state = TRANS_STARTING;
unit_m3(loopcut_info.spacemtx);
initTransInfo(C, &loopcut_info, NULL, NULL);
initTransformOrientation(C, &loopcut_info);
createTransData(C, &loopcut_info);
initEdgeSlide_ex(&loopcut_info,
Widget_LoopCut::double_side,
Widget_LoopCut::even,
Widget_LoopCut::flipped,
Widget_LoopCut::clamp);
/* Update manipulators */
Widget_Transform::transform_space = VR_UI::TRANSFORMSPACE_NORMAL;
Widget_Transform::update_manipulator();
}
else {
p1 = p0 = *(Coord3Df *)c.interaction_position.get(VR_SPACE_BLENDER).m[3];
/* Initialize ring selection */
ringsel_init(C, &loopcut_dummy_op, false);
}
for (int i = 0; i < VR_SIDES; ++i) {
Widget_LoopCut::obj.do_render[i] = true;
}
}
void Widget_LoopCut::drag_contd(VR_UI::Cursor &c)
{
bContext *C = vr_get_obj()->ctx;
Object *obedit = CTX_data_edit_object(C);
if (!obedit) {
return;
}
ToolSettings *ts = NULL;
BMesh *bm = NULL;
if (obedit) {
/* Edit mode */
ts = CTX_data_scene(C)->toolsettings;
if (!ts) {
return;
}
if (obedit->type == OB_MESH) {
bm = ((Mesh *)obedit->data)->edit_mesh->bm;
if (!bm) {
return;
}
}
}
else {
return;
}
if (c.bimanual) {
return;
}
if (edge_slide) {
if (selection_empty) {
return;
}
p1 = *(Coord3Df *)c.position.get(VR_SPACE_REAL).m[3];
p1_b = *(Coord3Df *)c.position.get(VR_SPACE_BLENDER).m[3];
Coord3Df v = p1 - p0;
percent = v.length() * WIDGET_LOOPCUT_SENSITIVITY;
if (VR_UI::shift_key_get()) {
percent *= WIDGET_TRANSFORM_TRANS_PRECISION;
}
if (v * *(Coord3Df *)Widget_Transform::manip_t.m[2] < 0) {
percent = -percent;
}
/* Execute edge slide operation */
loopcut_info.state = TRANS_RUNNING;
doEdgeSlide(&loopcut_info, percent);
DEG_id_tag_update((ID *)obedit->data, 0);
}
else {
p1 = *(Coord3Df *)c.position.get(VR_SPACE_BLENDER).m[3];
/* Update ring selection */
if (loopcut_dummy_op.customdata) {
ringsel_update(C, &loopcut_dummy_op);
}
}
for (int i = 0; i < VR_SIDES; ++i) {
Widget_LoopCut::obj.do_render[i] = true;
}
}
void Widget_LoopCut::drag_stop(VR_UI::Cursor &c)
{
if (c.bimanual) {
return;
}
bContext *C = vr_get_obj()->ctx;
Object *obedit = CTX_data_edit_object(C);
if (!obedit) {
return;
}
if (edge_slide) {
if (selection_empty) {
return;
}
p1 = *(Coord3Df *)c.position.get(VR_SPACE_REAL).m[3];
p1_b = *(Coord3Df *)c.position.get(VR_SPACE_BLENDER).m[3];
Coord3Df v = p1 - p0;
percent = v.length() * WIDGET_LOOPCUT_SENSITIVITY;
if (VR_UI::shift_key_get()) {
percent *= WIDGET_TRANSFORM_TRANS_PRECISION;
}
if (v * *(Coord3Df *)Widget_Transform::manip_t.m[2] < 0) {
percent = -percent;
}
/* Finish edge slide operation */
doEdgeSlide(&loopcut_info, percent);
/* Free data. TODO_XR: Free all edge slide data. */
loopcut_info.state = TRANS_CONFIRM;
TransDataContainer *tc = loopcut_info.data_container;
if (tc) {
if (tc->custom.mode.data) {
MEM_freeN(tc->custom.mode.data);
tc->custom.mode.data = NULL;
}
if (tc->data) {
MEM_freeN(tc->data);
tc->data = NULL;
}
}
}
else {
if (!loopcut_dummy_op.customdata) {
return;
}
p1 = *(Coord3Df *)c.position.get(VR_SPACE_BLENDER).m[3];
/* Finish ring selection */
ringsel_finish(C, &loopcut_dummy_op);
ringsel_exit(C, &loopcut_dummy_op);
/* Execute loop cut operation */
loopcut_init(C, &loopcut_dummy_op, NULL);
}
BMEditMesh *em = BKE_editmesh_from_object(obedit);
EDBM_mesh_normals_update(em);
Widget_Transform::update_manipulator();
DEG_id_tag_update((ID *)obedit->data, ID_RECALC_GEOMETRY);
WM_main_add_notifier(NC_GEOM | ND_DATA, obedit->data);
ED_undo_push(C, "Loop Cut");
for (int i = 0; i < VR_SIDES; ++i) {
Widget_LoopCut::obj.do_render[i] = false;
}
}
static void render_arrow(float length)
{
/* Adapted from arrow_draw_geom() in arrow3d_gizmo.c */
uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
bool unbind_shader = true;
static float c_black[4] = {0.0f, 0.0f, 0.0f, 1.0f};
immBindBuiltinProgram(GPU_SHADER_3D_LINE_DASHED_UNIFORM_COLOR);
immUniformColor4fv(c_black);
immUniform1f("dash_width", 6.0f);
/* Axis */
GPU_line_width(1.0f);
immBegin(GPU_PRIM_LINES, 2);
immVertex3f(pos, 0.0f, 0.0f, -length);
immVertex3f(pos, 0.0f, 0.0f, length);
immEnd();
/* Arrow */
immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
immUniformColor4fv(c_black);
GPU_matrix_push();
float len = length * 0.1f;
float width = length * 0.04f;
GPU_matrix_translate_3f(0.0f, 0.0f, length);
imm_draw_circle_fill_3d(pos, 0.0, 0.0, width, 8);
imm_draw_cylinder_fill_3d(pos, width, 0.0, len, 8, 1);
GPU_matrix_translate_3f(0.0f, 0.0f, -length);
GPU_matrix_pop();
if (unbind_shader) {
immUnbindProgram();
}
}
void Widget_LoopCut::render(VR_Side side)
{
if (edge_slide) {
/* Render edge slide */
drawEdgeSlide(&loopcut_info);
/* Render arrow */
GPU_matrix_push();
GPU_matrix_mul(Widget_Transform::manip_t.m);
GPU_blend(true);
render_arrow(Widget_Transform::manip_scale_factor);
GPU_blend(false);
GPU_matrix_pop();
}
else {
/* Render preselection ring */
RingSelOpData *lcd = (RingSelOpData *)loopcut_dummy_op.customdata;
if (lcd) {
EDBM_preselect_edgering_draw(lcd->presel_edgering, lcd->ob->obmat);
}
}
Widget_LoopCut::obj.do_render[side] = false;
}
| 29.268293 | 198 | 0.601503 | [
"mesh",
"render",
"object",
"shape",
"vector",
"transform",
"3d"
] |
31268adbfd76ce737f08a4e2d17d16db86b89d60 | 52,322 | cpp | C++ | src/alm2.cpp | anyks/alm | e168ae3c2be39ff2349e266253dd43f4b237eddd | [
"MIT"
] | 40 | 2020-02-17T19:36:19.000Z | 2022-03-04T09:41:54.000Z | src/alm2.cpp | anyks/alm | e168ae3c2be39ff2349e266253dd43f4b237eddd | [
"MIT"
] | 1 | 2020-08-03T21:25:37.000Z | 2020-08-04T22:04:26.000Z | src/alm2.cpp | anyks/alm | e168ae3c2be39ff2349e266253dd43f4b237eddd | [
"MIT"
] | 3 | 2020-05-22T14:10:59.000Z | 2021-04-10T17:24:12.000Z | /**
* author: Yuriy Lobarev
* telegram: @forman
* phone: +7(910)983-95-90
* email: forman@anyks.com
* site: https://anyks.com
*/
#include <alm.hpp>
/**
* exist Метод проверки существования последовательности
* @param seq список слов последовательности
* @return результат проверки
*/
const bool anyks::Alm2::exist(const vector <size_t> & seq) const noexcept {
// Результат работы функции
bool result = false;
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0) && !this->arpa.empty()){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
result = (jt != it->second.end());
}
}
// Выводим результат
return result;
}
/**
* backoff Метод извлечения обратной частоты последовательности
* @param seq последовательность для извлечения обратной частоты
* @return обратная частота последовательности
*/
const double anyks::Alm2::backoff(const vector <size_t> & seq) const noexcept {
// Результат работы функции
double result = 0.0;
// Если контекст передан
if(!seq.empty() && !this->arpa.empty()){
// Получаем частоту последовательности
const auto & data = this->frequency(seq);
// Запоминаем обратную частоту последовательности
if(data.second != this->zero) result = data.second;
// Если последовательность длинее юниграммы
if(seq.size() > 1){
// Временная последовательность
vector <size_t> tmp(seq.begin() + 1, seq.end());
// Продолжаем увеличение обратной частоты
result += this->backoff(tmp);
}
}
// Выводим результат
return result;
}
/**
* weight Метод извлечения веса последовательности
* @param seq последовательность для извлечения веса
* @return вес последовательноси и n-грамма для которой она получена
*/
const pair <u_short, double> anyks::Alm2::weight(const vector <size_t> & seq) const noexcept {
// Результат работы функции
pair <u_short, double> result = {0, 0.0};
// Если контекст передан
if(!seq.empty() && !this->arpa.empty()){
// Временная последовательность
vector <size_t> tmp(seq.begin() + 1, seq.end());
// Получаем размер N-граммы
const u_short size = tmp.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(tmp) : tmp.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
if((jt != it->second.end()) && (jt->second.weight != this->zero)){
// Формируем полученный вес n-граммы
result = make_pair(size, jt->second.weight);
// Иначе продолжаем дальше
} else result = this->weight(tmp);
}
}
// Выводим результат
return result;
}
/**
* frequency Метод извлечения частоты n-граммы
* @param seq список слов последовательности
* @return частота и обратная частота n-граммы
*/
const pair <double, double> anyks::Alm2::frequency(const vector <size_t> & seq) const noexcept {
// Результат работы функции
pair <double, double> result = {this->zero, this->zero};
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0) && !this->arpa.empty()){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
if(jt != it->second.end()){
// Формируем полученный вес n-граммы
result = make_pair(jt->second.weight, jt->second.backoff);
}
}
}
// Выводим результат
return result;
}
/**
* set Метод установки последовательности в словарь
* @param seq последовательность слов для установки
*/
void anyks::Alm2::set(const vector <alm_t::seq_t> & seq) const noexcept {
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Параметры N-граммы
ngram_t ngram;
// Временная последовательность
vector <size_t> tmp;
// Объект текущей последовательности
const seq_t * data = nullptr;
// Выполняем перебор всей последовательности
for(size_t i = 0; i < seq.size(); i++){
// Получаем данные последовательности
data = &seq.at(i);
// Формируем список последовательностей
tmp.push_back(data->idw);
// Устанавливаем регистры последовательности
ngram.uppers = data->ups;
// Устанавливаем обратную частоту последовательности
ngram.backoff = (data->backoff == 0.0 ? this->zero : data->backoff);
// Устанавливаем основную частоту последовательности
ngram.weight = ((data->weight == 0.0) || (fabs(round(data->weight)) >= 99.0) ? this->zero : data->weight);
// Если такого размера последовательности не существует, добавляем его
auto ret = this->arpa.emplace(i + 1, map <size_t, ngram_t> ());
// Добавляем последовательность в словарь последовательностей
ret.first->second.emplace((i > 0 ? this->tokenizer->ids(tmp) : tmp.front()), ngram);
}
}
}
/**
* set Метод установки последовательности в словарь
* @param seq список идентификаторов слов которые нужно добавить
* @param uppers список верхних регистров последнего слова последовательности
* @param weight вес n-граммы из файла arpa
* @param backoff обратная частота документа из файла arpa
*/
void anyks::Alm2::set(const vector <size_t> & seq, const size_t uppers, const double weight, const double backoff) const noexcept {
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Параметры N-граммы
ngram_t ngram;
// Устанавливаем регистры последовательности
ngram.uppers = uppers;
// Устанавливаем обратную частоту последовательности
ngram.backoff = (backoff == 0.0 ? this->zero : backoff);
// Устанавливаем основную частоту последовательности
ngram.weight = ((weight == 0.0) || (fabs(round(weight)) >= 99.0) ? this->zero : weight);
// Получаем размер последовательности
const u_short size = seq.size();
// Если такого размера последовательности не существует, добавляем его
auto ret = this->arpa.emplace(size, map <size_t, ngram_t> ());
// Добавляем последовательность в словарь последовательностей
ret.first->second.emplace((size > 1 ? this->tokenizer->ids(seq) : seq.front()), ngram);
}
}
/**
* clear Метод очистки всех данных
*/
void anyks::Alm2::clear(){
// Выполняем очистку объекта arpa
this->arpa.clear();
// Выполняем удаление всех основных параметров
reinterpret_cast <alm_t *> (this)->clear();
}
/**
* perplexity Метод расчёта перплексии
* @param seq список последовательностей
* @return результат расчёта
*/
const anyks::Alm::ppl_t anyks::Alm2::perplexity(const vector <size_t> & seq) const noexcept {
// Результат работы функции
ppl_t result;
// Если текст передан
if(!this->arpa.empty() && (seq.size() > 2) && (this->size > 0) &&
(seq.front() == size_t(token_t::start)) && (seq.back() == size_t(token_t::finish))){
// Позиция n-граммы в контексте
size_t index = 0;
// Временная последовательность
vector <size_t> tmp;
// Количество переданных последовательностей
const size_t count = seq.size();
// Текст данных отладки собранных при расчёте
map <size_t, pair <string, string>> debugMessages;
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(this->size) ? this->size : count);
// Проверяем разрешено ли неизвестное слово
const bool isAllowUnk = (this->frequency({size_t(token_t::unk)}).first != this->zero);
/**
* debugFn Функция вывода отладочной информации
* @param first первое слово
* @param second второе слово
* @param bigram является ли n-грамма длиннее биграммы
* @param gram граммность n-граммы для которой был произведён расчёт
* @param weight полученный вес n-граммы при расчёте
* @param delim проверочный делитель n-граммы
* @param pos позиция n-граммы в контексте
*/
auto debugFn = [&debugMessages, this](const string & first, const string & second, const bool bigram, const u_short gram, const double weight, const double delim, const size_t pos){
// Выводим отладочную информацию
if(this->isOption(options_t::debug)){
// Граммность n-граммы
string numGram = "OOV";
// Результат работы функции
pair <string, string> result;
// Значение полученного веса
double prob = 0.0, lprob = this->zero;
// Если вес не нулевой
if(weight != 0.0){
// Запоминаем вес n-граммы
lprob = weight;
// Избавляемся от логорифма
prob = pow(10, weight);
// Устанавливаем граммность
numGram = (to_string(gram) + "gram");
}
// Формируем информационное сообщение
result.first = this->alphabet->format(
"p( %s | %s %s) \t= [%s] %4.8f [ %4.8f ] / %4.8f",
second.c_str(),
first.c_str(),
(bigram ? "..." : ""),
numGram.c_str(),
prob, lprob, delim
);
// Выполняем округление делителя
const double value = (ceil((delim * 10000.0) + 0.5) / 10000.0);
// Если делитель не сходится к единице, выводим сообщение
if(fabs(value - 1.0) > 0.0009) result.second = this->alphabet->format("word probs for this context sum to %4.8f != 1", delim);
// Блокируем поток
this->locker.lock();
// Добавляем в список отладки
debugMessages.emplace(pos, move(result));
// Разблокируем поток
this->locker.unlock();
}
};
/**
* calcFn Функция расчёта перплексии
* @param seq последовательность слов для обработки
* @return вес n-граммы
*/
auto calcFn = [isAllowUnk, this](const vector <size_t> & seq) noexcept {
// Результат работы функции
pair <u_short, double> result = {0, 0.0};
// Если данные не пустые
if(!seq.empty()){
// Получаем нашу последовательность
vector <size_t> tmp = seq;
// Если первый элемент является неизвестным словом, удаляем его
if(!isAllowUnk){
// Удаляем все первые неизвестные слова
while(!tmp.empty() && (tmp.front() == size_t(token_t::unk))){
// Удаляем первый элемент в списке
tmp.assign(tmp.begin() + 1, tmp.end());
}
}
// Если есть еще смысл искать
if(!tmp.empty()){
// Список последовательности
vector <size_t> seq;
// Переходим по всей последовательностив
for(auto & idw : tmp){
// Формируем последовательность
seq.push_back(idw);
// Получаем частоту последовательности
result.second = this->frequency(seq).first;
// Если последовательность не существует
if((idw != size_t(token_t::start)) && (idw != size_t(token_t::unk)) && (result.second == this->zero)){
// Если последнее слово последовательности существует
if(this->exist({tmp.back()})){
// Получаем вес последовательности
const auto & wrs = this->weight(tmp);
// Получаем грамность
result.first = wrs.first;
// Запоминаем полученный вес
result.second = wrs.second;
// Если вес получен для юниграммы, выполняем поиск частоты отката
if(result.first == 1){
// Получаем список последовательности для извлечения обратной частоты
tmp.assign(tmp.begin(), tmp.end() - 1);
// Выполняем расчёт веса n-граммы
result.second += this->backoff(tmp);
}
// Если слово не найдено, устанавливаем -inf
} else result.second = 0.0;
// Выходим из цикла
break;
}
// Увеличиваем граммность
result.first++;
}
}
}
// Выводим результат
return result;
};
/**
* putDebugFn Функция расчёта отладочной информации
* @param seq последовательность слов для обработки
* @param gram граммность n-граммы для которой был произведён расчёт
* @param weight полученный вес n-граммы при расчёте
* @param pos позиция n-граммы в контексте
*/
auto putDebugFn = [&debugFn, this](const vector <size_t> & seq, const u_short gram, const double weight, const size_t pos) noexcept {
// Если последовательность передана
if(!seq.empty() && this->isOption(options_t::debug)){
// Получившийся разделитель
double delim = 0.0;
// Получаем нашу последовательность
vector <size_t> tmp = seq;
// Получаем количество слов в последовательности
const size_t count = tmp.size();
// Выполняем првоерку больше ли переданная последовательность биграммы
const bool isBigram = (count > 2);
// Получаем второе слово
const string & second = this->word(tmp.back()).real();
// Получаем первое слово
const string & first = this->word(tmp.at(count - 2)).real();
// Укорачиваем последовательность до 2-х слов
if(count > 2) tmp.assign(tmp.begin() + (count - 2), tmp.end());
// Удаляем последний элемент в списке
tmp.pop_back();
// Выполняем расчёт обратной частоты последовательности
const double backoff = this->backoff(tmp);
// Переходим по всем словам словаря
for(auto & value : this->arpa.at(1)){
// Если веса у n-граммы нету
if((value.second.weight != this->zero)){
// Формируем нашу последовательность
tmp.push_back(value.first);
// Получаем частоту последовательности
auto calc = this->frequency(tmp);
// Если частота последовательности получена
if(calc.first != this->zero) delim += exp(calc.first * this->mln10);
// Если последовательность не существует, считаем частоту иначе
else delim += exp((this->weight(tmp).second + backoff) * this->mln10);
// Удаляем последний элемент в списке
tmp.pop_back();
}
}
// Выводим отладочную информацию
debugFn(first, second, isBigram, gram, weight, delim, pos);
}
};
// Сбрасываем значение результата
result.logprob = 0.0;
/**
* runFn Функция запуска расчёта перплексии
* @param seq последовательность слов для обработки
* @param pos позиция n-граммы в контексте
*/
auto runFn = [&result, &calcFn, &putDebugFn](const vector <size_t> & seq, const size_t pos){
// Выполняем проверку существования граммы
auto calc = calcFn(seq);
// Если вес получен
if(calc.second != 0.0)
// Увеличиваем общее значение веса
result.logprob += calc.second;
// Увеличиваем количество нулевых весов
else result.zeroprobs++;
// Выводим отладочную информацию
putDebugFn(seq, calc.first, calc.second, pos);
};
// Обрабатываем первую часть n-грамм
for(u_short i = 2; i < offset2; i++){
// Получаем первую часть последовательности
tmp.assign(seq.begin(), seq.begin() + i);
// Добавляем в тредпул новое задание на обработку
runFn(tmp, index);
// Увеличиваем смещение позиции
index++;
}
// Если есть ещё n-граммы
if(count >= this->size){
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp.assign(seq.begin() + offset1, seq.begin() + offset2);
// Добавляем в тредпул новое задание на обработку
runFn(tmp, index);
// Увеличиваем смещение позиции
index++;
// Увеличиваем смещение
offset1++;
offset2++;
}
}
// Если неизвестное слово не разрешено
if(!isAllowUnk){
// Считаем количество неизвестных слов
for(auto & idw : seq){
// Считаем количество неизвестных слов
if(idw == size_t(token_t::unk)) result.oovs++;
}
}
// Устанавливаем предложение
result.sentences = 1;
// Устанавливаем количество слов
result.words = (seq.size() - 2);
// Если количество нулевых весов и количество неизвестных слов получено
if((result.oovs > 0) && (result.zeroprobs > 0)) result.zeroprobs -= result.oovs;
// Выполняем расчёт перплексии
const auto ppl = this->pplCalculate(result.logprob, result.words, result.oovs);
// Усталавниваем полученные значения перплексии
result.ppl = ppl.first;
result.ppl1 = ppl.second;
// Выводим отладочную информацию
if(this->isOption(options_t::debug)){
// Блокируем поток
this->locker.lock();
// Если список отладки сформирован
if(!debugMessages.empty()){
// Получаем обрабатываемый текст
const wstring & text = this->context(seq, true);
// Выводим сообщение отладки - количество слов
this->alphabet->log("%ls\n", alphabet_t::log_t::info, this->logfile, text.c_str());
// Переходим по всему списку отладки
for(auto & mess : debugMessages){
// Выводим основное сообщение отладки
this->alphabet->log("%s", alphabet_t::log_t::info, this->logfile, mess.second.first.c_str());
// Если второе сообщение существует, выводим и его
if(!mess.second.second.empty()) this->alphabet->log("%s", alphabet_t::log_t::warning, this->logfile, mess.second.second.c_str());
}
}
// Выводим разделитель
this->alphabet->log("%s", alphabet_t::log_t::null, this->logfile, "\r\n");
// Выводим сообщение отладки - количество слов
this->alphabet->log(
"%u sentences, %u words, %u OOVs",
alphabet_t::log_t::info,
this->logfile,
result.sentences,
result.words,
result.oovs
);
// Выводим сообщение отладки - результатов расчёта
this->alphabet->log(
"%u zeroprobs, logprob= %4.8f ppl= %4.8f ppl1= %4.8f\r\n",
alphabet_t::log_t::info,
this->logfile,
result.zeroprobs,
result.logprob,
result.ppl,
result.ppl1
);
// Разблокируем поток
this->locker.unlock();
}
}
// Выводим результат
return result;
}
/**
* check Метод проверки существования последовательности, с указанным шагом
* @param seq список слов последовательности
* @param step размер шага проверки последовательности
* @return результат проверки
*/
const bool anyks::Alm2::check(const vector <size_t> & seq, const u_short step) const noexcept {
// Результат работы функции
bool result = false;
// Если последовательность передана
if(!seq.empty() && (seq.size() >= size_t(step)) && (this->size >= step) && !this->arpa.empty()){
// Временная последовательность
vector <size_t> tmp, sequence;
// Если последовательность не экранированна
if((seq.back() == size_t(token_t::finish)) &&
(seq.front() == size_t(token_t::start))) sequence.assign(seq.begin() + 1, seq.end() - 1);
else if(seq.back() == size_t(token_t::finish)) sequence.assign(seq.begin(), seq.end() - 1);
else if(seq.front() == size_t(token_t::start)) sequence.assign(seq.begin() + 1, seq.end());
else sequence.assign(seq.begin(), seq.end());
// Если последовательность, до сих пор соответствует
if(sequence.size() >= size_t(step)){
/**
* checkFn Функция проверки существования последовательности
* @param seq список слов последовательности
* @return результат проверки
*/
auto checkFn = [this](const vector <size_t> & seq) noexcept {
// Регистры слова в последовательности
bool result = false;
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
result = (jt != it->second.end());
}
}
// Выводим результат
return result;
};
// Количество переданных последовательностей
const size_t count = sequence.size();
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(step) ? (step < 2 ? 2 : step) : count);
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp.assign(sequence.begin() + offset1, sequence.begin() + offset2);
// Если последовательность получена
if(!tmp.empty()){
// Получаем регистр слова
result = checkFn(tmp);
// Если последовательность не найдена, выходим
if(!result) break;
// Выходим из цикла
} else break;
// Увеличиваем смещение
offset1++;
offset2++;
}
}
}
// Выводим результат
return result;
}
/**
* exist Метод проверки существования последовательности
* @param seq список слов последовательности
* @param step размер шага проверки последовательности
* @return результат проверки
*/
const pair <bool, size_t> anyks::Alm2::exist(const vector <size_t> & seq, const u_short step) const noexcept {
// Результат работы функции
pair <bool, size_t> result = {false, 0};
// Если последовательность передана
if(!seq.empty() && (seq.size() >= size_t(step)) && (this->size >= step) && !this->arpa.empty()){
// Временная последовательность
vector <size_t> sequence;
// Если последовательность не экранированна
if((seq.back() == size_t(token_t::finish)) &&
(seq.front() == size_t(token_t::start))) sequence.assign(seq.begin() + 1, seq.end() - 1);
else if(seq.back() == size_t(token_t::finish)) sequence.assign(seq.begin(), seq.end() - 1);
else if(seq.front() == size_t(token_t::start)) sequence.assign(seq.begin() + 1, seq.end());
else sequence.assign(seq.begin(), seq.end());
// Если последовательность, до сих пор соответствует
if(sequence.size() >= size_t(step)){
/**
* Прототип функции проверки на существование последовательности
* @param начальная позиция итератора в последовательности
* @return результат проверки, сущестования последовательности
*/
function <const pair <bool, size_t> (u_short)> checkFn;
/**
* checkFn Функция проверки на существование последовательности
* @param start начальная позиция итератора в последовательности
* @return результат проверки, сущестования последовательности
*/
checkFn = [&checkFn, &sequence, step, this](u_short start) noexcept {
// Последовательность для проверки
vector <size_t> seq;
// Результат работы функции
pair <bool, size_t> result = {false, 0};
// Идентификатор слова и количество слов в последовательности
size_t idw = idw_t::NIDW, count = sequence.size();
// Получаем конечный элемент
const u_short stop = (start + ((count - size_t(start)) >= size_t(step) ? step : count - start));
// Переходим по всему объекту
for(u_short i = start; i < stop; i++){
// Получаем идентификатор слова
idw = sequence.at(i);
// Если идентификатор токена - валиден
if(this->tokenizer->isIdWord(idw)) seq.push_back(idw);
// Если токен не валиден
else {
// Увеличиваем начало следующей итерации
start += 2;
// Запоминаем, что результат возможем
result.first = true;
// Выходим из цикла
break;
}
}
// Если последовательность предположительно чистая
if(!result.first && !seq.empty()){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
result.first = (jt != it->second.end());
// Увеличиваем начало следующей итерации
if(result.first){
// Увеличиваем стартовую позицию
start++;
// Устанавливаем количество совпадений
if(step == stop) result.second = step;
}
}
}
// Если начало следующей итерации еще возможно
if(result.first && (size_t(start) < count)){
// Выполняем поиск дальше
const auto & res = checkFn(start);
// Устанавливаем результат поиска
result.first = res.first;
// Увеличиваем количество найденных совпадений
result.second += res.second;
}
// Выводим результат проверки
return result;
};
// Выполняем проверку
result = checkFn(0);
}
}
// Выводим результат
return result;
}
/**
* check Метод проверки существования последовательности
* @param seq список слов последовательности
* @param accurate режим точной проверки
* @return результат проверки
*/
const pair <bool, size_t> anyks::Alm2::check(const vector <size_t> & seq, const bool accurate) const noexcept {
// Результат работы функции
pair <bool, size_t> result = {false, 0};
// Если последовательность передана
if(!seq.empty() && !this->arpa.empty()){
// Временная последовательность
vector <size_t> tmp, sequence;
// Если последовательность не экранированна
if((seq.back() == size_t(token_t::finish)) &&
(seq.front() == size_t(token_t::start))) sequence.assign(seq.begin() + 1, seq.end() - 1);
else if(seq.back() == size_t(token_t::finish)) sequence.assign(seq.begin(), seq.end() - 1);
else if(seq.front() == size_t(token_t::start)) sequence.assign(seq.begin() + 1, seq.end());
else sequence.assign(seq.begin(), seq.end());
/**
* Прототип функции проверки существования последовательности
* @param список слов последовательности
* @return результат проверки
*/
function <const pair <bool, size_t> (const vector <size_t> &)> checkFn;
/**
* checkFn Функция проверки существования последовательности
* @param seq список слов последовательности
* @return результат проверки
*/
checkFn = [&checkFn, accurate, this](const vector <size_t> & seq) noexcept {
// Регистры слова в последовательности
pair <bool, size_t> result = {false, 0};
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
result.first = (jt != it->second.end());
// Если последовательность существует
if(result.first) result.second = jt->second.uppers;
}
// Если последовательность не существует
if(!accurate && !result.first && (seq.size() > 2)){
// Получаем новую последовательность
vector <size_t> tmp(seq.begin() + 1, seq.end());
// Пробуем уменьшить n-грамму
result = checkFn(tmp);
}
}
// Выводим результат
return result;
};
// Количество переданных последовательностей
const size_t count = sequence.size();
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(this->size) ? this->size : count);
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp.assign(sequence.begin() + offset1, sequence.begin() + offset2);
// Если последовательность получена
if(!tmp.empty()){
// Получаем регистр слова
result = checkFn(tmp);
// Если последовательность не найдена, выходим
if(!result.first) break;
// Выходим из цикла
} else break;
// Увеличиваем смещение
offset1++;
offset2++;
}
}
// Выводим результат
return result;
}
/**
* setBin Метод установки бинарных данных в словарь
* @param buffer буфер с бинарными данными
*/
void anyks::Alm2::setBin(const vector <char> & buffer) const noexcept {
// Если буфер передан
if(!buffer.empty()){
// Полученная последовательность
seq_t sequence;
// Количество слов в последовательности
u_short count = 0;
// Смещение в буфере
size_t offset = 0;
// Полученные данные последовательности
vector <seq_t> seq;
// Получаем данные буфера
const char * data = buffer.data();
// Выполняем перебор данных всего буфера
while(offset < buffer.size()){
// Извлекаем количество слов в последовательности
memcpy(&count, data + offset, sizeof(count));
// Увеличиваем смещение
offset += sizeof(count);
// Если последовательность получена
if(count > 0){
// Очищаем последовательность
seq.clear();
// Переходим по всем словам последовательности
for(u_short i = 0; i < count; i++){
// Извлекаем данные слова
memcpy(&sequence, data + offset, sizeof(sequence));
// Добавляем последовательность в список
seq.push_back(sequence);
// Увеличиваем смещение
offset += sizeof(sequence);
}
// Если нужно установить исходные данные
if(!seq.empty()) this->set(seq);
}
}
}
}
/**
* setBin2 Метод установки бинарных данных в словарь
* @param buffer буфер с бинарными данными
*/
void anyks::Alm2::setBin2(const vector <char> & buffer) const noexcept {
// Если буфер передан
if(!buffer.empty()){
// Параметры N-граммы
ngram_t ngram;
// Размер N-грамм
u_short size = 0;
// Получаем данные буфера
const char * data = buffer.data();
// Количество слов в последовательности, смещение в буфере и идентификатор последовательности
size_t count = 0, offset = 0, ids = 0;
// Извлекаем размер N-граммы
memcpy(&size, data + offset, sizeof(size));
// Увеличиваем смещение
offset += sizeof(size);
// Если размер N-грамм получен
if(size > 0){
// Если такого размера последовательности не существует, добавляем его
auto ret = this->arpa.emplace(size, map <size_t, ngram_t> ());
// Извлекаем количество N-грамм
memcpy(&count, data + offset, sizeof(count));
// Увеличиваем смещение
offset += sizeof(count);
// Если количество N-грамм получено
if(count > 0){
// Переходим по всему списку N-грамм
for(size_t i = 0; i < count; i++){
// Получаем идентификатор последовательности
memcpy(&ids, data + offset, sizeof(ids));
// Увеличиваем смещение
offset += sizeof(ids);
// Если идентификатор получен
if(ids > 0){
// Получаем параметры N-граммы
memcpy(&ngram, data + offset, sizeof(ngram));
// Увеличиваем смещение
offset += sizeof(ngram);
// Добавляем последовательность в словарь последовательностей
ret.first->second.emplace(ids, ngram);
}
}
}
}
}
}
/**
* getBin Метод извлечения данных arpa в бинарном виде
* @param callback функция обратного вызова
*/
void anyks::Alm2::getBin(function <void (const vector <char> &, const size_t, const u_short)> callback) const noexcept {
// Если данные загружены
if(!this->arpa.empty()){
// Буфер данных n-граммы
vector <char> buffer;
// Бинарные данные для добавления в буфер
const char * bin = nullptr;
// Текущий и предыдущий статус
u_short actual = 0, past = 100;
// Количество всех записей N-грамм
size_t count = 0, size = 0, index = 0, countNgrams = 0;
// Переходим по всему списку N-грамм
for(auto & item : this->arpa){
// Увеличиваем количество N-грамм
count += item.second.size();
}
// Переходим по всему списку N-грамм
for(auto & item : this->arpa){
// Получаем количество элементов в буфере
size = item.second.size();
// Получаем бинарные данные размера N-Граммы
bin = reinterpret_cast <const char *> (&item.first);
// Добавляем в буфер количество слов
buffer.insert(buffer.end(), bin, bin + sizeof(item.first));
// Получаем бинарные данные количества слов
bin = reinterpret_cast <const char *> (&size);
// Добавляем в буфер количество слов
buffer.insert(buffer.end(), bin, bin + sizeof(size));
// Переходим по всем N-Граммам
for(auto & value : item.second){
// Получаем бинарные данные идентификатора N-граммы
bin = reinterpret_cast <const char *> (&value.first);
// Добавляем в буфер бинарные данные идентификатора
buffer.insert(buffer.end(), bin, bin + sizeof(value.first));
// Получаем бинарные данные самой N-граммы
bin = reinterpret_cast <const char *> (&value.second);
// Добавляем в буфер бинарные данные N-граммы
buffer.insert(buffer.end(), bin, bin + sizeof(value.second));
// Увеличиваем значение индекса
index++;
// Увеличиваем количество обработанных N-грамм
if(item.first == this->size) countNgrams++;
// Выполняем расчёт текущего статуса
actual = u_short(index / double(count) * 100.0);
// Если статус обновился
if(actual != past){
// Запоминаем текущий статус
past = actual;
// Выводим статус извлечения
callback({}, countNgrams, actual);
}
}
// Выводим результат
callback(buffer, countNgrams, actual);
// Очищаем буфер данных
buffer.clear();
}
// Очищаем полученный буфер n-граммы
buffer.clear();
// Освобождаем выделенную память
vector <char> ().swap(buffer);
// Выводим пустой результат
} else callback({}, 0, 0);
}
/**
* sentences Метод генерации предложений
* @param callback функция обратного вызова
*/
void anyks::Alm2::sentences(function <const bool (const wstring &)> callback) const noexcept {
// Если языковая модель загружена
if(!this->arpa.empty()){
/**
* Прототип функции генерации предложений
* @param список собранной последовательности
*/
function <const bool (const vector <size_t> &)> runFn;
/**
* runFn Функция генерации предложений
* @param seq список собранной последовательности
*/
runFn = [&callback, &runFn, this](vector <size_t> seq) noexcept {
// Получаем базу юниграмм
auto it = this->arpa.find(1);
// Если база с последовательностями существует
if(it != this->arpa.end()){
// Если последовательность пустая
if(seq.empty()){
// Получаем базу биграмм
auto jt = this->arpa.find(2);
// Если база с последовательностями существует
if(jt != this->arpa.end()){
// Добавляем в список последовательности начало предложения
seq.push_back(size_t(token_t::start));
// Переходим по всему списку последовательности
for(auto & item : it->second){
// Если это не начало предложения и не конец предложения и не неизвестное слово
if((item.first != size_t(token_t::finish)) && (item.second.weight != this->zero)){
// Добавляем юниграмму в последовательность
seq.push_back(item.first);
// Если последовательность существует
if((jt->second.count(this->tokenizer->ids(seq)) > 0) && !runFn(seq)) return false;
// Удаляем добавленную юниграмму из последовательности
seq.pop_back();
}
}
}
// Если последовательность не пустая
} else {
// Получаем размер N-граммы
const size_t size = (seq.size() - (seq.size() >= this->size ? this->size - 1 : seq.size()));
// Создаём временную последовательность
vector <size_t> tmp(seq.begin() + size, seq.end());
// Получаем базу N-грамм
auto jt = this->arpa.find(tmp.size() + 1);
// Если база с последовательностями существует
if(jt != this->arpa.end()){
// Переходим по всему списку последовательности
for(auto & item : it->second){
// Если это не начало предложения и не конец предложения и не неизвестное слово
if(item.second.weight != this->zero){
// Добавляем юниграмму в последовательность
tmp.push_back(item.first);
// Если последовательность существует
if(jt->second.count(this->tokenizer->ids(tmp)) > 0){
// Добавляем в последовательность полученное слово
seq.push_back(item.first);
// Если это не конец предложения
if(item.first != size_t(token_t::finish)){
// Выполняем дальнейшую обработку, если нужно завершить, завершаем
if(!runFn(seq)) return false;
// Выводим результат
} else if(!callback(this->context(seq, true))) return false;
// Удаляем последнее слово из последовательности
seq.pop_back();
}
// Удаляем добавленную юниграмму из последовательности
tmp.pop_back();
}
}
}
}
}
// Выводим результат
return true;
};
// Выволняем генерацию предложений
runFn({});
}
}
/**
* getUppers Метод извлечения регистров для каждого слова
* @param seq последовательность слов для сборки контекста
* @param upps список извлечённых последовательностей
*/
void anyks::Alm2::getUppers(const vector <size_t> & seq, vector <size_t> & upps) const noexcept {
// Если последовательность передана
if(!seq.empty() && !this->arpa.empty()){
// Очищаем список регистров
upps.clear();
// Временная последовательность
vector <size_t> tmp, sequence = seq;
// Если последовательность не экранированна
const bool isFront = (seq.back() == size_t(token_t::finish));
const bool isBack = (seq.front() == size_t(token_t::start));
// Если флаги не установлены
if(!isFront) sequence.push_back((size_t) token_t::finish);
if(!isBack) sequence.insert(sequence.begin(), (size_t) token_t::start);
/**
* Прототип функции извлечения регистров последовательности
* @param список слов последовательности
* @return регистры последнего слова последовательности
*/
function <const size_t (const vector <size_t> &)> uppersFn;
/**
* uppersFn Функция извлечения регистров последовательности
* @param seq список слов последовательности
* @return регистры последнего слова последовательности
*/
uppersFn = [&uppersFn, this](const vector <size_t> & seq) noexcept {
// Регистры слова в последовательности
size_t result = 0;
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
if(jt != it->second.end()) result = jt->second.uppers;
// Если последовательность не существует
else if(seq.size() > 2){
// Получаем новую последовательность
vector <size_t> tmp(seq.begin() + 1, seq.end());
// Пробуем уменьшить n-грамму
result = uppersFn(tmp);
}
}
}
// Выводим результат
return result;
};
// Регистр слова
size_t uppers = 0;
// Флаг сборки первой итерации
bool flag = false;
// Количество переданных последовательностей
const size_t count = sequence.size();
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(this->size) ? this->size : count);
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp.assign(sequence.begin() + offset1, sequence.begin() + offset2);
// Если последовательность получена
if(!tmp.empty()){
// Получаем регистр слова
uppers = uppersFn(tmp);
// Если сборка первой n-граммы не выполнена
if(!flag && (flag = !flag)){
// Переходим по всей последовательности
for(size_t i = (!isFront ? 1 : 0); i < tmp.size(); i++){
// Если это не последнее слово в списке, добавляем нули
if(i != (tmp.size() - 1)) upps.push_back(0);
// Если же это последнее слово, добавляем регистр
else upps.push_back(uppers);
}
// Если же сборка первой n-граммы уже выполнена
} else upps.push_back(uppers);
// Выходим из цикла
} else break;
// Увеличиваем смещение
offset1++;
offset2++;
}
// Удаляем лишний элемент регистра
if(!isBack) upps.pop_back();
}
}
/**
* find Метод поиска n-грамм в тексте
* @param text текст в котором необходимо найти n-граммы
* @param callback функция обратного вызова
*/
void anyks::Alm2::find(const wstring & text, function <void (const wstring &)> callback) const noexcept {
// Если слово передано
if(!text.empty() && !this->arpa.empty()){
// Идентификатор неизвестного слова
const size_t uid = (size_t) token_t::unk;
// Идентификатор начала предложения
const size_t sid = (size_t) token_t::start;
// Идентификатор конца предложения
const size_t fid = (size_t) token_t::finish;
// Список последовательностей для обучения
vector <size_t> seq = {sid};
// Собранная n-грамма для проверки
vector <wstring> words = {L"<s>"};
// Кэш списка собранных n-грамм
unordered_set <wstring> cache = {};
/**
* callbackFn Функция вывода результата
* @param words список слов для вывода результата
* @param count количество слов для вывода результата
*/
auto callbackFn = [&cache, &callback](const vector <wstring> & words, const size_t count){
// Если список слов передан
if(!words.empty() && (count > 1)){
// Получившаяся строка текста
wstring text = L"";
// Переходим по всему списку слов
for(size_t i = 0; i < count; i++){
// Добавляем в текст слово
text.append(words.at(i));
// Добавляем пробел
text.append(L" ");
}
// Удаляем последний пробел
text.pop_back();
// Если текст получен
if(!text.empty() && (cache.count(text) < 1)){
// Выводим результат
callback(text);
// Добавляем собранный результат в кэш
cache.emplace(text);
}
}
};
/**
* unkFn Функция установки неизвестного слова в последовательность
* @return нужно ли остановить сбор последовательности
*/
auto unkFn = [&seq, &words, uid, this]() noexcept {
// Получаем установленное неизвестное слово
const word_t & word = (this->unknown > 0 ? this->word(this->unknown) : L"");
// Если неизвестное слово не установлено
if((this->unknown == 0) || word.empty()){
// Добавляем неизвестное слово
seq.push_back(uid);
// Добавляем в список неизвестное слово
words.push_back(L"<unk>");
// Если неизвестное слово установлено
} else if(!word.empty()) {
// Добавляем установленное неизвестное слово
seq.push_back(this->unknown);
// Добавляем полученное ранее слово
words.push_back(word.wreal());
}
};
/**
* Прототип функции проверки существования последовательности
* @param список слов последовательности
* @param список реальных слов в последовательности
*/
function <void (const vector <size_t> &, const vector <wstring> &)> checkFn;
/**
* checkFn Функция проверки существования последовательности
* @param seq список слов последовательности
* @param words список реальных слов в последовательности
*/
checkFn = [&checkFn, &callbackFn, this](const vector <size_t> & seq, const vector <wstring> & words) noexcept {
// Если список последовательностей передан
if(!seq.empty() && !words.empty() && (this->size > 0)){
// Итератор для подсчета длины n-граммы
u_short index = 0;
// Результат поиска слова
bool exist = false;
// Временный список последовательности
vector <size_t> tmp;
// Переходим по всей последовательности
for(auto & idw : seq){
// Добавляем слово в последовательность
tmp.push_back(idw);
// Выполняем проверку последовательности
exist = this->exist(tmp);
// Если последовательность не получена, выходим из цикла
if(!exist) break;
// Увеличиваем индекс найденных элементов
++index;
}
// Выводим результат
callbackFn(words, index);
// Если последовательность не существует
if(!exist && (seq.size() > 2)){
// Получаем новую последовательность
vector <size_t> tmp1(seq.begin() + 1, seq.end());
// Получаем новую последовательность слов
vector <wstring> tmp2(words.begin() + 1, words.end());
// Пробуем уменьшить n-грамму
checkFn(tmp1, tmp2);
}
}
};
/**
* resFn Функция вывода результата
*/
auto resFn = [&]() noexcept {
// Добавляем в список конец предложения
seq.push_back(fid);
// Добавляем конец предложения
words.push_back(L"</s>");
/**
* Если слова всего два, значит это начало и конец предложения.
* Нам же нужны только нормальные n-граммы.
*/
if((seq.size() > 2) && (seq.size() == words.size())){
// Временная последовательность
vector <size_t> tmp1;
// Временный список слов
vector <wstring> tmp2;
// Количество переданных последовательностей
const size_t count = seq.size();
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(this->size) ? this->size : count);
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp1.assign(seq.begin() + offset1, seq.begin() + offset2);
// Получаем первую часть списка слов
tmp2.assign(words.begin() + offset1, words.begin() + offset2);
// Если последовательность получена
if(!tmp1.empty()) checkFn(tmp1, tmp2);
// Увеличиваем смещение
offset1++;
offset2++;
}
// Выводим разделитель предложений
callback(L"\r\n");
}
// Очищаем список последовательностей
seq.clear();
// Очищаем список собранных слов
words.clear();
// Добавляем в список начало предложения
seq.push_back(sid);
// Добавляем начало предложения
words.push_back(L"<s>");
};
/**
* modeFn Функция обработки разбитого текста
* @param word слово для обработки
* @param ctx контекст к которому принадлежит слово
* @param reset флаг сброса контекста
* @param stop флаг завершения обработки
*/
auto modeFn = [&](const wstring & word, const vector <string> & ctx, const bool reset, const bool stop) noexcept {
// Если это сброс контекста, отправляем результат
if(reset) resFn();
// Если слово передано
if(!word.empty()){
// Получаем данные слова
word_t tmp = word;
// Если модуль питона активирован
if(this->python != nullptr){
// Если работа идет не изнутри Python
#ifndef NOPYTHON
// Ищем скрипт обработки слов
auto it = this->scripts.find(1);
// Если скрипт обработки слов установлен
if(it != this->scripts.end()){
// Блокируем поток
this->locker.lock();
// Выполняем внешний python скрипт
tmp = this->python->run(it->second.second, {tmp.real()}, ctx);
// Разблокируем поток
this->locker.unlock();
}
#endif
// Если модуль предобработки слов, существует
} else if(this->wordPress != nullptr) tmp = this->wordPress(tmp.real(), ctx);
// Если слово не разрешено
if(tmp.length() >= MAX_WORD_LENGTH) unkFn();
// Если слово разрешено
else if(!tmp.empty()) {
// Получаем идентификатор слова
const size_t idw = this->getIdw(tmp);
// Если это плохое слово, заменяем его на неизвестное
if((idw == 0) || (idw == idw_t::NIDW) || (this->badwords.count(idw) > 0)) unkFn();
// Иначе продолжаем дальше
else {
// Проверяем является ли строка словом
const bool isWord = !this->tokenizer->isToken(idw);
// Если это неизвестное слово
if((idw == uid) || (isWord && (this->getWord(idw) == nullptr))) unkFn();
// Иначе добавляем слово
else if(!isWord || (this->goodwords.count(idw) > 0) || this->alphabet->isAllowed(tmp)){
// Добавляем идентификатор в список последовательности
seq.push_back(idw);
// Добавляем слово в список слов
words.push_back(word);
// Отправляем слово как неизвестное
} else unkFn();
}
}
}
// Если это конец, отправляем результат
if(stop) resFn();
// Выводим результат
return true;
};
// Выполняем разбивку текста на токены
this->tokenizer->run(text, modeFn);
}
}
/**
* context Метод сборки текстового контекста из последовательности
* @param seq последовательность слов для сборки контекста
* @param nwrd флаг разрешающий вывод системных токенов
* @return собранный текстовый контекст
*/
const wstring anyks::Alm2::context(const vector <size_t> & seq, const bool nwrd) const noexcept {
// Результат работы функции
wstring result = L"";
// Если последовательность передана
if(!seq.empty() && !this->arpa.empty()){
// Временная последовательность
vector <size_t> tmp, sequence = seq;
// Если последовательность не экранированна
if(seq.back() != size_t(token_t::finish)) sequence.push_back((size_t) token_t::finish);
if(seq.front() != size_t(token_t::start)) sequence.insert(sequence.begin(), (size_t) token_t::start);
/**
* Прототип функции извлечения регистров последовательности
* @param список слов последовательности
* @return регистры последнего слова последовательности
*/
function <const size_t (const vector <size_t> &)> uppersFn;
/**
* uppersFn Функция извлечения регистров последовательности
* @param seq список слов последовательности
* @return регистры последнего слова последовательности
*/
uppersFn = [&uppersFn, this](const vector <size_t> & seq) noexcept {
// Регистры слова в последовательности
size_t result = 0;
// Если список последовательностей передан
if(!seq.empty() && (this->size > 0)){
// Получаем размер N-граммы
const u_short size = seq.size();
// Выполняем поиск списка N-грамм
auto it = this->arpa.find(size);
// Если список N-грамм получен
if(it != this->arpa.end()){
// Получаем идентификатор последовательности
const size_t ids = (size > 1 ? this->tokenizer->ids(seq) : seq.front());
// Выполняем проверку существования последовательности
auto jt = it->second.find(ids);
// Если последовательность существует
if(jt != it->second.end()) result = jt->second.uppers;
// Если последовательность не существует
else if(seq.size() > 2){
// Получаем новую последовательность
vector <size_t> tmp(seq.begin() + 1, seq.end());
// Пробуем уменьшить n-грамму
result = uppersFn(tmp);
}
}
}
// Выводим результат
return result;
};
// Полученное слово последовательности
word_t word = L"";
// Регистр слова
size_t uppers = 0;
// Флаг сборки первой итерации
bool flag = false;
// Количество переданных последовательностей
const size_t count = sequence.size();
// Определяем смещение в последовательности
size_t offset1 = 0, offset2 = (count > size_t(this->size) ? this->size : count);
// Выполняем извлечение данных
while(offset2 < (count + 1)){
// Получаем первую часть последовательности
tmp.assign(sequence.begin() + offset1, sequence.begin() + offset2);
// Если последовательность получена
if(!tmp.empty()){
// Получаем регистр слова
uppers = uppersFn(tmp);
// Если сборка первой n-граммы не выполнена
if(!flag && (flag = !flag)){
// Переходим по всей последовательности
for(size_t i = 0; i < tmp.size(); i++){
// Получаем слово
word = this->word(tmp.at(i));
// Если разрешено выводить системные токены или это нормальные слова
if(nwrd || ((word.front() != L'<') && (word.back() != L'>'))){
// Если это первое слово
if(i == 1) word.setUppers(1);
// Если это последнее слово
else if(i == (tmp.size() - 1)) word.setUppers(uppers);
// Формируем строку
result.append(word.wreal());
// Добавляем разделитель
result.append(L" ");
}
}
// Если же сборка первой n-граммы уже выполнена
} else {
// Получаем слово
word = this->word(tmp.back());
// Если разрешено выводить системные токены или это нормальные слова
if(nwrd || ((word.front() != L'<') && (word.back() != L'>'))){
// Устанавливаем регистры слова
word.setUppers(uppers);
// Формируем строку
result.append(word.wreal());
// Добавляем разделитель
result.append(L" ");
}
}
// Выходим из цикла
} else break;
// Увеличиваем смещение
offset1++;
offset2++;
}
// Если строка получена
if(!result.empty()) result.pop_back();
}
// Выводим результат
return result;
}
/**
* ~Alm2 Деструктор
*/
anyks::Alm2::~Alm2() noexcept {
// Очищаем языковую модель
this->clear();
}
| 36.691445 | 183 | 0.663602 | [
"vector"
] |
31275b304d88c31904934afc88ba102c2cad4aa6 | 20,010 | cpp | C++ | qtdeclarative/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdeclarative/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdeclarative/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgdefaultdistancefieldglyphcache_p.h"
#include <QtGui/private/qdistancefield_p.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <QtQml/private/qqmlglobal_p.h>
#include <QtQuick/private/qsgdistancefieldutil_p.h>
#include <qopenglfunctions.h>
#include <qopenglframebufferobject.h>
#include <qmath.h>
#if !defined(QT_OPENGL_ES_2)
#include <QtGui/qopenglfunctions_3_2_core.h>
#endif
QT_BEGIN_NAMESPACE
DEFINE_BOOL_CONFIG_OPTION(qmlUseGlyphCacheWorkaround, QML_USE_GLYPHCACHE_WORKAROUND)
DEFINE_BOOL_CONFIG_OPTION(qsgPreferFullSizeGlyphCacheTextures, QSG_PREFER_FULLSIZE_GLYPHCACHE_TEXTURES)
#if !defined(QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING)
# define QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING 2
#endif
QSGDefaultDistanceFieldGlyphCache::QSGDefaultDistanceFieldGlyphCache(QSGDistanceFieldGlyphCacheManager *man, QOpenGLContext *c, const QRawFont &font)
: QSGDistanceFieldGlyphCache(man, c, font)
, m_maxTextureSize(0)
, m_maxTextureCount(3)
, m_blitProgram(0)
, m_blitBuffer(QOpenGLBuffer::VertexBuffer)
, m_fboGuard(0)
, m_funcs(c->functions())
#if !defined(QT_OPENGL_ES_2)
, m_coreFuncs(0)
#endif
{
m_blitBuffer.create();
m_blitBuffer.bind();
static GLfloat buffer[16] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
m_blitBuffer.allocate(buffer, sizeof(buffer));
m_blitBuffer.release();
m_areaAllocator = new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()));
}
QSGDefaultDistanceFieldGlyphCache::~QSGDefaultDistanceFieldGlyphCache()
{
for (int i = 0; i < m_textures.count(); ++i)
m_funcs->glDeleteTextures(1, &m_textures[i].texture);
if (m_fboGuard != 0)
m_fboGuard->free();
delete m_blitProgram;
delete m_areaAllocator;
}
void QSGDefaultDistanceFieldGlyphCache::requestGlyphs(const QSet<glyph_t> &glyphs)
{
QList<GlyphPosition> glyphPositions;
QVector<glyph_t> glyphsToRender;
for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
glyph_t glyphIndex = *it;
int padding = QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING;
QRectF boundingRect = glyphData(glyphIndex).boundingRect;
int glyphWidth = qCeil(boundingRect.width()) + distanceFieldRadius() * 2;
int glyphHeight = qCeil(boundingRect.height()) + distanceFieldRadius() * 2;
QSize glyphSize(glyphWidth + padding * 2, glyphHeight + padding * 2);
QRect alloc = m_areaAllocator->allocate(glyphSize);
if (alloc.isNull()) {
// Unallocate unused glyphs until we can allocated the new glyph
while (alloc.isNull() && !m_unusedGlyphs.isEmpty()) {
glyph_t unusedGlyph = *m_unusedGlyphs.constBegin();
TexCoord unusedCoord = glyphTexCoord(unusedGlyph);
QRectF unusedGlyphBoundingRect = glyphData(unusedGlyph).boundingRect;
int unusedGlyphWidth = qCeil(unusedGlyphBoundingRect.width()) + distanceFieldRadius() * 2;
int unusedGlyphHeight = qCeil(unusedGlyphBoundingRect.height()) + distanceFieldRadius() * 2;
m_areaAllocator->deallocate(QRect(unusedCoord.x - padding,
unusedCoord.y - padding,
padding * 2 + unusedGlyphWidth,
padding * 2 + unusedGlyphHeight));
m_unusedGlyphs.remove(unusedGlyph);
m_glyphsTexture.remove(unusedGlyph);
removeGlyph(unusedGlyph);
alloc = m_areaAllocator->allocate(glyphSize);
}
// Not enough space left for this glyph... skip to the next one
if (alloc.isNull())
continue;
}
TextureInfo *tex = textureInfo(alloc.y() / maxTextureSize());
alloc = QRect(alloc.x(), alloc.y() % maxTextureSize(), alloc.width(), alloc.height());
tex->allocatedArea |= alloc;
Q_ASSERT(tex->padding == padding || tex->padding < 0);
tex->padding = padding;
GlyphPosition p;
p.glyph = glyphIndex;
p.position = alloc.topLeft() + QPoint(padding, padding);
glyphPositions.append(p);
glyphsToRender.append(glyphIndex);
m_glyphsTexture.insert(glyphIndex, tex);
}
setGlyphsPosition(glyphPositions);
markGlyphsToRender(glyphsToRender);
}
void QSGDefaultDistanceFieldGlyphCache::storeGlyphs(const QList<QDistanceField> &glyphs)
{
typedef QHash<TextureInfo *, QVector<glyph_t> > GlyphTextureHash;
typedef GlyphTextureHash::const_iterator GlyphTextureHashConstIt;
GlyphTextureHash glyphTextures;
GLint alignment = 4; // default value
m_funcs->glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
// Distance field data is always tightly packed
m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (int i = 0; i < glyphs.size(); ++i) {
QDistanceField glyph = glyphs.at(i);
glyph_t glyphIndex = glyph.glyph();
TexCoord c = glyphTexCoord(glyphIndex);
TextureInfo *texInfo = m_glyphsTexture.value(glyphIndex);
resizeTexture(texInfo, texInfo->allocatedArea.width(), texInfo->allocatedArea.height());
m_funcs->glBindTexture(GL_TEXTURE_2D, texInfo->texture);
glyphTextures[texInfo].append(glyphIndex);
int padding = texInfo->padding;
int expectedWidth = qCeil(c.width + c.xMargin * 2);
glyph = glyph.copy(-padding, -padding,
expectedWidth + padding * 2, glyph.height() + padding * 2);
if (useTextureResizeWorkaround()) {
uchar *inBits = glyph.scanLine(0);
uchar *outBits = texInfo->image.scanLine(int(c.y) - padding) + int(c.x) - padding;
for (int y = 0; y < glyph.height(); ++y) {
memcpy(outBits, inBits, glyph.width());
inBits += glyph.width();
outBits += texInfo->image.width();
}
}
#if !defined(QT_OPENGL_ES_2)
const GLenum format = isCoreProfile() ? GL_RED : GL_ALPHA;
#else
const GLenum format = GL_ALPHA;
#endif
if (useTextureUploadWorkaround()) {
for (int i = 0; i < glyph.height(); ++i) {
m_funcs->glTexSubImage2D(GL_TEXTURE_2D, 0,
c.x - padding, c.y + i - padding, glyph.width(),1,
format, GL_UNSIGNED_BYTE,
glyph.scanLine(i));
}
} else {
m_funcs->glTexSubImage2D(GL_TEXTURE_2D, 0,
c.x - padding, c.y - padding, glyph.width(), glyph.height(),
format, GL_UNSIGNED_BYTE,
glyph.constBits());
}
}
// restore to previous alignment
m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
for (GlyphTextureHashConstIt i = glyphTextures.constBegin(), cend = glyphTextures.constEnd(); i != cend; ++i) {
Texture t;
t.textureId = i.key()->texture;
t.size = i.key()->size;
setGlyphsTexture(i.value(), t);
}
}
void QSGDefaultDistanceFieldGlyphCache::referenceGlyphs(const QSet<glyph_t> &glyphs)
{
m_unusedGlyphs -= glyphs;
}
void QSGDefaultDistanceFieldGlyphCache::releaseGlyphs(const QSet<glyph_t> &glyphs)
{
m_unusedGlyphs += glyphs;
}
void QSGDefaultDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo, int width, int height)
{
if (useTextureResizeWorkaround() && texInfo->image.isNull())
texInfo->image = QDistanceField(width, height);
while (m_funcs->glGetError() != GL_NO_ERROR) { }
m_funcs->glGenTextures(1, &texInfo->texture);
m_funcs->glBindTexture(GL_TEXTURE_2D, texInfo->texture);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#if !defined(QT_OPENGL_ES_2)
if (!QOpenGLContext::currentContext()->isOpenGLES())
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
const GLint internalFormat = isCoreProfile() ? GL_R8 : GL_ALPHA;
const GLenum format = isCoreProfile() ? GL_RED : GL_ALPHA;
#else
const GLint internalFormat = GL_ALPHA;
const GLenum format = GL_ALPHA;
#endif
QByteArray zeroBuf(width * height, 0);
m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, zeroBuf.constData());
texInfo->size = QSize(width, height);
GLuint error = m_funcs->glGetError();
if (error != GL_NO_ERROR) {
m_funcs->glBindTexture(GL_TEXTURE_2D, 0);
m_funcs->glDeleteTextures(1, &texInfo->texture);
texInfo->texture = 0;
}
}
static void freeFramebufferFunc(QOpenGLFunctions *funcs, GLuint id)
{
funcs->glDeleteFramebuffers(1, &id);
}
void QSGDefaultDistanceFieldGlyphCache::resizeTexture(TextureInfo *texInfo, int width, int height)
{
QOpenGLContext *ctx = QOpenGLContext::currentContext();
Q_ASSERT(ctx);
int oldWidth = texInfo->size.width();
int oldHeight = texInfo->size.height();
if (width == oldWidth && height == oldHeight)
return;
GLuint oldTexture = texInfo->texture;
createTexture(texInfo, width, height);
if (!oldTexture)
return;
updateTexture(oldTexture, texInfo->texture, texInfo->size);
#if !defined(QT_OPENGL_ES_2)
if (isCoreProfile() && !useTextureResizeWorkaround()) {
// For an OpenGL Core Profile we can use http://www.opengl.org/wiki/Framebuffer#Blitting
// to efficiently copy the contents of the old texture to the new texture
// TODO: Use ARB_copy_image if available of if we have >=4.3 context
if (!m_coreFuncs) {
m_coreFuncs = ctx->versionFunctions<QOpenGLFunctions_3_2_Core>();
Q_ASSERT(m_coreFuncs);
m_coreFuncs->initializeOpenGLFunctions();
}
// Create a framebuffer object to which we can attach our old and new textures (to
// the first two color buffer attachment points)
if (!m_fboGuard) {
GLuint fbo;
m_coreFuncs->glGenFramebuffers(1, &fbo);
m_fboGuard = new QOpenGLSharedResourceGuard(ctx, fbo, freeFramebufferFunc);
}
// Bind the FBO to both the GL_READ_FRAMEBUFFER? and GL_DRAW_FRAMEBUFFER targets
m_coreFuncs->glBindFramebuffer(GL_FRAMEBUFFER, m_fboGuard->id());
// Bind the old texture to GL_COLOR_ATTACHMENT0
m_coreFuncs->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, oldTexture, 0);
// Bind the new texture to GL_COLOR_ATTACHMENT1
m_coreFuncs->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
GL_TEXTURE_2D, texInfo->texture, 0);
// Set the source and destination buffers
m_coreFuncs->glReadBuffer(GL_COLOR_ATTACHMENT0);
m_coreFuncs->glDrawBuffer(GL_COLOR_ATTACHMENT1);
// Do the blit
m_coreFuncs->glBlitFramebuffer(0, 0, oldWidth, oldHeight,
0, 0, oldWidth, oldHeight,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
// Reset the default framebuffer
QOpenGLFramebufferObject::bindDefault();
return;
} else if (useTextureResizeWorkaround()) {
#else
if (useTextureResizeWorkaround()) {
#endif
GLint alignment = 4; // default value
m_funcs->glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#if !defined(QT_OPENGL_ES_2)
const GLenum format = isCoreProfile() ? GL_RED : GL_ALPHA;
#else
const GLenum format = GL_ALPHA;
#endif
if (useTextureUploadWorkaround()) {
for (int i = 0; i < texInfo->image.height(); ++i) {
m_funcs->glTexSubImage2D(GL_TEXTURE_2D, 0,
0, i, oldWidth, 1,
format, GL_UNSIGNED_BYTE,
texInfo->image.scanLine(i));
}
} else {
m_funcs->glTexSubImage2D(GL_TEXTURE_2D, 0,
0, 0, oldWidth, oldHeight,
format, GL_UNSIGNED_BYTE,
texInfo->image.constBits());
}
m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, alignment); // restore to previous value
texInfo->image = texInfo->image.copy(0, 0, width, height);
m_funcs->glDeleteTextures(1, &oldTexture);
return;
}
if (!m_blitProgram)
createBlitProgram();
Q_ASSERT(m_blitProgram);
if (!m_fboGuard) {
GLuint fbo;
m_funcs->glGenFramebuffers(1, &fbo);
m_fboGuard = new QOpenGLSharedResourceGuard(ctx, fbo, freeFramebufferFunc);
}
m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, m_fboGuard->id());
GLuint tmp_texture;
m_funcs->glGenTextures(1, &tmp_texture);
m_funcs->glBindTexture(GL_TEXTURE_2D, tmp_texture);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#if !defined(QT_OPENGL_ES_2)
if (!ctx->isOpenGLES())
m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
#endif
m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,
GL_RGBA, GL_UNSIGNED_BYTE, NULL);
m_funcs->glBindTexture(GL_TEXTURE_2D, 0);
m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, tmp_texture, 0);
m_funcs->glActiveTexture(GL_TEXTURE0);
m_funcs->glBindTexture(GL_TEXTURE_2D, oldTexture);
// save current render states
GLboolean stencilTestEnabled;
GLboolean depthTestEnabled;
GLboolean scissorTestEnabled;
GLboolean blendEnabled;
GLint viewport[4];
GLint oldProgram;
m_funcs->glGetBooleanv(GL_STENCIL_TEST, &stencilTestEnabled);
m_funcs->glGetBooleanv(GL_DEPTH_TEST, &depthTestEnabled);
m_funcs->glGetBooleanv(GL_SCISSOR_TEST, &scissorTestEnabled);
m_funcs->glGetBooleanv(GL_BLEND, &blendEnabled);
m_funcs->glGetIntegerv(GL_VIEWPORT, &viewport[0]);
m_funcs->glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgram);
m_funcs->glDisable(GL_STENCIL_TEST);
m_funcs->glDisable(GL_DEPTH_TEST);
m_funcs->glDisable(GL_SCISSOR_TEST);
m_funcs->glDisable(GL_BLEND);
m_funcs->glViewport(0, 0, oldWidth, oldHeight);
const bool vaoInit = m_vao.isCreated();
if (isCoreProfile()) {
if ( !vaoInit )
m_vao.create();
m_vao.bind();
}
m_blitProgram->bind();
if (!vaoInit || !isCoreProfile()) {
m_blitBuffer.bind();
m_blitProgram->enableAttributeArray(int(QT_VERTEX_COORDS_ATTR));
m_blitProgram->enableAttributeArray(int(QT_TEXTURE_COORDS_ATTR));
m_blitProgram->setAttributeBuffer(int(QT_VERTEX_COORDS_ATTR), GL_FLOAT, 0, 2);
m_blitProgram->setAttributeBuffer(int(QT_TEXTURE_COORDS_ATTR), GL_FLOAT, 32, 2);
}
m_blitProgram->disableAttributeArray(int(QT_OPACITY_ATTR));
m_blitProgram->setUniformValue("imageTexture", GLuint(0));
m_funcs->glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
m_funcs->glBindTexture(GL_TEXTURE_2D, texInfo->texture);
if (useTextureUploadWorkaround()) {
for (int i = 0; i < oldHeight; ++i)
m_funcs->glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, 0, i, oldWidth, 1);
} else {
m_funcs->glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);
}
m_funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER, 0);
m_funcs->glDeleteTextures(1, &tmp_texture);
m_funcs->glDeleteTextures(1, &oldTexture);
QOpenGLFramebufferObject::bindDefault();
// restore render states
if (stencilTestEnabled)
m_funcs->glEnable(GL_STENCIL_TEST);
if (depthTestEnabled)
m_funcs->glEnable(GL_DEPTH_TEST);
if (scissorTestEnabled)
m_funcs->glEnable(GL_SCISSOR_TEST);
if (blendEnabled)
m_funcs->glEnable(GL_BLEND);
m_funcs->glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
m_funcs->glUseProgram(oldProgram);
m_blitProgram->disableAttributeArray(int(QT_VERTEX_COORDS_ATTR));
m_blitProgram->disableAttributeArray(int(QT_TEXTURE_COORDS_ATTR));
if (isCoreProfile())
m_vao.release();
}
bool QSGDefaultDistanceFieldGlyphCache::useTextureResizeWorkaround() const
{
static bool set = false;
static bool useWorkaround = false;
if (!set) {
QOpenGLContextPrivate *ctx_p = static_cast<QOpenGLContextPrivate *>(QOpenGLContextPrivate::get(QOpenGLContext::currentContext()));
useWorkaround = ctx_p->workaround_brokenFBOReadBack
|| qmlUseGlyphCacheWorkaround(); // on some hardware the workaround is faster (see QTBUG-29264)
set = true;
}
return useWorkaround;
}
bool QSGDefaultDistanceFieldGlyphCache::useTextureUploadWorkaround() const
{
static bool set = false;
static bool useWorkaround = false;
if (!set) {
useWorkaround = qstrcmp(reinterpret_cast<const char*>(m_funcs->glGetString(GL_RENDERER)),
"Mali-400 MP") == 0;
set = true;
}
return useWorkaround;
}
bool QSGDefaultDistanceFieldGlyphCache::createFullSizeTextures() const
{
return qsgPreferFullSizeGlyphCacheTextures() && glyphCount() > QT_DISTANCEFIELD_HIGHGLYPHCOUNT;
}
int QSGDefaultDistanceFieldGlyphCache::maxTextureSize() const
{
if (!m_maxTextureSize)
m_funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize);
return m_maxTextureSize;
}
QT_END_NAMESPACE
| 38.77907 | 149 | 0.65907 | [
"render",
"object"
] |
31281c65d0d7f80be65b3b77b31c9b7411291b72 | 2,491 | cpp | C++ | src/Mesh.cpp | jonixis/Crest | dc2397775262ff4edfba7354398917a5070586b4 | [
"MIT"
] | null | null | null | src/Mesh.cpp | jonixis/Crest | dc2397775262ff4edfba7354398917a5070586b4 | [
"MIT"
] | null | null | null | src/Mesh.cpp | jonixis/Crest | dc2397775262ff4edfba7354398917a5070586b4 | [
"MIT"
] | null | null | null | #include "Mesh.h"
#include <iostream>
#include <memory>
#include "Renderer.h"
Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices) : m_vertices(vertices),
m_indices(indices) {
init();
}
Mesh::~Mesh() {
}
void Mesh::init() {
m_VAO = std::make_unique<VertexArray>();
m_VBO = std::make_unique<VertexBuffer>(m_vertices.data(), m_vertices.size() * sizeof(Vertex));
m_VAO->addBuffer(*m_VBO);
m_IBO = std::make_unique<IndexBuffer>(m_indices.data(), m_indices.size());
if (!m_material)
m_material = std::make_shared<Material>();
}
void Mesh::addVertex(const Vertex &vertex) {
m_vertices.push_back(vertex);
}
void Mesh::addIndex(const unsigned int index) {
m_indices.push_back(index);
}
void Mesh::setMaterial(const std::shared_ptr<Material> material) {
m_material = material;
}
void Mesh::draw(const std::shared_ptr<Shader>& shader, bool useMaterial) const {
if (!m_VAO || !m_IBO) {
std::cout << "Initialize model before drawing!" << std::endl;
exit(1);
}
if (useMaterial) {
if (m_material->diffuseTexture) {
m_material->diffuseTexture->bind(0);
shader->setUniform1i("u_material.map_kd", 0);
shader->setUniform1i("u_material.hasDiffuseTex", 1);
} else {
shader->setUniform1i("u_material.hasDiffuseTex", 0);
}
if (m_material->specularTexture) {
m_material->specularTexture->bind(1);
shader->setUniform1i("u_material.map_ks", 1);
shader->setUniform1i("u_material.hasSpecularTex", 1);
} else {
shader->setUniform1i("u_material.hasSpecularTex", 0);
}
if (m_material->normalTexture) {
m_material->normalTexture->bind(2);
shader->setUniform1i("u_material.map_norm", 2);
shader->setUniform1i("u_material.hasNormalTex", 1);
} else {
shader->setUniform1i("u_material.hasNormalTex", 0);
}
shader->setUniform3f("u_material.ka", m_material->ka);
shader->setUniform3f("u_material.kd", m_material->kd);
shader->setUniform3f("u_material.ks", m_material->ks);
shader->setUniform1f("u_material.ns", m_material->ns);
}
Renderer::draw(*m_VAO, *m_IBO, *shader);
}
unsigned int Mesh::getNumOfVertices() const {
return m_vertices.size();
}
| 29.305882 | 113 | 0.607788 | [
"mesh",
"vector",
"model"
] |
312b0d93efdfa4b6a056da6bd13ab5b0f63cd95e | 2,682 | cpp | C++ | almostsorted.cpp | rishavpramanik/hackerrankpers | b452731af65239f152a4578de4a1a20588a94d86 | [
"MIT"
] | 1 | 2021-08-19T21:28:43.000Z | 2021-08-19T21:28:43.000Z | almostsorted.cpp | rishavpramanik/hackerrankpers | b452731af65239f152a4578de4a1a20588a94d86 | [
"MIT"
] | 2 | 2021-09-29T20:02:44.000Z | 2021-09-29T20:07:05.000Z | almostsorted.cpp | rishavpramanik/hackerrankpers | b452731af65239f152a4578de4a1a20588a94d86 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
//Case 1 : Increasing --> Decreasing --> Increasing
pair<bool,pair<int,int> > isCase1(vector<int>arr,int n){
int i = 0;
while(i<n-1 && arr[i]<arr[i+1]){
i++;
}
int peak_loc = i;
while(i<n-1 && arr[i]>arr[i+1]){
i++;
}
int valley_loc = i;
while(i<n-1 && arr[i]<arr[i+1]){
i++;
}
if(i!=n-1)
return make_pair(false,make_pair(-1,-1));
bool res1 = (peak_loc>0) ? arr[valley_loc]>arr[peak_loc-1] : true;
bool res2 = (valley_loc<n-1) ? arr[peak_loc]<arr[valley_loc+1] : true;
return make_pair(res1 && res2,make_pair(peak_loc,valley_loc));
}
pair<bool,pair<int,int> > isCase2(vector<int>arr,int n){
int i = 0;
while(i<n-1 && arr[i]<arr[i+1]){
i++;
}
int peak1_loc = i;
while(i<n-1 && arr[i]>arr[i+1]){
i++;
}
int valley1_loc = i;
while(i<n-1 && arr[i]<arr[i+1]){
i++;
}
int peak2_loc = i;
// if(peak2_loc+1!=n-1)
// return make_pair(false,make_pair(-1,-1));
// int valley2_loc = peak2_loc + 1;
int valley2_loc = peak2_loc + 1;
i+=1;
while(i<n-1 && arr[i]<arr[i+1])
i++;
if(i!=n-1)
return make_pair(false,make_pair(-1,-1));
bool ans1 = (peak1_loc>0) ? (arr[valley2_loc]>arr[peak1_loc-1] && arr[valley2_loc]<arr[valley1_loc]) : true;
bool ans2 = arr[peak1_loc]>arr[peak2_loc];
bool ans3 = valley2_loc+1<n-1 ? arr[peak1_loc]<arr[valley2_loc+1] : true;
// if(ans1&&ans2){
// cout<<"Peak 1 : "<<peak1_loc<<endl;
// cout<<"Valley 1 : "<<valley1_loc<<endl;
// cout<<"Peak 2 : "<<peak2_loc<<endl;
// cout<<"Valley 2 : "<<valley2_loc<<endl;
// }
return make_pair(ans1 && ans2 && ans3,make_pair(peak1_loc,valley2_loc));
}
bool isSorted(vector<int>arr,int n){
for(int i=0;i<n-1;i++){
if(arr[i]>arr[i+1])
return false;
}
return true;
}
// Complete the almostSorted function below.
void almostSorted(vector<int> arr) {
int n = arr.size();
if(isSorted(arr,n)){
cout<<"yes";
return;
}
else if(n==2 && arr[0]>arr[1]){
cout<<"yes"<<endl;
cout<<"swap 1 2";
}
else if(isCase1(arr,n).first){
pair<bool,pair<int,int> >ans = isCase1(arr,n);
if(ans.first){
cout<<"yes"<<endl;
int l = (ans.second).first + 1;
int r = (ans.second).second + 1;
if(r-l==1){
cout<<"swap "<<l<<" "<<r;
}
else{
cout<<"reverse "<<l<<" "<<r;
}
}
}
| 27.090909 | 113 | 0.51305 | [
"vector"
] |
312d9a2360326008f26a2c2918c860c5073b21c0 | 2,713 | cpp | C++ | Dijkstra/d-ary.cpp | AngusRitossa/Heaps | 0658004f4a209387de2fb1490ce0c1ae890b40de | [
"MIT"
] | 4 | 2018-07-10T07:34:25.000Z | 2021-08-20T05:21:11.000Z | Dijkstra/d-ary.cpp | AngusRitossa/Heaps | 0658004f4a209387de2fb1490ce0c1ae890b40de | [
"MIT"
] | null | null | null | Dijkstra/d-ary.cpp | AngusRitossa/Heaps | 0658004f4a209387de2fb1490ce0c1ae890b40de | [
"MIT"
] | null | null | null | // Dijkstra's algorithm implemented with a d-ary heap: O((v + e) log v)
#include <cstdio>
#include <vector>
#include <utility>
#include <queue>
#include <chrono>
using namespace std;
using namespace chrono;
#define D 16
#define MAXN 1000001
typedef long long ll;
struct daryheap
{
ll heap[MAXN];
int node[MAXN];
int at[MAXN];
int upto, sz;
// Auxilary functions
int size()
{
return sz;
}
bool empty()
{
return !sz;
}
ll top()
{
return heap[0];
}
void swap(int a, int b) // Swaps two elements in the heap
{
ll c = heap[a];
heap[a] = heap[b];
heap[b] = c;
c = node[a];
node[a] = node[b];
node[b] = c;
at[node[a]] = a;
at[node[b]] = b;
}
void bubbleup(int a) // Swaps with parents until its in the correct position
{
while (a)
{
int p = (a-1)/D;
if (heap[a] < heap[p]) // Should perform the swap
{
swap(a, p);
a = p;
}
else break; // We are finished
}
}
void bubbledown(int a) // Swaps with children until its in the correct position
{
while (true)
{
ll mn = heap[a];
int mnchild = -1;
for (int i = 1; i <= D; i++)
{
int c = a*D+i;
if (c < sz && heap[c] < mn) // This is the new minimum value
{
mn = heap[c];
mnchild = c;
}
}
if (mnchild == -1) break; // We are done
swap(a, mnchild);
a = mnchild;
}
}
// Main functions
void push(ll val)
{
// Insert as a leaf
heap[sz] = val;
node[sz] = upto;
at[upto++] = sz;
// Bubble up
bubbleup(sz++);
}
void pop()
{
sz--;
// Replace root with last child, bubble down
swap(0, sz);
// Bubble down
bubbledown(0);
}
void decreasekey(int a, ll val)
{
// Update value, bubble up
heap[a] = val;
bubbleup(a);
}
};
int v, e;
vector<pair<int, ll> > adj[MAXN];
daryheap pq;
int main()
{
// Scan in the input
scanf("%d%d", &v, &e);
for (int i = 0; i < e; i++)
{
int a, b;
ll c;
scanf("%d%d%lld", &a, &b, &c);
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
// Start the timer
milliseconds start = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
// Initialise the distance to each node
pq.push(0);
for (int i = 1; i < v; i++)
{
pq.push(1e18);
}
// Run dijkstra
while (!pq.empty())
{
int a = pq.node[0];
ll d = pq.top();
pq.pop();
for (auto b : adj[a])
{
if (d + b.second < pq.heap[pq.at[b.first]])
{
pq.decreasekey(pq.at[b.first], d + b.second);
}
}
}
// Print distance to node n-1;
printf("%lld\n", pq.heap[pq.at[v-1]]);
// End the timer, print the time
milliseconds end = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
ll totaltime = end.count() - start.count();
printf("Time % 6lldms\n", totaltime);
} | 18.086667 | 90 | 0.574272 | [
"vector"
] |
3139d25482b13a142621e7996b9c0f25167dca11 | 25,812 | cxx | C++ | etf/src/TAMWDCArray.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | 1 | 2017-11-23T14:47:47.000Z | 2017-11-23T14:47:47.000Z | etf/src/TAMWDCArray.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | etf/src/TAMWDCArray.cxx | asiarabbit/BINGER | f525a7445be1aa3ac3f8fb235f6097c999f25f2d | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////////
// Data Analysis Code Project for the External Target Facility, HIRFL-CSR, @IMP //
// //
// BINGER/inc/etf/TAMWDCArray.cxx //
// TAMWDCArray.cxx -- source file for class TAMWDCArray //
// Introduction: MWDC array class, implementing pattern recognition and 3-D //
// tracking through track projection matching. //
// //
// Author: SUN Yazhou, asia.rabbit@163.com. //
// Created: 2017/10/7. //
// Last modified: 2018/9/6, SUN Yazhou. //
// //
// //
// Copyright (C) 2017-2018, SUN Yazhou. //
// All rights reserved. //
///////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>
#include "TH1F.h" // ROOT include
#include "TAMWDCArray.h"
#include "TACtrlPara.h"
#include "TAUIDParser.h"
#include "TATrack.h"
#include "TAPopMsg.h"
#include "tTrack.h"
#include "TAAnodePara.h"
#include "TAAnodeData.h"
#include "TAAnode.h"
#include "TADCSFE16.h"
#include "TADCCable.h"
#include "TADCSuperLayer.h"
#include "TAMWDC.h"
#include "TADetectorPara.h"
#include "TAPlaStripPara.h"
#include "TAPlaStrip.h"
#include "TATOFWall.h"
#include "TAChannel.h"
#include "TAMath.h"
#include "TAParaManager.h"
#include "TAGPar.h"
#include "TAUI.h"
#include "tEntry.h"
//#define DEBUG // DEBUG MODE
using std::cout;
using std::endl;
static TACtrlPara *ctrlPara = TACtrlPara::Instance();
const double TAMWDCArray::kPropagationSpeed = 200.; // mm/ns
const double DEGREE = TAMath::DEGREE();
static TAGPar *gp = TAGPar::Instance();
TAMWDCArray::TAMWDCArray(const string &name, const string &title, unsigned uid)
: TAStuff(name, title, uid), TADetUnion(uid), fMWDC{0}, fTOFWall(0), fPlaT0(0){
fPhiAvrg = -9999.;
// would be overwritten later in the derived classes
// using values from TACtrlPara::DsquareThresholdPerDot()
fDsquareThresholdPerDot = 100.;
}
TAMWDCArray::~TAMWDCArray(){
for(TAMWDC *&dc : fMWDC) if(dc){
delete dc;
dc = nullptr;
}
if(fTOFWall){
delete fTOFWall;
fTOFWall = nullptr;
}
for(vector<TATrack *> &trls : fTrackList){
for(TATrack *&tr : trls){
if(tr){
delete tr;
tr = nullptr;
}
} // end for over tracks
trls.clear();
} // end for over vectors
}
void TAMWDCArray::SetDsquareThresholdPerDot(double d2Thre){
if(d2Thre < 0.)
TAPopMsg::Error(GetName().c_str(), "SetDsquareThresholdPerDot: minus input: %f", d2Thre);
fDsquareThresholdPerDot = d2Thre;
}
vector<TATrack *> &TAMWDCArray::GetTrackList(int dcType){
if(dcType < 0 || dcType > 2){
TAPopMsg::Error(GetName().c_str(), "GetTrackList: dcType out of range: dcType: %d", dcType);
}
return fTrackList[dcType];
}
// get MWDC #dcId
TAMWDC *TAMWDCArray::GetMWDC(int dcId) const{
if(dcId < 0 || dcId > 2){
TAPopMsg::Error(GetName().c_str(), "GetMWDC: dcId out of range: dcId: %d", dcId);
}
if(!fMWDC[dcId])
TAPopMsg::Error(GetName().c_str(), "GetMWDC: requested dc pointer is null");
return fMWDC[dcId];
}
TATOFWall *TAMWDCArray::GetTOFWall() const{
if(!fTOFWall){
TAPopMsg::Error(GetName().c_str(), "GetTOFWall: fTOFWall is null.");
}
return fTOFWall;
}
TAPlaStrip *TAMWDCArray::GetPlaT0() const{
if(!fPlaT0) TAPopMsg::Error(GetName().c_str(), "GetPlaT0: requested PlaT0 pointer is null");
return fPlaT0;
}
void TAMWDCArray::SetPlaT0(TAPlaStrip *t0){
if(!t0) TAPopMsg::Error(GetName().c_str(), "SetPlaT0: input t0 is a null pointer");
if(fPlaT0){
TAPopMsg::Warn(GetName().c_str(), "SetPlaT0: fPlaT0 has already been assigned: %s", fPlaT0->GetName().c_str());
}
fPlaT0 = t0;
}
double TAMWDCArray::GetPhiAvrg(){
if(-9999. == fPhiAvrg){
fPhiAvrg = 0.;
for(int i = 3; i--;) fPhiAvrg += GetMWDC(i)->GetDetPara()->GetPhi();
fPhiAvrg /= 3.;
}
return fPhiAvrg;
}
void TAMWDCArray::AssignTracks(vector<tTrack *> &track_ls){ // assign tracks
if(!fTrackList[0].size()) return; // no tracks to assign
int index = TAUI::Instance()->GetEntryList()[0]->index;
int type[6]{}; TAUIDParser::DNS(type, GetUID());
tTrack *ptrack_t = nullptr; // a temporary variable
for(int l = 0; l < 3; l++){ // loop over X-U-V
for(TATrack *x : fTrackList[l]){
// x.SetFitRotationCenter(fMWDC[1]->GetZc(), fMWDC[1]->GetXc()); // DEBUG
// x.SetFitMethod(TATrack::kNormalFit); // DEBUG
ptrack_t = new tTrack;
x->AssignTrack(ptrack_t);
// track type: 1[LR][XUV] <=> 1[01][012]
ptrack_t->type = 100 + (type[0] - 3) * 10 + l;
ptrack_t->index = index;
track_ls.push_back(ptrack_t);
} // end for over tracks
} // end for over l
} // end of funtion AssignTracks
#include "TAMWDCArray/map.cxx" // definition of bool Map(TAMWDC **MWDC, vector<TATrack> &track)
void TAMWDCArray::Map(){ // map the fired channels in one data section once and for all.
// cout << GetName() << endl; // DEBUG
// cout << "GetTOFWall()->GetNFiredStrip(): " << GetTOFWall()->GetNFiredStrip() << endl; getchar(); // DEBUG
if(GetTOFWall()->GetNFiredStrip() <= 0
// && 4 != GetPlaT0()->GetFiredStatus()
// && 3 != GetPlaT0()->GetFiredStatus()
) return; // event filter
Map(fMWDC, fTrackList[0], 0); // X
if(ctrlPara->Is3DTracking()){
Map(fMWDC, fTrackList[1], 1); // U
Map(fMWDC, fTrackList[2], 2); // V
// merge track projections into 3-D tracks by labelling them with 3-D track ids
TrackMerger();
}
} // end of function void Map()
// to see if particle track resolved from UV data is compatible with that from X data.
bool TAMWDCArray::Compatible(double k, double b, double ku, double bu, double kv, double bv, double &k2, double &b2, double *xMiss3D){
const double phi = GetPhiAvrg();
double k1t = TAMath::kUV_X(phi, ku, kv);
double b1t = TAMath::bUV_X(phi, ku, kv, bu, bv);
double z, x, xt;
#ifdef DEBUG
cout << "TAMath::kUV_X(" << phi / DEGREE << ", " << ku << ", " << kv << "): ";
cout << TAMath::kUV_X(phi, ku, kv) << endl; // DEBUG
cout << "ku: " << ku << "\tkv: " << kv << endl; // DEBUG
cout << "bu: " << bu << "\tbv: " << bv << endl; // DEBUG
cout << "phi: " << phi / DEGREE << endl; // DEBUG
cout << "k1: " << k << "\tb1: " << b << endl; // DEBUG
cout << "k1t: " << k1t << "\tb1t: " << b1t << endl; // DEBUG
k2 = TAMath::kUV_Y(phi, ku, kv); // DEBUG
b2 = TAMath::bUV_Y(phi, ku, kv, bu, bv); // DEBUG
cout << "k2: " << k2 << "\tb2: " << b2 << endl; // DEBUG
cout << "Coincidence test begin: \n"; // DEBUG
#endif
bool coincide = true;
for(int i = 0; i < 3; i++){
z = fMWDC[i]->GetDetPara()->GetZ();
xt = k1t*z+b1t; x = k*z+b;
xMiss3D[i] = x-xt;
#ifdef DEBUG
cout << "z: " << z << "\txt: " << xt << "\tx: " << x << endl; // DEBUG
cout << "fabs(x-xt): " << fabs(x-xt) << endl; // DEBUG
#endif
// test coincidence in every MWDC.
if(fabs(x-xt) > ctrlPara->Get3DCoincideWindow()){
coincide = false; // 105: 10.5 DC cells, given all kinds of errors
}
} // end for over i
#ifdef DEBUG
cout << "______________ end of Compatible function _____________" << endl; // DEBUG
getchar(); // DEBUG
#endif
if(!coincide) return false;
k2 = TAMath::kUV_Y(phi, ku, kv);
b2 = TAMath::bUV_Y(phi, ku, kv, bu, bv);
return true;
}
void TAMWDCArray::TrackMerger(){ // assembly projections to 3-D tracks
#ifdef DEBUG
cout << "\033[32;1m" << GetName() << "\033[0m" << endl; // DEBUG
cout << "This is TAMWDCArray::TrackMerger():" << endl; // DEBUG
cout << "x.size(): " << fTrackList[0].size(); cout << "\tu.size(): " << fTrackList[1].size(); // DEBUG
cout << "\tv.size(): " << fTrackList[2].size(); // DEBUG
cout << "____________________________________________" << endl; getchar(); // DEBUG
// for(TATrack *&x : fTrackList[0]) x->Show(); // DEBUG
// for(TATrack *&u : fTrackList[1]) u->Show(); // DEBUG
// for(TATrack *&v : fTrackList[2]) v->Show(); // DEBUG
cout << "____________________________________________" << endl; getchar(); // DEBUG
cout << "\n\n\033[33;1m____________________________________________\n\033[0m"; // DEBUG
getchar(); // DEBUG
#endif
if(fTrackList[0].size() > 0){
((TH1F*)gp->Agent(0))->Fill(fTrackList[1].size()); // DEBUG
((TH1F*)gp->Agent(1))->Fill(fTrackList[2].size()); // DEBUG
}
if(fTrackList[0].size() <= 0 || // X tracks are indispensable.
// no U or V tracks are found, no 3D tracks would be matched
0 == fTrackList[1].size() || 0 == fTrackList[2].size()){
fTrackList[1].clear();
fTrackList[2].clear();
fN3DTrk = 0;
return;
} // end if
bool BINGO = false; // X, U, V are projections of the same one 3-D straight track.
int id = -1; // 3-D track identifier
double k2, b2;
// initialize TATrack member variable -- marked.
// marked == true indicates that the track projection has found its mother 3-D track already.
for(TATrack *&x : fTrackList[0]) x->marked = false;
for(TATrack *&u : fTrackList[1]) u->marked = false;
for(TATrack *&v : fTrackList[2]) v->marked = false;
for(unsigned i = 0; i < fTrackList[0].size(); i++){ // loop over track X
TATrack *&x = fTrackList[0][i];
bool isMatched = false; // whether the current X track finds its companies.
// cout << "x.marked: " << x.marked << endl; getchar(); // DEBUG
for(unsigned j = 0; j < fTrackList[1].size(); j++){ // loop over track U
TATrack *&u = fTrackList[1][j];
// u.Show(); // DEBUG
// cout << "u.marked: " << u.marked << endl; getchar(); // DEBUG
int id0 = id + 1; if(isMatched) id0 = id; // the current 3D track id
// One projection cannot be matched with multiple 3-D tracks
if(u->Get3DId() != -1 && u->Get3DId() < id0) continue; // owned by previous X-tracks
for(unsigned k = 0; k < fTrackList[2].size(); k++){ // loop over track V
TATrack *&v = fTrackList[2][k];
// v->Show(); // DEBUG
// cout << "v->marked: " << v->marked << endl; getchar(); // DEBUG
// One projection cannot be matched with multiple 3-D tracks
if(v->Get3DId() != -1 && v->Get3DId() < id0) continue; // owned by previous X-tracks
double xMiss3D[3]{};
BINGO = Compatible(x->GetSlope(), x->GetIntercept(), u->GetSlope(), u->GetIntercept(), v->GetSlope(), v->GetIntercept(), k2, b2, xMiss3D);
if(BINGO){
// make use of the TOF information of X track projection //
const double TOF = x->GetTOF();
const double firedStripId = x->GetFiredStripId();
const double nStripStray = x->GetNStripStray();
double tu[6] = {-9999., -9999., -9999., -9999., -9999., -9999.};
double ru[6] = {-9999., -9999., -9999., -9999., -9999., -9999.};
double tv[6] = {-9999., -9999., -9999., -9999., -9999., -9999.};
double rv[6] = {-9999., -9999., -9999., -9999., -9999., -9999.};
// weight for weighted addition of chi to chi2
double weightU[6] = {1., 1., 1., 1., 1., 1.};
double weightV[6] = {1., 1., 1., 1., 1., 1.};
int nuU[6] = {-1, -1, -1, -1, -1, -1};
int nuV[6] = {-1, -1, -1, -1, -1, -1};
u->GetNu(nuU); v->GetNu(nuV);
for(int l = 0; l < 6; l++){
if(-1 != nuU[l]){
TAAnode *ano = fMWDC[l/2]->GetAnode(1, l%2+1, nuU[l]);
ano->GetAnodeData()->SetTOF(TOF);
tu[l] = ano->GetDriftTime(weightU[l]);
// rough correction for time of flight from DC to TOF wall
tu[l] += ctrlPara->T_tofDCtoTOFW(ano->GetUID()) - ctrlPara->T_wireMean(ano->GetUID());
ru[l] = ano->GetDriftDistance(tu[l], u->GetSlope());
} // end if
if(-1 != nuV[l]){
TAAnode *ano = fMWDC[l/2]->GetAnode(2, l%2+1, nuV[l]);
ano->GetAnodeData()->SetTOF(TOF);
tv[l] = ano->GetDriftTime(weightV[l]);
// rough correction for time of flight from DC to TOF wall
tv[l] += ctrlPara->T_tofDCtoTOFW(ano->GetUID()) - ctrlPara->T_wireMean(ano->GetUID());
rv[l] = ano->GetDriftDistance(tv[l], v->GetSlope());
} // end if
} // end for over i
if(TOF != u->GetTOF()){ // so that TOF would be assigned or altered only if their owner X-track is changed
// which would save Fit() invocation for one time
u->SetTOF(TOF, firedStripId, nStripStray);
u->SetDriftTime(tu, weightU); u->SetDriftDistance(ru);
}
if(TOF != v->GetTOF()){
v->SetTOF(TOF, firedStripId, nStripStray);
v->SetDriftTime(tv, weightV); v->SetDriftDistance(rv);
}
// check the validity of U and V tracks
short badTrk = 0;
for(double tt : tu) if(-9999. != tt && !ctrlPara->TimeThre(tt)) { badTrk = 1; break; }
for(double tt : tv) if(-9999. != tt && !ctrlPara->TimeThre(tt)) { badTrk = 2; break; }
#ifdef DEBUG
u->Show(); // DEBUG
v->Show(); // DEBUG
cout << "u->GetChi(): " << u->GetChi() << endl; // DEBUG
cout << "v->GetChi(): " << v->GetChi() << endl; // DEBUG
cout << "ctrlPara->ChiThre(): " << ctrlPara->ChiThre() << endl; // DEBUG
cout << "badTrk: " << badTrk << endl; getchar(); // DEBUG
if(badTrk) continue; // nasty combination
#endif
if(fabs(u->GetChi()) > 1.5 * ctrlPara->ChiThre()) break; // nasty combination, break to next U track
if(fabs(v->GetChi()) > 1.5 * ctrlPara->ChiThre()) continue; // nasty combination, skip the current V track
double chi[6]{};
u->GetChi(chi);
for(double cc : chi)
if(-9999. != cc && fabs(cc) > 1.5 * ctrlPara->ChiThrePD()){ badTrk = 3; break; }
v->GetChi(chi);
for(double cc : chi)
if(-9999. != cc && fabs(cc) > 1.5 * ctrlPara->ChiThrePD()){ badTrk = 4; break; }
#ifdef DEBUG
cout << "badTrk: " << badTrk << endl; getchar(); // DEBUG
#endif
if(badTrk) continue; // nasty combination
if(!isMatched){ id++; isMatched = true; }
x->Set3DId(id); x->marked = true;
u->Set3DId(id); u->marked = true;
v->Set3DId(id); v->marked = true;
memcpy(x->fXMiss3D, xMiss3D, sizeof(xMiss3D));
memcpy(u->fXMiss3D, xMiss3D, sizeof(xMiss3D));
memcpy(v->fXMiss3D, xMiss3D, sizeof(xMiss3D));
// cout << "ultimately, u and v:" << endl; // DEBUG
// u->Show(); v->Show(); // DEBUG
#ifdef DEBUG
// // // // // // // // // // // // // // // // // // //
cout << "x3DMiss: " << x->fXMiss3D[0] << " "; // DEBUG
cout << x->fXMiss3D[1] << " " << x->fXMiss3D[2] << endl; // DEBUG
cout << "k1: " << x->GetSlope(); // DEBUG
cout << "\tb1: " << x->GetIntercept() << endl; // DEBUG
cout << "k2: " << k2 << "\tb2: " << b2; // DEBUG
cout << "\tid: " << id << endl; // DEBUG
// Compatible(x->GetSlope(), x->GetIntercept(), u->GetSlope(), u->GetIntercept(), v->GetSlope(), v->GetIntercept(), k2, b2, xMiss3D);
// x->Show(); u->Show(); v->Show(); getchar(); // DEBUG
#endif
} // end if
} // end of loop over track v
} // end of loop over track u
} // end of loop over track x
// clean eliminated tracks
cleanUp(fTrackList[1], id + 1);
cleanUp(fTrackList[2], id + 1);
#ifdef DEBUG
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl; // DEBUG
cout << "x.size(): " << fTrackList[0].size(); cout << "\tu.size(): " << fTrackList[1].size(); // DEBUG
cout << "\tv.size(): " << fTrackList[2].size(); // DEBUG
cout << "\n\033[35;3;1;4m3DId of X tracks\033[0m\n";
for(TATrack *x : fTrackList[0]) cout << x->Get3DId() << " "; // DEBUG
for(TATrack *x : fTrackList[0]) x->Show(); // DEBUG
for(TATrack *x : fTrackList[1]) x->Show(); // DEBUG
for(TATrack *x : fTrackList[2]) x->Show(); // DEBUG
cout << "____________________________________________" << endl; getchar(); // DEBUG
#endif
// for(TATrack &x : fTrackList[0]) x.Show(); // DEBUG
// number of 3D tracks in the data section; used for global 3DTrk identification
fN3DTrk = id + 1;
} // end of function TrackFilter().
/// select the best U and V track according to compare(), and clean up unmatched tracks. ///
// n: number of 3D tracks
// because multiple U and V tracks could match one X track, the redundant ones are eliminated in this function
void TAMWDCArray::cleanUp(vector<TATrack *> &tr, const int n){
// eliminate inferior tracks for every 3D track
// cout << "n: " << n << endl; // DEBUG
// for(TATrack *x : tr) cout << x->Get3DId() << " "; // DEBUG
for(int i = 0; i < n; i++){
TATrack *tm = nullptr; // the optimal track
// cout << "\ni: " << i << endl; getchar(); // DEBUG
const int ntrk = tr.size();
for(int j = 0; j < ntrk; j++){
if(tr[j]->Get3DId() != i) continue; // tracks with 3Did == -1 would be eliminated later
if(!tm) tm = tr[j];
TATrack *tt = tr[j];
// cout << "tm: " << tm << "\ttt: " << tt << endl; // DEBUG
if(tt != tm){
const int overlap = compare(tt, tm, 'X', 0);
// cout << "overlap: " << overlap << endl; getchar(); // DEBUG
if(1 == overlap){ // tt is defeated
tt->Set3DId(-1);
}
if(2 == overlap){
tm->Set3DId(-1); // tm is defeated
tm = tt;
}
if(0 == overlap){ // shit happens
if(tt->GetChi() > tm->GetChi()){
tt->Set3DId(-1);
}
else{
tm->Set3DId(-1);
tm = tt;
}
} // end if
} // end if(tt != tm)
} // end for over j
} // end for over i
// cout << "HAHAHAHAHn: " << n << endl; // DEBUG
// for(TATrack *x : tr) cout << x->Get3DId() << ""; // DEBUG
// erase the unmatched and defeated tracks
for(unsigned i = 0; i < tr.size(); i++){
if(-1 == tr[i]->Get3DId()){
delete tr[i]; tr.erase(tr.begin()+i); // erase tr[k]
i--;
} // end if
} // end for over k
// cout << "tr.size(): " << tr.size() << endl; getchar(); // DEBUG
} // end function cleanUp
// drift time correction: time of flight and signal propagation time
// p[4]: [0-3]: [k1, k2, b1, b2]; a[0-1]: [layer0~layer18, nu]
// t = T_DC - T_TOF
void TAMWDCArray::DriftTimeCorrection(double &t, double &r, const double *a, const double *p, int firedStripId, double beta){
if(beta <= 0. || beta > 1.) return; // invalid beta
int LAYER = int(a[0]); // 0~17: nuX, nuU+6, nuV+6
int j = LAYER / 6; // j: 0-1-2: X-U-V
int k = LAYER % 6; // k: DC0X1-DC0X2-DC1X1-DC1X2-DC2X1-DC2X2
int DCid = k / 2; // 0-1-2: DC0-DC1-DC2
int layerType = LAYER % 2 + 1; // 1-2: anodeL1-anode L2
int nu = int(a[1]); // 0~79; anode id in the layer
double Bz = GetMWDC(1)->GetDetPara()->GetZ(); // DC[1]-X1-central z
double B[3] = {0., 0., Bz}, b[3] = {0., 0., 1.}; // B[2] = 0. and b[2] = 1.; preset values.
B[0] = p[2]+B[2]*p[0]; // B[0] = b1+B[2]*k1;
B[1] = p[3]+B[2]*p[1]; // B[1] = b2+B[2]*k2;
b[0] = b[2]*p[0]; // b[0] = b[2]*k1;
b[1] = b[2]*p[1]; // b[1] = b[2]*k2;
double T_wire = GetWirePropagationTime(b, B, nu, j, k);
double T_tof = GetTimeOfFlight(b, B, nu, j, k, firedStripId, beta);
// t = T_DC - T_TOF; T_DC - (T_TOF - T_tof) = T_wire + T_drift
t += T_tof - T_wire; // t + T_tof = T_wire + T_drift => T_drift = t + T_tof - T_wire
double slope = 0.;
if(0 == j) slope = p[0]; // X
else if(1 == j) slope = TAMath::kXY_U(GetPhiAvrg(), p[0], p[1]); // U
else slope = TAMath::kXY_V(GetPhiAvrg(), p[0], p[1]); // V
r = GetMWDC(DCid)->GetAnode(j, layerType, nu)->GetDriftDistance(t, slope);
#ifdef DEBUG
cout << "Bz: " << Bz << endl; // DEBUG
cout << "b[0]: " << b[0] << "\tb[1]: " << b[1] << "\tb[2]: " << b[2] << endl; // DEBUG
cout << "B[0]: " << B[0] << "\tB[1]: " << B[1] << "\tB[2]: " << B[2] << endl; // DEBUG
cout << "p[0]: " << p[0] << "\tp[1]: " << p[1] << "\tp[2]: " << p[2] << "\tp[3]: " << p[3] << endl; // DEBUG
cout << "nu: " << nu << "\tj: " << j << "\tk: " << k << "\tDCid: " << DCid << "\tlayerType: " << layerType << "\tLAYER: " << LAYER << endl; // DEBUG
cout << "firedStripId: " << firedStripId << endl; // DEBUG
cout << "j: " << j << "\tk: " << k << endl; // DEBUG
cout << "T_wire: " << T_wire << "\tT_tof: " << T_tof << endl; // DEBUG
cout << "t: " << t << "\tr: " << r << endl; getchar(); // DEBUG
#endif
} // end of function DriftTimeCorrection
// tool functions for drift time correction j: X-U-V; k: DC0X1-DC0X2-DC1X1-DC1X2-DC2X1-DC2X2
static const double c0 = TAParaManager::Instance()->GetPhysConst("c0");
double TAMWDCArray::GetWirePropagationTime(const double *b, const double *B, int nu, int j, int k){
return GetWirePropagationLength(b, B, nu, j, k) / kPropagationSpeed; // mm/ns
}
double TAMWDCArray::GetTimeOfFlight(const double *b, const double *B, int nu, int j, int k, int firedStripId, double beta){
#ifdef DEBUG
TAPopMsg::Debug(GetName().c_str(), "GetDistanceOfFlight(b, B, nu, j, k, firedStripId): %f\t(beta*c0): %f", GetDistanceOfFlight(b, B, nu, j, k, firedStripId), (beta*c0)); // DEBUG
#endif
return GetDistanceOfFlight(b, B, nu, j, k, firedStripId) / (beta*c0);
}
double TAMWDCArray::GetWirePropagationLength(const double *b, const double *B, int nu, int j, int k){
if(j < 0 && j > 2){
TAPopMsg::Error(GetName().c_str(), "GetWirePropagationLength: Input j (X-U-V) is abnormal, j: %d", j);
}
if(k < 0 && k > 5){
TAPopMsg::Error(GetName().c_str(), "GetWirePropagationLength: Input k (0-5, anode layer) is abnormal, k: %d", k);
}
const TAMWDC *dc = GetMWDC(k/2);
const TAAnode *ano = dc->GetAnode(j, k%2+1, nu);
double p0[3]{}, p1[3]{}; // p0: the hit point on the anode; p1: anode center position
double ag[3]{}; ((TAAnodePara*)ano->GetPara())->GetGlobalDirection(ag); // global direction
ano->GetAnodePara()->GetGlobalCenter(p1);
TAMath::GetHitPoint(b, B, ag, p1, p0);
p0[1] -= dc->GetDetPara()->GetY(); // p0[1] now is roughly in the detector-local coordinate system
#ifdef DEBUG
cout << "The calculated hit point in the anode: " << endl; // DEBUG
cout << "p0[0]: " << p0[0] << "\tp0[1]: " << p0[1] << "\tp0[2]: " << p0[2] << endl; // DEBUG
cout << "p1[0]: " << p1[0] << "\tp1[1]: " << p1[1] << "\tp1[2]: " << p1[2] << endl; // DEBUG
cout << "ag[0]: " << ag[0] << "\tag[1]: " << ag[1] << "\tag[2]: " << ag[2] << endl; // DEBUG
getchar(); // DEBUG
#endif
// type[2]: XUV; type[3]: cable id
int type[6]{}; TAUIDParser::DNS(type, ano->GetUID());
double theta = 0.; // wire-vertical angle
if(0 != j) theta = 30. * DEGREE; // U V
double FEE_Y = 303.; // Y position of FEE, in detector-local coordinate system
if(3 == type[0] && 2 == k/2) FEE_Y = 253.; // LDC2
if(3 == type[0] && 2 == k/2){
if(1 == j && (type[3] <= 5 && type[3] >= 4)) FEE_Y *= -1.; // U, the last two cable
if(2 == j && (type[3] <= 1 && type[3] >= 0)) FEE_Y *= -1.; // V, the first two cable
}
else{
if(1 == j && (type[3] <= 4 && type[3] >= 3)) FEE_Y *= -1.; // U, the last two cable
if(2 == j && (type[3] <= 1 && type[3] >= 0)) FEE_Y *= -1.; // V, the first two cable
}
double dd = fabs(p0[1] - FEE_Y) / cos(theta);
#ifdef DEBUG
cout << "TAMWDCArray::GetWirePropagationLength(): " << dd << endl; getchar(); // DEBUG
#endif
return dd;
} // end of function GetWirePropagationLength
double TAMWDCArray::GetDistanceOfFlight(const double *b, const double *B, int nu, int j, int k, int firedStripId){
if(j < 0 && j > 2){
TAPopMsg::Error(GetName().c_str(), "GetWirePropagationLength: Input j (X-U-V) is abnormal, j: %d", j);
}
if(k < 0 && k > 5){
TAPopMsg::Error(GetName().c_str(), "GetWirePropagationLength: Input k (0-5, anode layer) is abnormal, k: %d", k);
}
const TAMWDC *dc = GetMWDC(k/2);
const TAAnode *ano = dc->GetAnode(j, k%2+1, nu);
// p0: the hit point on the anode; p1: anode center position
double p0[3], p1[3], p2[3]; // p2: fired strip projection
double ag[3]; ((TAAnodePara*)ano->GetPara())->GetGlobalDirection(ag);
((TAAnodePara*)ano->GetPara())->GetGlobalCenter(p1);
TAMath::GetHitPoint(b, B, ag, p1, p0);
// Get the z and x coordinate of the fired strip
GetTOFWall()->GetStrip(firedStripId)->GetStripPara()->GetGlobalProjection(p2);
p2[1] = B[1] + b[1] * (p2[2]-B[2])/b[2];
// more accurate x, calculated from the track function
p2[0] = B[0] + b[0] * (p2[2]-B[2])/b[2];
double dd = TAMath::L(p0, p2, 3);
#ifdef DEBUG
cout << "TAMWDCArray::GetDistanceOfFlight(): " << dd << endl; getchar(); // DEBUG
#endif
return dd;
} // end of function GetDistanceOfFlight
void TAMWDCArray::Initialize(){
for(int i = 0; i < 3; i++){
if(fMWDC[i]) fMWDC[i]->Initialize();
}
fN3DTrk = 0;
if(fTOFWall) fTOFWall->Initialize();
for(vector<TATrack *> &trls : fTrackList){
for(TATrack *&tr : trls){
if(tr){
delete tr;
tr = nullptr;
}
} // end for over tracks
trls.clear();
} // end for over vectors
} // end of function Initialize
// get the channel that belongs to this and has the specified uid
TAStuff *TAMWDCArray::GetChannel(unsigned uid) const{
if(uid > 0x7FFFF) return nullptr; // not a uid belonging to this class (only 19 bits)
int type[6]{}; TAUIDParser::DNS(type, uid); // parse input uid
int TYPE[6]{}; TAUIDParser::DNS(TYPE, GetUID()); // parse uid of this
if(type[0] == TYPE[0]){ // belongs to this object
if(type[1] < 3){ // MWDCs
return
GetMWDC(type[1])->GetSLayer(type[2])->GetCable(type[3])->GetSFE16(type[4])->GetAnode(type[5]);
}
else if(3 == type[1]){ // TOFWall
TAPlaStrip *str = GetTOFWall()->GetStrip(type[2]);
switch(type[3]){
case 0: return str->GetUV();
case 1: return str->GetUH();
case 2: return str->GetDV();
case 3: return str->GetDH();
default: return nullptr;
} // end switch
}
} // end if uid belongs to this object
return nullptr;
}
// display the detector information
void TAMWDCArray::Info() const{
if(!TAPopMsg::IsVerbose()) return;
for(int i = 0; i < 3; i++){
GetMWDC(i)->Info();
cout << "----------------------------------------------------------\n";
}
GetTOFWall()->Info();
cout << "\n\033[1m______________________________________________________________\033[0m\n\n";
}
// a method dedicated for TAVisual::Fill()
void TAMWDCArray::FillTrack(TGraph *gTrack, TGraph *gTrack_R) const{
if(!gTrack || !gTrack_R)
TAPopMsg::Error(GetName().c_str(), "FillTrack: input TGraph pointer is null");
for(TATrack *t : fTrackList[0]) t->FillTrack(gTrack, gTrack_R);
}
| 42.176471 | 179 | 0.585619 | [
"object",
"vector",
"3d"
] |
31430f113e56b31963b2feaafa6fcef30a91beca | 2,012 | cpp | C++ | Source/BattleRoyale/core/GameMode/BattleRoyale/GameRules/CheckThereIsOnlyOneTeamAliveRule.cpp | homeguatlla/BattleRoyale | 9d68a4a902c9b0052788769ae6b963d65ef060a4 | [
"Unlicense"
] | 2 | 2022-02-11T07:25:49.000Z | 2022-03-14T23:00:28.000Z | Source/BattleRoyale/core/GameMode/BattleRoyale/GameRules/CheckThereIsOnlyOneTeamAliveRule.cpp | homeguatlla/BattleRoyale | 9d68a4a902c9b0052788769ae6b963d65ef060a4 | [
"Unlicense"
] | null | null | null | Source/BattleRoyale/core/GameMode/BattleRoyale/GameRules/CheckThereIsOnlyOneTeamAliveRule.cpp | homeguatlla/BattleRoyale | 9d68a4a902c9b0052788769ae6b963d65ef060a4 | [
"Unlicense"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "CheckThereIsOnlyOneTeamAliveRule.h"
#include "EndOfGameRule.h"
#include "BattleRoyale/BattleRoyale.h"
#include "BattleRoyale/core/GameMode/IGameState.h"
#include "BattleRoyale/core/GameMode/IPlayerState.h"
void CheckThereIsOnlyOneTeamAliveRule::Initialize(UWorld* world, IIGameState* gameState)
{
mWorld = world;
mGameState = gameState;
}
bool CheckThereIsOnlyOneTeamAliveRule::Evaluate()
{
if(mGameState->GetNumPlayers() <= 0)
{
return false;
}
if(!mGameState->AreAllPlayersReplicated())
{
return false;
}
bool thereIsOnlyOneTeamAlive = true;
mTeamIdAlive = -1;
mGameState->PerformActionForEachPlayerState(
[this, &thereIsOnlyOneTeamAlive](const IIPlayerState* playerState)
{
if(playerState->IsAlive())
{
if(mTeamIdAlive >=0 && mTeamIdAlive != playerState->GetTeamId())
{
thereIsOnlyOneTeamAlive = false;
return true; //finish the search
}
else
{
mTeamIdAlive = playerState->GetTeamId();
}
}
return false;//continue searching
});
return thereIsOnlyOneTeamAlive;
}
bool CheckThereIsOnlyOneTeamAliveRule::Execute(std::vector<std::shared_ptr<IGameRule>>& rules) const
{
UE_LOG(LogGameRules, Log, TEXT("GameRules: Executing Rule CheckThereIsOnlyOneTeamAliveRule"));
//TODO es un poco raro que tengamos que decirle al game state quién es el equipo ganador.
//igual lo podría hacer todo el mismo. Aunque luego, la regla igual perdería sentido pues
//no podría hacer muchas cosas operando con el gamestate?
//Set data
mGameState->SetWinnerTeam(mTeamIdAlive);
//remove rules not needed
/*TScriptInterface<IIGameRule> thisRule;
thisRule.SetObject(Cast<UObject>(this));
rules.Remove(thisRule);
*/
rules.clear();
//add new rules
const auto endOfGameRule = std::make_shared<EndOfGameRule>();
endOfGameRule->Initialize(mWorld, mGameState);
rules.push_back(endOfGameRule);
//return true if added/removed rules
return true;
}
| 25.15 | 100 | 0.746521 | [
"vector"
] |
314a34092ca6413fb02f2856944784f481b27a4d | 1,452 | cpp | C++ | aws-cpp-sdk-alexaforbusiness/source/model/ResolveRoomResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-alexaforbusiness/source/model/ResolveRoomResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-alexaforbusiness/source/model/ResolveRoomResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/alexaforbusiness/model/ResolveRoomResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::AlexaForBusiness::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ResolveRoomResult::ResolveRoomResult()
{
}
ResolveRoomResult::ResolveRoomResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ResolveRoomResult& ResolveRoomResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("RoomArn"))
{
m_roomArn = jsonValue.GetString("RoomArn");
}
if(jsonValue.ValueExists("RoomName"))
{
m_roomName = jsonValue.GetString("RoomName");
}
if(jsonValue.ValueExists("RoomSkillParameters"))
{
Array<JsonView> roomSkillParametersJsonList = jsonValue.GetArray("RoomSkillParameters");
for(unsigned roomSkillParametersIndex = 0; roomSkillParametersIndex < roomSkillParametersJsonList.GetLength(); ++roomSkillParametersIndex)
{
m_roomSkillParameters.push_back(roomSkillParametersJsonList[roomSkillParametersIndex].AsObject());
}
}
return *this;
}
| 25.928571 | 142 | 0.759642 | [
"model"
] |
314d6baa8f90689567eb68401772ee9d20e2f7a5 | 73,121 | cpp | C++ | lib/scipoptsuite-5.0.1/ug/src/ug_scip/scipParaInitiator.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | lib/scipoptsuite-5.0.1/ug/src/ug_scip/scipParaInitiator.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | lib/scipoptsuite-5.0.1/ug/src/ug_scip/scipParaInitiator.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and software framework */
/* UG --- Ubquity Generator Framework */
/* */
/* Copyright (C) 2002-2017 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* UG is distributed under the terms of the ZIB Academic Licence. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with UG; see the file COPYING. If not email to scip@zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file scipParaInitiator.cpp
* @brief ParaInitiator extension for SCIP solver.
* @author Yuji Shinano
*
*
*
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
// #define UG_SCIP_SOL_FEASIBILITY_CHECK_IN_LC
#include <cctype>
#include <sstream>
#include "scipParaInstance.h"
#include "scipParaInitiator.h"
#include "scipParaObjMessageHdlr.h"
#include "scipParaInitialStat.h"
#ifdef UG_DEBUG_SOLUTION
#include "scip/debug.h"
#endif
// #define UG_SCIP_SOL_FEASIBILITY_CHECK_IN_LC
using namespace UG;
using namespace ParaSCIP;
bool
ScipParaInitiator::addRootNodeCuts(
)
{
SCIP_Longint originalLimitsNodes;
SCIP_CALL_ABORT( SCIPgetLongintParam(scip, "limits/nodes", &originalLimitsNodes) );
SCIP_CALL_ABORT( SCIPsetLongintParam(scip, "limits/nodes", 1) );
if( scipDiffParamSetRoot ) scipDiffParamSetRoot->setParametersInScip(scip);
if( paraParams->getRealParamValue(UG::TimeLimit) > 0.0 )
{
double timeRemains = paraParams->getRealParamValue(UG::TimeLimit) - timer->getElapsedTime();
// SCIP_CALL_ABORT( SCIPsetIntParam(scip,"timing/clocktype", 2) );
SCIP_CALL_ABORT( SCIPsetRealParam(scip,"limits/time", timeRemains) );
}
SCIP_RETCODE ret = SCIPsolve(scip);
if( ret != SCIP_OKAY )
{
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
SCIPprintError(ret, NULL);
#else
SCIPprintError(ret);
#endif
abort();
}
/* reset LC parameter settings */
SCIP_CALL_ABORT( SCIPresetParams(scip) );
if( paraParams->getBoolParamValue(NoPreprocessingInLC) )
{
SCIP_CALL_ABORT( SCIPsetIntParam(scip, "presolving/maxrounds", 0));
}
else
{
if( settingsNameLC )
{
SCIP_CALL_ABORT( SCIPreadParams(scip, settingsNameLC) );
}
}
/* don't catch control+c */
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "misc/catchctrlc", FALSE) );
// Then, solver status should be checked
SCIP_STATUS status = SCIPgetStatus(scip);
if( status == SCIP_STATUS_OPTIMAL ) // when sub-MIP is solved at root node, the solution may not be saved
{
return false;
}
else
{
if( status == SCIP_STATUS_MEMLIMIT )
{
std::cout << "Warning: SCIP was interrupted because the memory limit was reached" << std::endl;
return false;
}
if( paraParams->getRealParamValue(UG::TimeLimit) > 0.0 &&
timer->getElapsedTime() > paraParams->getRealParamValue(UG::TimeLimit) )
{
return true; // pretended to add cuts, anyway, timelimit.
}
}
SCIP_CUT** cuts;
int ncuts;
int ncutsadded;
ncutsadded = 0;
cuts = SCIPgetPoolCuts(scip);
ncuts = SCIPgetNPoolCuts(scip);
for( int c = 0; c < ncuts; ++c )
{
SCIP_ROW* row;
row = SCIPcutGetRow(cuts[c]);
assert(!SCIProwIsLocal(row));
assert(!SCIProwIsModifiable(row));
if( SCIPcutGetAge(cuts[c]) == 0 && SCIProwIsInLP(row) )
{
char name[SCIP_MAXSTRLEN];
SCIP_CONS* cons;
SCIP_COL** cols;
SCIP_VAR** vars;
int ncols;
int i;
/* create a linear constraint out of the cut */
cols = SCIProwGetCols(row);
ncols = SCIProwGetNNonz(row);
SCIP_CALL_ABORT( SCIPallocBufferArray(scip, &vars, ncols) );
for( i = 0; i < ncols; ++i )
vars[i] = SCIPcolGetVar(cols[i]);
(void) SCIPsnprintf(name, SCIP_MAXSTRLEN, "%s_%d", SCIProwGetName(row), SCIPgetNRuns(scip));
SCIP_CALL_ABORT( SCIPcreateConsLinear(scip, &cons, name, ncols, vars, SCIProwGetVals(row),
SCIProwGetLhs(row) - SCIProwGetConstant(row), SCIProwGetRhs(row) - SCIProwGetConstant(row),
TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE) );
SCIP_CALL_ABORT( SCIPaddCons(scip, cons) );
SCIP_CALL_ABORT( SCIPreleaseCons(scip, &cons) );
SCIPfreeBufferArray(scip, &vars);
ncutsadded++;
}
}
// SCIP_CALL_ABORT( SCIPsetLongintParam(scip, "limits/nodes", originalLimitsNodes) );
return true;
}
/** init function */
int
ScipParaInitiator::init(
ParaParamSet *inParaParams,
int argc,
char** argv
)
{
int i;
bool quiet = false;
#ifdef _COMM_PTH
bool noUpgrade = false;
#endif
paraParams = inParaParams;
probname = argv[2];
/********************
* Parse parameters *
********************/
if( std::string(paraParams->getStringParamValue(SolverSettingsForInitialPresolving)) != "" )
{
settingsNameLC = const_cast<char*> (paraParams->getStringParamValue(SolverSettingsForInitialPresolving));
}
if( std::string(paraParams->getStringParamValue(SolverSettingsAtRootNode)) != "" )
{
settingsNameRoot = const_cast<char*> (paraParams->getStringParamValue(SolverSettingsAtRootNode));
}
if( std::string(paraParams->getStringParamValue(SolverSettingsExceptRootNode)) != "" )
{
settingsName = const_cast<char*> (paraParams->getStringParamValue(SolverSettingsExceptRootNode));
}
if( std::string(paraParams->getStringParamValue(SolverSettingsAtRacing)) != "" )
{
racingSettingsName = const_cast<char*> (paraParams->getStringParamValue(SolverSettingsAtRacing));
}
for( i = 3; i < argc; ++i ) /** the first argument is runtime parameter file for ParaSCIP */
/** the second argument is problem file name */
{
if( strcmp(argv[i], "-l") == 0 )
{
i++;
if( i < argc )
logname = argv[i];
else
{
std::cerr << "missing log filename after parameter '-l'" << std::endl;
exit(1);
}
}
else if( strcmp(argv[i], "-q") == 0 )
quiet = true;
else if( strcmp(argv[i], "-s") == 0 )
{
i++;
if( i < argc )
settingsName = argv[i];
else
{
std::cerr << "missing settings filename after parameter '-s'" << std::endl;
exit(1);
}
}
else if( strcmp(argv[i], "-sr") == 0 )
{
i++;
if( i < argc )
settingsNameRoot = argv[i];
else
{
std::cerr << "missing settings filename after parameter '-sr'" << std::endl;
exit(1);
}
}
else if( strcmp(argv[i], "-sl") == 0 )
{
i++;
if( i < argc )
settingsNameLC = argv[i];
else
{
std::cerr << "missing settings filename after parameter '-sl'" << std::endl;
exit(1);
}
}
else if( strcmp(argv[i], "-w") == 0)
{
#ifdef UG_WITH_ZLIB
i++;
if( i < argc )
{
prefixWarm = argv[i];
char nodesFileName[256];
sprintf(nodesFileName,"%s_nodes_LC0.gz",prefixWarm);
checkpointNodesStream.open(nodesFileName, std::ios::in | std::ios::binary);
if( !checkpointNodesStream.good() ){
std::cerr << "ERROR: Opening file `" << nodesFileName << "' failed.\n";
exit(1);
}
}
else
{
std::cerr << "missing settings filename after parameter '-w'" << std::endl;
exit(1);
}
#else
std::cerr << "Cannot work with parameter '-w' compiling without zlib" << std::endl;
exit(1);
#endif
}
else if( strcmp(argv[i], "-racing") == 0 )
{
i++;
if( i < argc )
{
racingSettingsName = argv[i];
}
else
{
std::cerr << "missing settings filename after parameter '-racing'" << std::endl;
exit(1);
}
}
else if ( strcmp(argv[i], "-isol") == 0 )
{
i++;
if( i < argc )
{
isolname = argv[i];
}
else
{
std::cerr << "missing settings filename after parameter '-isol'" << std::endl;
exit(1);
}
}
else if( strcmp(argv[i], "-objlimit") == 0 )
{
i++;
if( i < argc )
{
objlimit = atof(argv[i]);
}
else
{
std::cerr << "missing objective limit after parameter '-objlimit'" << std::endl;
exit(1);
}
}
else if ( strcmp(argv[i], "-sth") == 0 )
{
i++; // just omit this parameter and the following number.
}
else if ( strcmp(argv[i], "-fsol" ) == 0 )
{
i++;
if( i < argc )
{
solutionFileName = argv[i];
}
else
{
std::cerr << "missing solution filename after parameter '-fsol'" << std::endl;
exit(1);
}
}
#ifdef _COMM_PTH
else if ( strcmp(argv[i], "-nou" ) == 0 )
{
noUpgrade = true;
}
#endif
else
{
THROW_LOGICAL_ERROR3("invalid parameter <", argv[i], ">");
}
}
/*********
* Setup *
*********/
/* initialize SCIP */
SCIP_CALL( SCIPcreate(&scip) );
/********************
* Setup clock type *
********************/
SCIP_CALL_ABORT( SCIPsetIntParam(scip,"timing/clocktype", 2) ); // always use wall clock time
if( paraParams->getRealParamValue(UG::TimeLimit) > 0.0 )
{
double timeRemains = paraParams->getRealParamValue(UG::TimeLimit) - timer->getElapsedTime();
SCIP_CALL_ABORT( SCIPsetRealParam(scip,"limits/time", timeRemains) );
}
/*******************
* Install plugins *
*******************/
/* include default SCIP plugins */
SCIP_CALL( SCIPincludeDefaultPlugins(scip) );
/** user include plugins */
includeUserPlugins(scip); // user plugin must set later, since it also sets user parameters
// We should include here
/* initialize finalDual bound */
finalDualBound = SCIPinfinity(scip);
/* output solver version */
printSolverVersion(NULL);
/*************************************************
* set quiet message handler, if it is necessary *
*************************************************/
messagehdlr = NULL;
if( paraParams->getBoolParamValue(Quiet) )
{
SCIP_CALL_ABORT( SCIPcreateObjMessagehdlr(&messagehdlr, new ScipParaObjMessageHdlr(paraComm, NULL, TRUE, FALSE), TRUE) );
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
SCIP_CALL_ABORT( SCIPsetMessagehdlr(messagehdlr) );
#else
SCIP_CALL_ABORT( SCIPsetMessagehdlr(scip, messagehdlr) );
SCIP_CALL_ABORT( SCIPmessagehdlrRelease(&messagehdlr));
#endif
}
else
{
if( logname != NULL || quiet )
{
if( logname != NULL )
{
std::ostringstream os;
os << logname << paraComm->getRank();
logfile = fopen(os.str().c_str(), "a"); // append to log file */
if( logfile == NULL )
{
THROW_LOGICAL_ERROR3("cannot open log file <", logname, "> for writing");
}
}
SCIP_CALL_ABORT( SCIPcreateObjMessagehdlr(&messagehdlr, new ScipParaObjMessageHdlr(paraComm, logfile, quiet, FALSE), TRUE) );
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
SCIP_CALL_ABORT( SCIPsetMessagehdlr(messagehdlr) );
#else
SCIP_CALL_ABORT( SCIPsetMessagehdlr(scip, messagehdlr) );
SCIP_CALL_ABORT( SCIPmessagehdlrRelease(&messagehdlr));
#endif
}
}
if( probname != NULL )
{
/***********************
* Version information *
***********************/
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
SCIPprintVersion(NULL);
#else
SCIPprintVersion(scip, NULL);
#endif
SCIPinfoMessage(scip, NULL, "\n");
/*****************
* Load settings *
*****************/
DEF_SCIP_PARA_COMM( scipParaComm, paraComm );
SCIP *paramScip = 0;
if( !(settingsName == NULL && settingsNameRoot == NULL && settingsNameLC == NULL ) )
{
/* initialize SCIP to get diff params */
SCIP_CALL( SCIPcreate(¶mScip) );
/* include default SCIP plugins */
SCIP_CALL( SCIPincludeDefaultPlugins(paramScip) );
/** user include plugins */
includeUserPlugins(paramScip); // need to install user parameters
}
if( settingsName != NULL )
{
SCIP_CALL( SCIPreadParams(paramScip, settingsName) );
scipDiffParamSet = scipParaComm->createScipDiffParamSet(paramScip);
}
else
{
scipDiffParamSet = scipParaComm->createScipDiffParamSet(scip);
}
if( settingsNameRoot != NULL )
{
SCIP_CALL( SCIPreadParams(scip, settingsNameRoot) );
// SCIP_CALL( SCIPresetParams(paramScip) );
SCIP_CALL( SCIPreadParams(paramScip, settingsNameRoot) );
scipDiffParamSetRoot = scipParaComm->createScipDiffParamSet(paramScip);
// Root settings are used for LC. They should be a part of root process.
// SCIP_CALL( SCIPresetParams(scip) );
}
else
{
scipDiffParamSetRoot = scipParaComm->createScipDiffParamSet(scip);
}
if( settingsNameLC != NULL )
{
// SCIP_CALL( SCIPresetParams(scip) );
SCIP_CALL( SCIPreadParams(scip, settingsNameLC) );
}
if( paramScip )
{
SCIP_CALL_ABORT( SCIPfree(¶mScip) );
paramScip = 0;
}
/**************
* Start SCIP *
**************/
/** user include plugins */
// includeUserPlugins(scip); // need to set user plugins: should be set
// Problem Creation
int retcode = SCIPreadProb(scip, probname, NULL);
if( retcode != SCIP_OKAY )
{
std::cout << "error reading file <" << probname << ">" << std::endl;
SCIP_CALL( SCIPfreeProb(scip) );
exit(1);
}
/* transform the problem */
SCIP_CALL_ABORT( SCIPtransformProb(scip));
/* read initail solution, if it is specified */
if( isolname )
{
// NOTE:
// When CPLEX license file cannot find, SCIPtransformProb(scip) may fail
// SCIP_CALL_ABORT( SCIPreadSol(scip, isolname) );
SCIP_CALL_ABORT( SCIPreadProb(scip, isolname, 0) );
}
/* change problem name */
char *probNameFromFileName;
char *temp = new char[strlen(probname)+1];
(void) strcpy(temp, probname);
SCIPsplitFilename(temp, NULL, &probNameFromFileName, NULL, NULL);
SCIP_CALL_ABORT( SCIPsetProbName(scip, probNameFromFileName));
delete [] temp;
/* presolve problem */
if( paraParams->getBoolParamValue(NoPreprocessingInLC) )
{
if( SCIPfindConshdlr(scip, "pseudoboolean") == NULL || SCIPconshdlrGetNConss(SCIPfindConshdlr(scip, "pseudoboolean")) == 0 ) // this is workaround for a bug.
{
SCIP_CALL_ABORT( SCIPsetIntParam(scip, "presolving/maxrounds", 0) );
std::cout << "No LC presolving is specified." << std::endl;
}
else
{
std::cout << "Default LC presolving (default)." << std::endl;
}
}
else
{
if( settingsNameLC )
{
SCIP_CALL_ABORT( SCIPreadParams(scip, settingsNameLC) );
std::cout << "LC presolving settings file is specified." << std::endl;
}
else
{
// SCIP_CALL_ABORT( SCIPsetPresolving(scip, SCIP_PARAMSETTING_FAST, TRUE) );
std::cout << "Default LC presolving (default)." << std::endl;
}
}
// SCIP_CALL_ABORT( SCIPsetIntParam(scip, "constraints/quadratic/replacebinaryprod", 0));
// SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/nonlinear/reformulate", FALSE));
/* don't catch control+c */
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "misc/catchctrlc", FALSE) );
/* objlimit is specified */
if( EPSLT( objlimit, DBL_MAX, MINEPSILON ) )
{
SCIP_CALL_ABORT( SCIPsetObjlimit(scip, objlimit) );
}
// #ifdef _COMM_PTH
// SCIP_CALL( SCIPsetBoolParam(scip, "misc/catchctrlc", FALSE) );
// #endif
SCIP_Bool originalUpgradeKnapsack;
SCIP_Bool originalUpgradeLogicor;
SCIP_Bool originalUpgradeSetppc;
SCIP_Bool originalUpgradeVarbound;
bool onlyLinearConss = onlyLinearConsHandler();
#ifndef _COMM_PTH
if( onlyLinearConss )
{
std::cout << "** Original problem has only linear constraints" << std::endl;
}
else
{
std::cout << "** Original problem has non-linear constraints" << std::endl;
}
if( paraParams->getIntParamValue(UG::InstanceTransferMethod) != 2 )
{
if( onlyLinearConss )
{
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/knapsack", &originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/logicor", &originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/setppc", &originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/varbound", &originalUpgradeVarbound));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", FALSE));
}
}
#else
if( noUpgrade )
{
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/knapsack", &originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/logicor", &originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/setppc", &originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/varbound", &originalUpgradeVarbound));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", FALSE));
}
#endif
#ifdef UG_DEBUG_SOLUTION
SCIPdebugSolDisable(scip);
#endif
// instance = new PARA_INSTANCE_TYPE(scip, paraParams->getIntParamValue(InstanceTransferMethod));
/** instance needs to be generated befor presolving **/
instance = scipParaComm->createScipParaInstance(scip, paraParams->getIntParamValue(InstanceTransferMethod));
std::ostringstream os;
if( solutionFileName )
{
os << solutionFileName;
}
else
{
os << paraParams->getStringParamValue(SolutionFilePath);
os << instance->getProbName() << ".sol";
}
solutionFile = fopen(os.str().c_str(), "a"); // if solution file exists, append
if( solutionFile == NULL )
{
THROW_LOGICAL_ERROR3("cannot open solution file <", os.str(), "> for writing");
}
SCIP_CALL( SCIPpresolve(scip) );
SCIP_STATUS scipStatus = SCIPgetStatus(scip);
if( scipStatus == SCIP_STATUS_OPTIMAL ||
scipStatus == SCIP_STATUS_INFEASIBLE ) // when sub-MIP is solved at root node, the solution may not be saved
{
solvedAtInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at Init ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
else
{
if( paraParams->getRealParamValue(UG::TimeLimit) > 0.0 &&
timer->getElapsedTime() > paraParams->getRealParamValue(UG::TimeLimit) )
{
solvedAtInit = true;
setFinalSolverStatus(HardTimeLimitIsReached);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at Init ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
else
{
/* adding root node cuts, if necessary */
if( paraParams->getBoolParamValue(UseRootNodeCuts) )
{
if( !addRootNodeCuts() )
{
solvedAtInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at Init ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
else
{
if( paraParams->getRealParamValue(UG::TimeLimit) > 0.0 &&
timer->getElapsedTime() > paraParams->getRealParamValue(UG::TimeLimit) )
{
solvedAtInit = true;
setFinalSolverStatus(HardTimeLimitIsReached);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at Init ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
}
}
}
}
// output presolved instance information
int nNonLinearConsHdlrs = 0;
outputProblemInfo(&nNonLinearConsHdlrs);
#ifndef _COMM_PTH
PARA_COMM_CALL(
paraComm->bcast( &nNonLinearConsHdlrs, 1, ParaINT, 0 )
);
if( nNonLinearConsHdlrs > 0 )
{
paraParams->setIntParamValue(InstanceTransferMethod,2);
}
#endif
std::cout << "** Instance transfer method used: " << paraParams->getIntParamValue(InstanceTransferMethod) << std::endl;
if( SCIPgetNVars(scip) == 0 ) // all variables were fixed in presolve
{
SCIP_CALL( SCIPsolve(scip) );
solvedAtInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at Init ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
/** check if feasible solution is found or not. If it was found, then generate paraSolution */
SCIP_SOL *sol = SCIPgetBestSol(scip);
// std::cout << "solobj = " << SCIPgetSolOrigObj(scip, sol) << ", objlimit = " << SCIPgetObjlimit(scip) << std::endl;
if( sol )
{
if( EPSLT( objlimit, DBL_MAX, MINEPSILON ) )
{
if( ( SCIPgetObjsense(scip) == SCIP_OBJSENSE_MINIMIZE && SCIPgetSolOrigObj(scip, sol) < objlimit ) ||
( SCIPgetObjsense(scip) == SCIP_OBJSENSE_MAXIMIZE && SCIPgetSolOrigObj(scip, sol) > objlimit ) )
{
int nVars = SCIPgetNVars(scip);
SCIP_VAR **vars = SCIPgetVars(scip);
SCIP_Real *vals = new SCIP_Real[nVars];
SCIP_CALL_ABORT( SCIPgetSolVals(scip, sol, nVars, vars, vals) );
solution = scipParaComm->createScipParaSolution(
0,
SCIPgetSolTransObj(scip, sol), // Only this value may be used
nVars,
vars,
vals
);
delete [] vals;
}
else
{
solution = scipParaComm->createScipParaSolution(
0,
( ( objlimit / ( SCIPgetTransObjscale(scip) * SCIPgetObjsense(scip) ) ) - SCIPgetTransObjoffset(scip) ), // Only this value may be used
0,
(SCIP_VAR **)0,
0
);
}
}
else
{
int nVars = SCIPgetNVars(scip);
SCIP_VAR **vars = SCIPgetVars(scip);
SCIP_Real *vals = new SCIP_Real[nVars];
SCIP_CALL_ABORT( SCIPgetSolVals(scip, sol, nVars, vars, vals) );
solution = scipParaComm->createScipParaSolution(
0,
SCIPgetSolTransObj(scip, sol), // Only this value may be used
0,
(SCIP_VAR **)0,
0
);
delete [] vals;
}
}
else
{
if( EPSLT( objlimit, DBL_MAX, MINEPSILON ) )
{
solution = scipParaComm->createScipParaSolution(
0,
( ( objlimit / ( SCIPgetTransObjscale(scip) * SCIPgetObjsense(scip) ) ) - SCIPgetTransObjoffset(scip) ), // Only this value may be used
0,
(SCIP_VAR **)0,
0
);
}
}
// instance = new PARA_INSTANCE_TYPE(scip, paraParams->getIntParamValue(InstanceTransferMethod));
#ifndef _COMM_PTH
/** In ParaSCIP case, instance have to provided for the presolved instance **/
delete instance;
instance = scipParaComm->createScipParaInstance(scip, paraParams->getIntParamValue(InstanceTransferMethod));
#endif
// instance = scipParaComm->createScipParaInstance(scip, paraParams->getIntParamValue(InstanceTransferMethod));
/* for debugging
std::string subcipprefix("presolved_");
std::string subcipfilename;
std::ostringstream oss;
oss << subcipprefix;
oss << instance->getProbName();
subcipfilename = oss.str();
subcipfilename += ".lp";
if( SCIPgetStage(scip) >= SCIP_STAGE_TRANSFORMED )
{
SCIP_CALL_ABORT( SCIPwriteTransProblem(scip, subcipfilename.c_str(), "lp", FALSE) );
}
************************/
#ifndef _COMM_PTH
if( onlyLinearConss && paraParams->getIntParamValue(UG::InstanceTransferMethod) != 2 )
{
// restore original parameters
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", originalUpgradeVarbound));
}
#else
if( noUpgrade )
{
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", originalUpgradeVarbound));
}
#endif
int maxrounds = 0;
SCIP_CALL_ABORT( SCIPgetIntParam(scip, "presolving/maxrounds", &maxrounds));
if( !paraParams->getBoolParamValue(Quiet) && maxrounds != 0 )
{
os << ".trans";
transSolutionFile = fopen(os.str().c_str(), "a"); // if trans. solution file exists, append
if( transSolutionFile == NULL )
{
THROW_LOGICAL_ERROR3("cannot open solution file <", os.str(), "> for writing");
}
}
if( paraParams->getBoolParamValue(UG::OutputPresolvedInstance) )
{
std::ostringstream os2;
os2 << paraParams->getStringParamValue(UG::LogSolvingStatusFilePath);
if( onlyLinearConss )
{
os2 << instance->getProbName() << "_presolved.lp";
}
else
{
os2 << instance->getProbName() << "_presolved.cip";
}
SCIP_CALL_ABORT( SCIPwriteTransProblem(scip, os2.str().c_str(), NULL, FALSE));
}
}
else
{
std::cout << std::endl;
std::cout << "syntax: " << argv[0] << "#solvers ppscip_param_file problem_file_name "
<< "[-l <logfile>] [-q] [-sl <settings>] [-s <settings>] [-sr <root_settings>] [-w <prefix_warm>] [-sth <number>]" << std::endl;
std::cout << " -l <logfile> : copy output into log file" << std::endl;
std::cout << " -q : suppress screen messages" << std::endl;
std::cout << " -sl <settings> : load parameter settings (.set) file for LC presolving" << std::endl;
std::cout << " -s <settings> : load parameter settings (.set) file for solvers" << std::endl;
std::cout << " -sr <root_settings> : load parameter settings (.set) file for root" << std::endl;
std::cout << " -w <prefix_warm> : warm start file prefix ( prefix_warm_nodes.gz and prefix_warm_solution.txt are read )" << std::endl;
std::cout << " -sth <number> : the number of solver threads used(FiberSCIP)" << std::endl;
THROW_LOGICAL_ERROR1("invalid parameter");
}
if( solution )
{
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("");
}
}
return 0;
}
/** reInit function */
int
ScipParaInitiator::reInit(
int nRestartedRacing
)
{
/** save incumbent solution */
char initSolFileName[256];
if( isolname )
{
(void) sprintf(initSolFileName,"%s.%d",isolname, nRestartedRacing);
if( !rename( isolname, initSolFileName ) )
{
std::cout << "Warning: initial solution file name cannot rename: " << isolname << ", " << nRestartedRacing << "'th restarted file." << std::endl;
// perror("cannot rename");
// THROW_LOGICAL_ERROR1("cannot rename solution file");
}
if( !generatedIsolname )
{
(void) sprintf(initSolFileName,"%s", isolname );
generatedIsolname = new char[strlen(initSolFileName)+1];
(void) strcpy(generatedIsolname, initSolFileName);
}
}
else
{
if( !generatedIsolname )
{
(void) sprintf(initSolFileName,"i_%s.sol", instance->getProbName() );
generatedIsolname = new char[strlen(initSolFileName)+1];
(void) strcpy(generatedIsolname, initSolFileName);
}
}
FILE *fp = fopen(generatedIsolname, "w");
if( !fp )
{
std::cout << "Could not open " << generatedIsolname << " file to reinitialize for restart." << std::endl;
abort();
}
assert( SCIPgetBestSol(scip) );
SCIP_CALL_ABORT( SCIPprintBestSol( scip, fp, FALSE) );
(void) fclose(fp);
// Problem Creation
int retcode = SCIPreadProb(scip, probname, NULL);
if( retcode != SCIP_OKAY )
{
std::cout << "error reading file <" << probname << ">" << std::endl;
SCIP_CALL( SCIPfreeProb(scip) );
exit(1);
}
// std::cout << "problem name in initiator ' " << SCIPgetProbName(scip) << std::endl;
SCIP_CALL_ABORT( SCIPtransformProb(scip));
// NOTE:
// When CPLEX license file cannot find, SCIPtransformProb(scip) may fail
SCIP_CALL_ABORT( SCIPreadSol(scip, generatedIsolname) );
/* change problem name */
char *probNameFromFileName;
char *temp = new char[strlen(probname)+1];
(void) strcpy(temp, probname);
SCIPsplitFilename(temp, NULL, &probNameFromFileName, NULL, NULL);
SCIP_CALL_ABORT( SCIPsetProbName(scip, probNameFromFileName));
delete [] temp;
#ifdef _COMM_PTH
SCIP_CALL( SCIPsetBoolParam(scip, "misc/catchctrlc", FALSE) );
#endif
#ifndef _COMM_PTH
SCIP_Bool originalUpgradeKnapsack;
SCIP_Bool originalUpgradeLogicor;
SCIP_Bool originalUpgradeSetppc;
SCIP_Bool originalUpgradeVarbound;
bool onlyLinearConss = onlyLinearConsHandler();
if( onlyLinearConss )
{
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/knapsack", &originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/logicor", &originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/setppc", &originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPgetBoolParam(scip, "constraints/linear/upgrade/varbound", &originalUpgradeVarbound));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", FALSE));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", FALSE));
}
#endif
SCIP_CALL( SCIPpresolve(scip) );
SCIP_STATUS scipStatus = SCIPgetStatus(scip);
// output presolved instance information
int nNonLinearConsHdlrs = 0;
outputProblemInfo(&nNonLinearConsHdlrs);
if( scipStatus == SCIP_STATUS_OPTIMAL ||
scipStatus == SCIP_STATUS_INFEASIBLE ) // when sub-MIP is solved at root node, the solution may not be saved
{
solvedAtReInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at reInit ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
else
{
/* adding root node cuts, if necessary */
if( paraParams->getBoolParamValue(UseRootNodeCuts) )
{
if( !addRootNodeCuts() )
{
solvedAtReInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at reInit ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
}
}
if( SCIPgetNVars(scip) == 0 ) // all variables were fixed in presolve
{
SCIP_CALL( SCIPsolve(scip) );
solvedAtReInit = true;
setFinalSolverStatus(ProblemWasSolved);
// finalDualBound = SCIPgetDualbound(scip);
std::cout << "=== solved at reInit ===" << std::endl;
finalDualBound = instance->convertToInternalValue(SCIPgetDualbound(scip));
writeSolution("Final Solution");
return 1;
}
DEF_SCIP_PARA_COMM( scipParaComm, paraComm );
/** check if feasible solution is found or not. If it was found, then generate paraSolution */
SCIP_SOL *sol = SCIPgetBestSol(scip);
assert(sol);
int nVars = SCIPgetNVars(scip);
SCIP_VAR **vars = SCIPgetVars(scip);
SCIP_Real *vals = new SCIP_Real[nVars];
SCIP_CALL_ABORT( SCIPgetSolVals(scip, sol, nVars, vars, vals) );
assert(solution);
delete solution;
solution = scipParaComm->createScipParaSolution(
0,
SCIPgetSolTransObj(scip, sol), // Only this value may be used
nVars,
vars,
vals
);
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("[Reinitialize]");
}
delete [] vals;
// instance = new PARA_INSTANCE_TYPE(scip, paraParams->getIntParamValue(InstanceTransferMethod));
assert(instance);
delete instance;
instance = scipParaComm->createScipParaInstance(scip, paraParams->getIntParamValue(InstanceTransferMethod));
/* for debugging
std::string subcipprefix("presolved_");
std::string subcipfilename;
std::ostringstream oss;
oss << instance->getProbName();
subcipfilename = oss.str();
subcipfilename += ".lp";
if( SCIPgetStage(scip) >= SCIP_STAGE_TRANSFORMED )
{
SCIP_CALL_ABORT( SCIPwriteTransProblem(scip, subcipfilename.c_str(), "lp", FALSE) );
}
************************/
#ifndef _COMM_PTH
if( onlyLinearConss )
{
// restore original parameters
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/knapsack", originalUpgradeKnapsack));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/logicor", originalUpgradeLogicor));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/setppc", originalUpgradeSetppc));
SCIP_CALL_ABORT( SCIPsetBoolParam(scip, "constraints/linear/upgrade/varbound", originalUpgradeVarbound));
}
#endif
return 0;
}
bool
ScipParaInitiator::tryToSetIncumbentSolution(
ParaSolution *sol,
bool checksol
)
{
ScipParaSolution *tempSol = dynamic_cast< ScipParaSolution * >(sol);
if( tempSol->getNVars() == 0 )
{
delete tempSol;
return false;
}
SCIP_SOL* newsol; /* solution to be created for the original problem */
paraComm->lockApp(); /* lock is necessary, if Solver runs as thread */
/* the solution from the working node should have at least as many variables as we have in the load coordinator scip
* it may be more if inactive variable had to be copied, i.e.,
* SCIPgetNVars(scip) is the number of active variables in the load coordinator scip
* tempSol->getNVars() is the number of original variables in the working node scip (scipParaSolver)
*/
SCIP_VAR** vars = 0;
/*
int maxrounds = 0;
SCIP_CALL_ABORT( SCIPgetIntParam(scip, "presolving/maxrounds", &maxrounds));
// if( paraParams->getIntParamValue(InstanceTransferMethod) == 2 // original file read
if( maxrounds == 0 ) // nopreprocessing
{
//assert(SCIPgetNVars(scip) <= tempSol->getNVars());
// create new solution for the original problem
SCIP_CALL_ABORT( SCIPcreateOrigSol(scip, &newsol, 0) );
vars = SCIPgetOrigVars(scip);
}
else
{
*/
if( checksol && SCIPgetNVars(scip) > tempSol->getNVars() )
{
std::cout << "*** You should check the solution! ***" << std::endl;
std::cout << "checksol = " << checksol << std::endl;
std::cout << "SCIPgetNVars(scip) = " << SCIPgetNVars(scip) << ", " << tempSol->getNVars() << std::endl;
delete tempSol;
return false;
}
assert(SCIPgetNVars(scip) <= tempSol->getNVars());
SCIP_CALL_ABORT( SCIPcreateSol(scip, &newsol, 0) );
vars = SCIPgetVars(scip);
// }
int i;
ScipParaInstance *scipInstance = dynamic_cast<ScipParaInstance *>(instance);
if( scipInstance->isOriginalIndeciesMap() )
{
int n = SCIPgetNVars(scip);
SCIP_Real *orgSolValues = new SCIP_Real[tempSol->getNVars()];
scipInstance->getSolValuesForOriginalProblem(tempSol, orgSolValues);
// for( i = 0; i < n; i++ )
// assert(SCIPgetNVars(scip) == tempSol->getNVars());
for( i = 0; i < n; i++ )
// for( i = 0; i < scipInstance->getVarIndexRange(); i++ )
{
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[i], orgSolValues[i]) );
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[tempSol->indexAmongSolvers(i)], orgSolValues[i]) );
// int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
// int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
// int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
/* skip inactive variable */
// if( probindex < 0 ) continue;
// assert(i == probindex); /* this is just a temporory assert, maybe this holds... */
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[probindex], orgSolValues[i]) );
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[i], orgSolValues[i]) );
}
delete [] orgSolValues;
}
else
{
assert( SCIPgetNVars(scip) == tempSol->getNVars() );
// for( i = 0; i < tempSol->getNVars(); i++ )
// {
// if( EPSGT(tempSol->getValues()[i],0.0, MINEPSILON) )
// {
// std::cout << "inex[" << i << "] = " << tempSol->indexAmongSolvers(i) << " = " << tempSol->getValues()[i] << std::endl;
// }
// }
for( i = 0; i < tempSol->getNVars(); i++ )
{
/* if index is larger-equal than number of active vars, then it's probably an inactive variable which had to be copied via SCIPcopy
* so we just ignore its value
*/
// if( tempSol->indexAmongSolvers(i) >= SCIPgetNVars(scip) ) continue;
// if( tempSol->indexAmongSolvers(i) > ( tempSol->getNVars() - 1 ) ) break;
// if( scipInstance->isOriginalIndeciesMap() )
// {
// int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[probindex], tempSol->getValues()[i]) );
// }
// else
// {
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[tempSol->indexAmongSolvers(i)], tempSol->getValues()[i]) );
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[i], tempSol->getValues()[i]) );
// }
/*
if( scipInstance->isOriginalIndeciesMap() )
{
if( scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i)) >= 0 && scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i)) < SCIPgetNVars(scip) )
{
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i))], tempSol->getValues()[i]) );
}
}
else
{
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[tempSol->indexAmongSolvers(i)], tempSol->getValues()[i]) );
}
*/
}
// if( i != tempSol->getNVars() )
// {
// /** the given solution should be generated in original space,
// * therefore the solution values cannot use for ParaSCIP
// */
// SCIP_CALL_ABORT( SCIPfreeSol(scip, &newsol) );
// delete tempSol;
// std::cout << "solution size mismatch! Call Yuji!" << std::endl;
// return false;
// }
}
SCIP_Bool success;
// checksol = true;
if( paraParams->getBoolParamValue(CheckFeasibilityInLC) == false )
{
if( checksol ) // checksol == true only when this routine is called to add solution from checkpoint file.
// therefore, no need to lock.
{
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, &success) );
#else
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, TRUE, &success) );
#endif
}
else
{
SCIP_CALL_ABORT( SCIPaddSolFree(scip, &newsol, &success) );
}
// std::cout << "** 2 ** success = " << success << std::endl;
paraComm->unlockApp();
if( success )
{
if( solution )
{
delete solution;
}
solution = tempSol;
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("");
}
return true;
}
else
{
if( checksol )
{
SCIP_CALL_ABORT( SCIPcreateOrigSol(scip, &newsol, 0) );
vars = SCIPgetOrigVars(scip);
if( scipInstance->isOriginalIndeciesMap() )
{
for( i = 0; i < tempSol->getNVars(); i++ )
{
int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
/* skip inactive variable */
if( probindex < 0 ) continue;
// assert(i == probindex); /* this is just a temporory assert, maybe this holds... */
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[probindex], tempSol->getValues()[i]) );
}
}
else
{
for( i = 0; i < tempSol->getNVars(); i++ )
{
// SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[tempSol->indexAmongSolvers(i)], tempSol->getValues()[i]) );
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, vars[i], tempSol->getValues()[i]) );
}
}
// if( i != tempSol->getNVars() ) /* this should not happen */
// {
// /** the given solution should be generated in original space,
// * therefore the solution values cannot use for ParaSCIP
// */
// SCIP_CALL_ABORT( SCIPfreeSol(scip, &newsol) );
// delete tempSol;
// std::cout << "solution size mismatch! Call Yuji!" << std::endl;
// return false;
//}
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, &success) );
#else
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, TRUE, &success) );
#endif
// std::cout << "** 3 ** success = " << success << std::endl;
if( success )
{
if( solution )
{
delete solution;
}
solution = tempSol;
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("");
}
return true;
}
}
delete tempSol;
return false;
}
}
else
{
//
// The following routine is not tested yet.
//
// std::cout << "Print sol. orig" << std::endl;
// SCIP_CALL_ABORT( SCIPprintSol(scip, newsol, NULL, FALSE) );
// std::cout << "Print sol. trans" << std::endl;
// SCIP_CALL_ABORT( SCIPprintTransSol(scip, newsol, NULL, FALSE) );
// int nVars = SCIPgetNVars(scip);
// for( int i = 0; i < nVars; i ++)
// {
// std::cout << i << ": " << SCIPvarGetName(vars[tempSol->indexAmongSolvers(i)]) << std::endl;
// std::cout << i << ": " << SCIPvarGetName(vars[i]) << std::endl;
// }
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, &success) );
#else
SCIP_CALL_ABORT( SCIPtrySolFree(scip, &newsol, FALSE, TRUE, TRUE, TRUE, TRUE, &success) );
#endif
assert(success);
if( success )
{
SCIP_CALL_ABORT( SCIPfreeSol(scip, &newsol) );
if( solution )
{
delete solution;
}
solution = tempSol;
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("");
}
paraComm->unlockApp();
return true;
}
else
{
SCIP_VAR* var = 0;
for( i = 0; i < tempSol->getNVars(); i++ )
{
int probindex = scipInstance->getOrigProbIndex(tempSol->indexAmongSolvers(i));
/* skip inactive variable */
if( probindex < 0 ) continue;
assert(i == probindex); /* this is just a temporory assert, maybe this holds... */
var = vars[probindex];
if( SCIPvarGetType(var) == SCIP_VARTYPE_CONTINUOUS ) continue;
if( tempSol->getValues()[i] > 0.0 )
{
tempSol->setValue(i, SCIPfeasFloor(scip,tempSol->getValues()[i]));
}
else
{
tempSol->setValue(i, SCIPfeasCeil(scip, tempSol->getValues()[i]) );
}
SCIP_CALL_ABORT( SCIPsetSolVal(scip, newsol, var, tempSol->getValues()[i]) );
}
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
SCIP_CALL_ABORT( SCIPtrySol(scip, newsol, FALSE, TRUE, TRUE, TRUE, &success) );
#else
SCIP_CALL_ABORT( SCIPtrySol(scip, newsol, FALSE, TRUE, TRUE, TRUE, TRUE, &success) );
#endif
if( success )
{
tempSol->setObjectiveFuntionValue(convertToInternalValue(SCIPsolGetOrigObj(newsol)));
SCIP_CALL_ABORT( SCIPfreeSol(scip, &newsol) );
if( solution )
{
delete solution;
}
solution = tempSol;
if( !paraParams->getBoolParamValue(Quiet) )
{
writeSolution("");
}
paraComm->unlockApp();
return true;
}
else
{
fprintf(solutionFile, "*** Rejected Solution ***\n");
SCIP_CALL_ABORT(SCIPprintSol(scip, newsol, solutionFile, FALSE));
if( transSolutionFile )
{
fprintf(transSolutionFile, "*** Rejected Solution ***\n");
SCIP_CALL_ABORT(SCIPprintTransSol(scip, newsol, transSolutionFile, FALSE));
}
if( SCIPisFeasLT( scip, convertToExternalValue(tempSol->getObjectiveFuntionValue()), SCIPgetPrimalbound(scip) ) )
{
// paraComm->lockApp();
std::cout << "Current scip primal value = " << SCIPgetPrimalbound(scip) << std::endl;
std::cout << "Objective value = " << convertToExternalValue(tempSol->getObjectiveFuntionValue()) << std::endl;
std::cout << "Initiator did not accept solution!" << std::endl;
// paraComm->unlockApp();
}
SCIP_CALL_ABORT( SCIPfreeSol(scip, &newsol) );
delete tempSol;
paraComm->unlockApp();
return false;
}
}
}
}
void
ScipParaInitiator::sendSolverInitializationMessage(
)
{
assert(scipDiffParamSetRoot && scipDiffParamSet);
scipDiffParamSetRoot->bcast(paraComm, 0);
scipDiffParamSet->bcast(paraComm, 0);
int warmStarted = 0;
if( isWarmStarted() )
{
warmStarted = 1;
}
paraComm->bcast(&warmStarted,1, ParaINT, 0);
double incumbentValue;
if( solution )
{
incumbentValue = solution->getObjectiveFuntionValue();
}
else
{
SCIP_SOL *sol = SCIPgetBestSol(scip);
if ( sol )
{
int nVars = SCIPgetNVars(scip);
SCIP_VAR **vars = SCIPgetVars(scip);
SCIP_Real *vals = new SCIP_Real[nVars];
SCIP_CALL_ABORT( SCIPgetSolVals(scip, sol, nVars, vars, vals) );
DEF_SCIP_PARA_COMM( scipParaComm, paraComm);
solution = scipParaComm->createScipParaSolution(
0,
SCIPgetSolTransObj(scip,sol),
nVars,
vars,
vals
);
delete [] vals;
incumbentValue = solution->getObjectiveFuntionValue();
}
else
{
incumbentValue = DBL_MAX;
}
}
paraComm->bcast(&incumbentValue, 1, ParaDOUBLE, 0);
if( paraParams->getBoolParamValue(NoUpperBoundTransferInRacing) )
{
int solutionExists = 0;
paraComm->bcast(&solutionExists, 1, ParaINT, 0);
}
else
{
/** if a feasible solution exists, broadcast the solution */
if( paraParams->getBoolParamValue(DistributeBestPrimalSolution) )
{
/* bcast solution if it is necessary */
int solutionExists = 0;
if( solution )
{
solutionExists = 1;
paraComm->bcast(&solutionExists, 1, ParaINT, 0);
solution->bcast(paraComm, 0);
}
else
{
paraComm->bcast(&solutionExists, 1, ParaINT, 0);
}
}
}
// allocate here, since the number of variables is fixed when the instance data are sent
if( ( paraParams->getIntParamValue(UG::RampUpPhaseProcess) == 1 ||
paraParams->getIntParamValue(UG::RampUpPhaseProcess) == 2 ) &&
paraParams->getBoolParamValue(UG::CommunicateTighterBoundsInRacing) )
{
assert( instance->getNVars() > 0 );
assert( instance->getVarIndexRange() > 0 );
tightenedVarLbs = new double[instance->getNVars()];
tightenedVarUbs = new double[instance->getNVars()];
for( int i = 0; i < instance->getNVars(); i++ )
{
tightenedVarLbs[i] = -DBL_MAX;
tightenedVarUbs[i] = DBL_MAX;
}
}
}
/** get gap */
double
ScipParaInitiator::getAbsgap(
double dualBoundValue
)
{
if( !solution ) return SCIPinfinity(scip);
SCIP_Real primalbound = instance->convertToExternalValue(solution->getObjectiveFuntionValue());
SCIP_Real dualbound = instance->convertToExternalValue(dualBoundValue);
return (primalbound - dualbound);
}
/** get gap */
double
ScipParaInitiator::getGap(
double dualBoundValue
)
{
if( !solution ) return SCIPinfinity(scip);
SCIP_Real primalbound = instance->convertToExternalValue(solution->getObjectiveFuntionValue());
SCIP_Real dualbound = instance->convertToExternalValue(dualBoundValue);
if( SCIPisEQ(scip, primalbound, dualbound) )
return 0.0;
else if( SCIPisZero(scip, dualbound)
|| SCIPisZero(scip, primalbound)
|| SCIPisInfinity(scip, REALABS(primalbound))
|| SCIPisInfinity(scip, REALABS(dualbound))
|| primalbound * dualbound < 0.0 )
return SCIPinfinity(scip);
else
return REALABS((primalbound - dualbound)/MIN(REALABS(dualbound),REALABS(primalbound)));
}
/** get epsilon */
double
ScipParaInitiator::getEpsilon(
)
{
SCIP_Real epsilon;
SCIP_CALL_ABORT( SCIPgetRealParam(scip, "numerics/epsilon", &epsilon));
return epsilon;
}
void
ScipParaInitiator::writeSolution(
const std::string& message
)
{
if( message == "Final Solution" )
{
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
if( paraParams->getBoolParamValue(Quiet) )
{
SCIPmessageSetDefaultHandler(); // If no message handler is set, it cannot write solution,too.
}
#endif
fprintf(solutionFile, "[ Final Solution ]\n");
if( transSolutionFile )
{
fprintf(transSolutionFile, "[ Final Solution ]\n");
}
}
else
{
fprintf(solutionFile,"%s\n",message.c_str());
if( transSolutionFile )
{
fprintf(transSolutionFile,"%s\n", message.c_str());
}
}
SCIP_SOL* sol = SCIPgetBestSol(scip);
if( sol )
{
SCIP_CALL_ABORT( SCIPprintBestSol( scip, solutionFile, FALSE) );
if( transSolutionFile )
{
if( SCIPsolGetOrigin(sol) != SCIP_SOLORIGIN_ORIGINAL )
{
ScipParaInstance *scipInstance = dynamic_cast<ScipParaInstance *>(instance);
if( scipInstance->isOriginalIndeciesMap() )
{
SCIP_CALL_ABORT( SCIPprintBestSol( scipInstance->getParaInstanceScip(), transSolutionFile, FALSE) );
}
else
{
SCIP_CALL_ABORT( SCIPprintBestTransSol( scip, transSolutionFile, FALSE) );
}
}
else
{
fprintf(transSolutionFile, "best solution is defined in original space - cannot print it as transformed solution\n");
}
}
/*
if( userPlugins )
{
userPlugins->writeUserSolution(scip);
}
*/
}
else
{
fprintf(solutionFile, "No Solution\n");
if( transSolutionFile )
{
fprintf(transSolutionFile, "No Solution\n");
}
}
}
void
ScipParaInitiator::writeParaInstance(
const std::string& filename
)
{
FILE *file = fopen(filename.c_str(),"a");
if( !file )
{
std::cout << "file : " << filename << "cannot open." << std::endl;
exit(1);
}
ScipParaInstance *scipInstance = dynamic_cast<ScipParaInstance *>(instance);
if( scipInstance->isOriginalIndeciesMap() )
{
SCIP_CALL_ABORT( SCIPprintOrigProblem(scipInstance->getParaInstanceScip(), file, "lp", FALSE) );
}
else
{
SCIP_CALL_ABORT( SCIPprintTransProblem(scip, file, "lp", FALSE) );
}
}
/** write solver runtime parameters */
void
ScipParaInitiator::writeSolverParameters(
std::ostream *os
)
{
if( scipDiffParamSetRoot->nDiffParams() == 0 )
{
*os << "[ SCIP parameters for root Solver are all default values ]" << std::endl;
}
else
{
*os << "[ Not default SCIP parameters for root Solver are as follows ]" << std::endl;
*os << scipDiffParamSetRoot->toString();
}
if( scipDiffParamSet->nDiffParams() == 0 )
{
*os << "[ SCIP parameters for NOT root Solvers are all default values ]" << std::endl;
}
else
{
*os << "[ Not default SCIP parameters for NOT root Solvers are as follows ]" << std::endl;
*os << scipDiffParamSet->toString();
}
}
#ifdef UG_WITH_ZLIB
/** write checkpoint solution */
void
ScipParaInitiator::writeCheckpointSolution(
const std::string& filename
)
{
gzstream::ogzstream checkpointSolutionStream;
checkpointSolutionStream.open(filename.c_str(), std::ios::out | std::ios::binary);
if( !checkpointSolutionStream )
{
std::cout << "Checkpoint file for solution cannot open. file name = " << filename << std::endl;
exit(1);
}
if( solution )
solution->write(checkpointSolutionStream);
checkpointSolutionStream.close(); /** empty solution file is necessary,
* because it is removed next at the next checkpoint */
}
/** read solution from checkpoint file */
double
ScipParaInitiator::readSolutionFromCheckpointFile(
char *afterCheckpointingSolutionFileName
)
{
char tempSolutionFileName[256];
sprintf(tempSolutionFileName,"%s_solution.gz", prefixWarm );
gzstream::igzstream checkpointSolutionStream;
checkpointSolutionStream.open(tempSolutionFileName, std::ios::in | std::ios::binary);
if( !checkpointSolutionStream )
{
std::cout << "checkpoint solution file cannot open: file name = " << tempSolutionFileName << std::endl;
exit(1);
}
if( solution )
{
ScipParaSolution *sol = dynamic_cast<ScipParaSolution*>(paraComm->createParaSolution());
if( sol->read(paraComm, checkpointSolutionStream) )
{
if( solution->getObjectiveFuntionValue() > sol->getObjectiveFuntionValue() )
{
delete solution;
solution = sol;
}
}
else
{
delete sol;
}
}
else
{
solution = dynamic_cast<ScipParaSolution*>(paraComm->createParaSolution());
if( !solution->read(paraComm, checkpointSolutionStream) )
{
delete solution;
solution = 0;
checkpointSolutionStream.close();
}
}
checkpointSolutionStream.close();
if( solution )
{
if( !tryToSetIncumbentSolution(solution->clone(paraComm), true) )
{
std::cout << "***** Given solution is wrong! ***************************" << std::endl;
std::cout << "***** If the solution was given from checkpoint file, ***" << std::endl;
std::cout << "***** it might be generated in original problem space **" << std::endl;
std::cout << "***** Only primal value is used. *************************" << std::endl;
std::cout << "***** You should better to use -isol option. ************" << std::endl;
std::cout << "***** Or, better to use no distribute solution option. ***" << std::endl;
}
}
/** check if after checkpoing solution file exists or not */
checkpointSolutionStream.open(afterCheckpointingSolutionFileName, std::ios::in | std::ios::binary);
if( checkpointSolutionStream )
{
/** set up from after checkpointing solution file */
ScipParaSolution *sol = dynamic_cast<ScipParaSolution*>(paraComm->createParaSolution());
if( sol->read(paraComm, checkpointSolutionStream) )
{
if( !solution )
{
solution = sol;
if( tryToSetIncumbentSolution(solution->clone(paraComm), true) )
{
std::cout << "***** After checkpoint solution is RIGHT! ****************" << std::endl;
}
}
else
{
if( solution->getObjectiveFuntionValue() > sol->getObjectiveFuntionValue() )
{
delete solution;
solution = sol;
if( tryToSetIncumbentSolution(solution->clone(paraComm), true) )
{
std::cout << "***** After checkpoint solution is RIGHT! ****************" << std::endl;
}
}
}
}
else
{
delete sol;
}
checkpointSolutionStream.close();
}
if( solution )
{
return solution->getObjectiveFuntionValue();
}
else
{
return DBL_MAX;
}
}
#endif
/** generate racing ramp-up parameter sets */
void
ScipParaInitiator::generateRacingRampUpParameterSets(
int nParamSets,
ParaRacingRampUpParamSet **racingRampUpParamSets
)
{
ScipDiffParamSet *racingScipDiffParamSet;
if( racingSettingsName )
{
SCIP_CALL_ABORT( SCIPresetParams(scip) );
SCIP_CALL_ABORT( SCIPreadParams(scip, racingSettingsName) );
DEF_SCIP_PARA_COMM( scipParaComm, paraComm );
racingScipDiffParamSet = scipParaComm->createScipDiffParamSet(scip);;
SCIP_CALL_ABORT( SCIPresetParams(scip) );
}
else
{
racingScipDiffParamSet = 0; // all default
}
int n = 0; /**< keep the number of generated params */
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
int npm = -1; /**< keep the number of variable permutation seed; start from default: -1 */
#else
int npm = 0; /**< keep the number of variable permutation seed; start from default: 0 */
#endif
int nbo = 0; /**< keep the number of branching order seed */
DEF_SCIP_PARA_COMM( scipParaComm, paraComm);
for(;;)
{
for( int i = 0; i < paraParams->getIntParamValue(MaxNRacingParamSetSeed); i++ )
{
#if (SCIP_VERSION < 321 || ( SCIP_VERSION == 321 && SCIP_SUBVERSION < 2) )
if( npm > ( paraParams->getIntParamValue(TryNVariablegOrderInRacing) - 1 ) ) npm = -1;
#else
if( npm > ( paraParams->getIntParamValue(TryNVariablegOrderInRacing) - 1 ) ) npm = 0;
#endif
if( nbo > paraParams->getIntParamValue(TryNBranchingOrderInRacing) ) nbo = 0;
racingRampUpParamSets[n] = scipParaComm->createScipParaRacingRampUpParamSet(
paraParams->getIntParamValue(RacingRampUpTerminationCriteria),
paraParams->getIntParamValue(StopRacingNumberOfNodesLeft),
paraParams->getRealParamValue(StopRacingTimeLimit),
i,
npm,
nbo,
racingScipDiffParamSet
);
npm++;
nbo++;
n++;
if( n >= nParamSets ) return;
}
}
}
/** get solving status string */
std::string
ScipParaInitiator::getStatus(
)
{
SCIP_SOL* sol = SCIPgetBestSol(scip);
if( sol )
{
return std::string("solution found exist");
}
else
{
return std::string("no solution");
}
}
/** print solver version **/
void
ScipParaInitiator::printSolverVersion(
std::ostream *os /**< output file (or NULL for standard output) */
)
{
#ifndef SCIP_THREADSAFE_MESSAGEHDLRS
SCIPprintVersion( NULL );
#else
SCIPprintVersion( scip, NULL );
#endif
SCIPprintExternalCodes(scip, NULL);
}
/** set initial stat on initiator */
void
ScipParaInitiator::accumulateInitialStat(
ParaInitialStat *initialStat
)
{
ScipParaInitialStat *scipInitialStat = dynamic_cast<ScipParaInitialStat *>(initialStat);
ScipParaInstance *scipInstance = dynamic_cast<ScipParaInstance *>(instance);
if( scipInstance->isOriginalIndeciesMap() )
{
scipInitialStat->accumulateOn(scipInstance->getParaInstanceScip());;
}
else
{
scipInitialStat->accumulateOn(scip);
}
}
/** set initial stat on DiffSubproblem */
void
ScipParaInitiator::setInitialStatOnDiffSubproblem(
int minDepth,
int maxDepth,
ParaDiffSubproblem *diffSubproblem
)
{
ScipParaDiffSubproblem *scipDiffSubproblem = dynamic_cast<ScipParaDiffSubproblem *>(diffSubproblem);
ScipParaInstance *scipInstance = dynamic_cast<ScipParaInstance *>(instance);
if( scipInstance->isOriginalIndeciesMap() )
{
scipDiffSubproblem->addInitialBranchVarStats(minDepth, maxDepth, scipInstance->getParaInstanceScip());
}
else
{
scipDiffSubproblem->addInitialBranchVarStats(minDepth, maxDepth, scip);
}
}
/** set final solver status */
void
ScipParaInitiator::setFinalSolverStatus(
FinalSolverState state
)
{
finalState = state;
}
/** set number of nodes solved */
void
ScipParaInitiator::setNumberOfNodesSolved(
long long n
)
{
nSolved = n;
}
/** set final dual bound */
void
ScipParaInitiator::setDualBound(
double bound
)
{
finalDualBound = bound;
}
/** output solution status */
void
ScipParaInitiator::outputFinalSolverStatistics(
std::ostream *os,
double time
)
{
if( os == 0 )
{
os = &std::cout;
}
if( finalState != Aborted )
{
*os << "SCIP Status : ";
}
switch ( finalState )
{
case InitialNodesGenerated:
*os << "initial nodes were generated" << std::endl;
break;
case Aborted:
*os << std::endl;
break;
case HardTimeLimitIsReached:
*os << "solving was interrupted [ hard time limit reached ]" << std::endl;
break;
case ComputingWasInterrupted:
*os << "solving was interrupted" << std::endl;
break;
case ProblemWasSolved:
*os << "problem is solved" << std::endl;
break;
case RequestedSubProblemsWereSolved:
*os << "requested subproblems are solved" << std::endl;
break;
default:
THROW_LOGICAL_ERROR1("invalid final state");
}
*os << "Total Time : " << time << std::endl;
*os << " solving : " << time << std::endl;
*os << " presolving : " << SCIPgetPresolvingTime(scip) << " (included in solving)" << std::endl;
*os << "B&B Tree :" << std::endl;
*os << " nodes (total) : " << nSolved << std::endl;
*os << "Solution :" << std::endl;
*os << " Solutions found : " << SCIPgetNSols(scip) << std::endl;
SCIP_Real primalbound = SCIPinfinity(scip);
// std::cout << "** Nsols = " << SCIPgetNSols(scip) << std::endl;
// if( solution )
// {
// std::cout << "*** obj = " << convertToExternalValue(solution->getObjectiveFuntionValue()) << std::endl;
// }
if( SCIPgetNSols(scip) != 0 )
{
primalbound = SCIPgetPrimalbound(scip);
}
else
{
if( solution && solution->getNVars() > 0 )
{
primalbound = solution->getObjectiveFuntionValue(); // This solution should be in original problem space.
// So, do not have to convert to original space.
}
else
{
if( EPSLT( objlimit, DBL_MAX, MINEPSILON ) )
{
primalbound = objlimit;
}
}
}
*os << " Primal Bound : ";
if( SCIPisInfinity(scip, REALABS(primalbound) ) )
{
*os << "infeasible" << std::endl;
}
else
{
(*os).setf(std::ios::showpos);
*os << std::scientific << std::showpoint << std::setprecision(14) << primalbound << std::endl;
(*os).unsetf(std::ios::showpos);
}
finalDualBound = instance->convertToExternalValue(finalDualBound); // converted to original one
SCIP_Real finalGap = 0.0;
if( SCIPisEQ(scip, primalbound, finalDualBound) )
finalGap = 0.0;
else if( SCIPisZero(scip, finalDualBound)
|| SCIPisZero(scip, primalbound)
|| SCIPisInfinity(scip, REALABS(primalbound))
|| SCIPisInfinity(scip, REALABS(finalDualBound))
|| primalbound * finalDualBound < 0.0 )
finalGap = SCIPinfinity(scip);
else
finalGap = REALABS((primalbound - finalDualBound)/MIN(REALABS(finalDualBound),REALABS(primalbound)));
#if SCIP_VERSION > 302 || ( SCIP_VERSION == 302 && SCIP_SUBVERSION == 1 )
*os << " Dual Bound : ";
#else
*os << "Dual Bound : ";
#endif
if( SCIPisInfinity(scip, REALABS(finalDualBound) ) )
*os << " -" << std::endl;
else
{
(*os).setf(std::ios::showpos);
*os << std::scientific << std::showpoint << std::setprecision(14)
<< finalDualBound << std::endl;
(*os).unsetf(std::ios::showpos);
}
*os << "Gap : ";
if( SCIPisInfinity(scip, finalGap ) )
*os << " infinite" << std::endl;
else
{
*os << std::fixed << std::setprecision(5) << 100.0 * finalGap << " %" << std::endl;
}
assert( finalState != ProblemWasSolved ||
( finalState == ProblemWasSolved && ( SCIPgetNSols(scip) == 0 || ( SCIPgetNSols(scip) != 0 && finalGap <= MINEPSILON ) ) ) );
if( userPlugins )
{
userPlugins->writeUserSolution(scip, paraComm->getSize()-1, finalDualBound);
}
}
void
ScipParaInitiator::outputProblemInfo(
int *nNonLinearConsHdlrs
)
{
std::cout << "Original Problem :" << std::endl;
std::cout << " Problem name : " << SCIPgetProbName(scip) << std::endl;
std::cout << " Variables : " << SCIPgetNOrigVars(scip)
<< " (" << SCIPgetNOrigBinVars(scip) << " binary, "
<< SCIPgetNOrigIntVars(scip) << " integer, "
<< SCIPgetNOrigImplVars(scip) << " implicit integer, "
<< SCIPgetNOrigContVars(scip) << " continuous)" << std::endl;
std::cout << " Constraints : " << SCIPgetNOrigConss(scip) << std::endl;
std::cout << " Objective sense : " << (SCIPgetObjsense(scip) == SCIP_OBJSENSE_MINIMIZE ? "minimize" : "maximize") << std::endl;
std::cout << "Presolved Problem :" << std::endl;
std::cout << " Variables : " << SCIPgetNVars(scip)
<< " (" << SCIPgetNBinVars(scip) << " binary, "
<< SCIPgetNIntVars(scip) << " integer, "
<< SCIPgetNImplVars(scip) << " implicit integer, "
<< SCIPgetNContVars(scip) << " continuous)" << std::endl;
std::cout << " Constraints : " << SCIPgetNConss(scip) << std::endl;
std::cout << "Constraints : Number" << std::endl;
for( int i = 0; i < SCIPgetNConshdlrs(scip); ++i )
{
SCIP_CONSHDLR* conshdlr;
int startnactiveconss;
int maxnactiveconss;
conshdlr = SCIPgetConshdlrs(scip)[i];
startnactiveconss = SCIPconshdlrGetStartNActiveConss(conshdlr);
maxnactiveconss = SCIPconshdlrGetMaxNActiveConss(conshdlr);
std::cout << " " << std::setw(17) << std::left << SCIPconshdlrGetName(conshdlr) << ": "
<< startnactiveconss << ( maxnactiveconss > startnactiveconss ? '+' : ' ') << std::endl;
if( startnactiveconss > 0
&& std::string(SCIPconshdlrGetName(conshdlr)) != std::string("linear") )
{
*nNonLinearConsHdlrs += startnactiveconss;
}
}
}
bool
ScipParaInitiator::onlyLinearConsHandler(
)
{
for( int i = 0; i < SCIPgetNConss(scip); ++i )
{
SCIP_CONS** conss = SCIPgetConss(scip);
SCIP_CONSHDLR* conshdlr = SCIPconsGetHdlr(conss[i]);
if( std::string(SCIPconshdlrGetName(conshdlr)) != std::string("linear") )
{
return false;
}
}
return true;
}
void
ScipParaInitiator::setUserPlugins(
ScipUserPlugins *inUi
)
{
userPlugins = inUi;
}
| 34.670934 | 170 | 0.579943 | [
"transform"
] |
314fba4e4128a162c6544e388002ff6d2276ea80 | 7,588 | cpp | C++ | src/core/impgeneration.cpp | TimoBx/pbrt | 1d5634953a79eb251b1a245382cc3587b6e0a15a | [
"BSD-2-Clause"
] | null | null | null | src/core/impgeneration.cpp | TimoBx/pbrt | 1d5634953a79eb251b1a245382cc3587b6e0a15a | [
"BSD-2-Clause"
] | null | null | null | src/core/impgeneration.cpp | TimoBx/pbrt | 1d5634953a79eb251b1a245382cc3587b6e0a15a | [
"BSD-2-Clause"
] | null | null | null | // core/impgeneration.cpp*
#include "impgeneration.h"
#include "api.h"
#include "imageio.h"
#include "lights/infinite.h"
#include "paramset.h"
#include <limits>
#include <algorithm>
#include <iostream>
#include <string>
#include <fstream>
namespace pbrt {
/*
Takes a .pbrt file name as parameter, and returns the name of the new file.
This function is used to generate the name of both the imp map and the
rendered image, in case we chosed to change the material.
*/
std::string computeNewFilename(std::string filename, std::string prefix, std::string suffix, std::string extension) {
std::string file = filename;
std::size_t pos = file.find_last_of(".");
return prefix + file.substr(0,pos) + suffix + extension;
}
void computeImpMapNames(Options &options) {
// These names represent the path of the ray.
// R means we got a reflection; T means we got a transmission; 0 means it's the end of the path.
// X means we got anything; at this point we don't care what, though it is not 0.
options.mapNames["R0"] = computeNewFilename(options.newFileName, "impmapR0_", "", ".exr");
options.mapNames["RX"] = computeNewFilename(options.newFileName, "impmapRX_", "", ".exr");
options.mapNames["R"] = computeNewFilename(options.newFileName, "impmapR_", "", ".exr");
options.mapNames["TT"] = computeNewFilename(options.newFileName, "impmapTT_", "", ".exr");
options.mapNames["TT0"] = computeNewFilename(options.newFileName, "impmapTT0_", "", ".exr");
options.mapNames["TTX"] = computeNewFilename(options.newFileName, "impmapTTX_", "", ".exr");
options.mapNames["TRT"] = computeNewFilename(options.newFileName, "impmapTRT_", "", ".exr");
options.mapNames["TRT0"] = computeNewFilename(options.newFileName, "impmapTRT0_", "", ".exr");
options.mapNames["TRTX"] = computeNewFilename(options.newFileName, "impmapTRTX_", "", ".exr");
options.mapNames["TX"] = computeNewFilename(options.newFileName, "impmapTX_", "", ".exr");
options.mapNames["ALL"] = computeNewFilename(options.newFileName, "impmapALL_", "", ".exr");
}
/*
Changes the pbrt options: the importance boolean, the size of the importance
map, and the initial color of the imp map (black by default).
This function is called when the option --importance is given by the user.
*/
void changeImpOptions(Options &options) {
options.importance = true;
options.orthoCam = true;
options.widthImpMap = 1024, options.heightImpMap = 512;
options.maps["R0"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["RX"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["R"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TT"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TT0"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TTX"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TRT"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TRT0"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TRTX"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["TX"] = new Float[3 * options.widthImpMap * options.heightImpMap];
options.maps["ALL"] = new Float[3 * options.widthImpMap * options.heightImpMap];
}
/*
Replace whatever integrator was specified in the pbrt file, by our importance
integrator.
If the integrator was path, volpath or whitted, the parameters specified can be kept
by the importance integrator.
*/
void changeIntegrator(const std::string &name, const ParamSet ¶ms, std::string &IntegratorName, ParamSet &IntegratorParams) {
IntegratorName = "impath";
if (name == "volpath" || name == "path" || name == "whitted") {
IntegratorParams = params;
}
}
/*
Remove all lights in the scene, and add a single light source of type InfiniteAreaLight.
There is supposedly no light left in the scene already; but just in case, we clear the light vector.
The importance map, used to initialize the infinite light, is created, with its file
name given by the computeNewFilename function.
*/
void changeLights(Options &options, std::vector<std::shared_ptr<Light>> &lights, const Transform &light2world) {
if (!lights.empty()) {
lights.clear();
}
int w = options.widthImpMap, h = options.heightImpMap;
lights.push_back(std::make_shared<InfiniteAreaLight>(Transform(), Spectrum(1.0) * Spectrum(1.0), 100, "../../../build/uffizi-large.exr"));
//lights.push_back(std::make_shared<InfiniteAreaLight>(light2world, Spectrum(1.0) * Spectrum(1.0), 100, "../../../build/test.png"));
}
/*
Normalizes the importance map. Every value should be between 0 and 1.
*/
Float* normalizeImpMap(Float *impmap, int width, int height) {
Float max = 0;
for (int i = 0; i < width*height; i++) {
if (max < impmap[i*3])
max = impmap[i*3];
}
for (int i = 0; i < width*height*3; i++) {
impmap[i] = (Float)(impmap[i] / max);
}
return impmap;
}
/*
The following functions aim to normalize the importance maps, using an arbitrairy value:
the mean of the basic imp map, its median, its maxi value etc...
The max seems to be the best choice to use; in doubt, use max.
*/
Float getTotal(Float* t, int w, int h) {
Float total = 0;
for (int i = 0; i < w*h; i++) {
total += t[i*3];
}
return total;
}
Float getMax(Float* t, int w, int h) {
Float max = 0;
for (int i = 0; i < w*h; i++) {
if (t[i*3] > max) max = t[i*3];
}
return max;
}
Float getMean(Float* t, int w, int h) {
Float min = std::numeric_limits<float>::max(), max = 0;
for (int i = 0; i < w*h; i++) {
if (t[i*3] > 0 && t[i*3] < min) min = t[i*3];
if (t[i*3] > max) max = t[i*3];
}
return (max - min) / 2;
}
Float getMedian(Float* t, int w, int h) {
std::vector<Float> tmp;
for (int i = 0; i < w*h; i++) {
if (t[i*3] > 0)
tmp.push_back(t[i*3]);
}
std::sort(tmp.begin(), tmp.end());
// std::ofstream fichier("test.txt", std::ios::out | std::ios::trunc);
// if(fichier) {
// for (int i = 0; i < tmp.size(); i++) {
// fichier << tmp[i] << std::endl;
// }
// fichier.close();
// }
// else
// std::cout << "Impossible d'ouvrir le fichier !" << std::endl;
return 0.5 * (tmp[tmp.size()/2 - 1] + tmp[tmp.size()/2]);
}
void normalizeMaps(Options &options, Float value) {
int w = options.widthImpMap, h = options.heightImpMap;
if (value == 0) return;
std::map<std::string, Float*>::iterator it = options.maps.begin();
while (it != options.maps.end()) {
for (int i = 0; i < w*h*3; i++) {
(it->second)[i] /= value;
}
it++;
}
}
/*
Saves the importance map in the .EXR image file used by the previously
created infinite light.
*/
void writeImpImages(Options &options) {
// options.impMap = normalizeImpMap(options.impMap, options.widthImpMap, options.heightImpMap);
int w = options.widthImpMap, h = options.heightImpMap;
std::map<std::string, Float*>::iterator it = options.maps.begin();
while (it != options.maps.end()) {
std::string index = it->first;
WriteImage(options.mapNames[index], options.maps[index], Bounds2i(Point2i(0, 0), Point2i(w, h)), Point2i(w, h));
it++;
}
}
} // namespace pbrt
| 36.30622 | 143 | 0.641671 | [
"vector",
"transform"
] |
315391a1def098a583dda7f1204aa7dcfb91c0e3 | 3,314 | cpp | C++ | Desktop/colortie.cpp | Waller-Lab/CompCellScopeTIE | 1b05098b339d7ef3cdd7c894e5084beed81b1b89 | [
"MIT"
] | null | null | null | Desktop/colortie.cpp | Waller-Lab/CompCellScopeTIE | 1b05098b339d7ef3cdd7c894e5084beed81b1b89 | [
"MIT"
] | null | null | null | Desktop/colortie.cpp | Waller-Lab/CompCellScopeTIE | 1b05098b339d7ef3cdd7c894e5084beed81b1b89 | [
"MIT"
] | null | null | null | #include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#include <math.h>
#include <iostream>
using namespace cv;
using namespace std;
int* meshgrid_x(int width);
int* meshgrid_y(int height);
int main(int argc, char ** argv)
{
if( argc < 2 ){
cout << "usage: ColorTie imagepath k deltaZ epsilon outputpath" << endl;
return 0;
}
double k, delta_z, epsilon;
const char* filename = argv[1];
if(argc == 6){
k = strtol(argv[2], NULL, 10);
delta_z = strtol(argv[3], NULL, 10);
epsilon = strtol(argv[4], NULL, 10);
} else {
k = 10;
delta_z = 1000;
epsilon = 100;
}
Mat I = imread(filename, CV_LOAD_IMAGE_COLOR);
if(I.empty())
return -1;
vector<Mat> rgb;
split(I, rgb);
Mat red, green, blue;
rgb[0].convertTo(blue, CV_64F);
rgb[1].convertTo(green, CV_64F);
rgb[2].convertTo(red, CV_64F);
double offset = 10;
Mat G = (k/(green + offset)).mul((blue - red)*(1.0/delta_z));
Mat padded; //expand input image to optimal size
int m = getOptimalDFTSize( G.rows );
int n = getOptimalDFTSize( G.cols ); // on the border add zero values
copyMakeBorder(G, padded, 0, m - G.rows, 0, n - G.cols, BORDER_CONSTANT, Scalar::all(0));
Mat planes[] = {Mat_<double>(padded), Mat::zeros(padded.size(), CV_64F)};
Mat complexG;
merge(planes, 2, complexG); // Add to the expanded another plane with zeros
dft(complexG, complexG); // this way the result may fit in the source matrix
// compute the magnitude and switch to logarithmic scale
// => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
split(complexG, planes); // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
int * mesh_x = meshgrid_x(planes[0].cols);
int * mesh_y = meshgrid_y(planes[0].rows);
double pi_squared = pow(M_PI, 2);
for(int y = 0; y < planes[0].rows; y++){
for(int x = 0; x < planes[0].cols; x++){
double denom = -4*pi_squared*(pow(mesh_x[x], 2) + pow(mesh_y[y], 2)) + epsilon;
planes[0].at<double>(y,x) /= denom;
planes[1].at<double>(y,x) /= denom;
}
}
merge(planes, 2, complexG);
Mat result;
dft(complexG, result, DFT_INVERSE|DFT_REAL_OUTPUT);
string result_path = "results/";
result_path.append(argv[5]);
normalize(result, result, 0, 1, CV_MINMAX);
//result.convertTo(result, CV_32F);
//imshow("original image" , I); // Show the result
//imshow("qualitative phase image", result);
result.convertTo(result, CV_8U, 255.0);
imwrite(result_path, result);
return 0;
}
int* meshgrid_x(int width){
int * mesh_x = new int[width];
for(int i = 0; i < width; i++){
if(i <= (width-1)/2){
mesh_x[i] = i;
} else {
mesh_x[i] = i - width;
}
}
return mesh_x;
}
int* meshgrid_y(int height){
int * mesh_y = new int[height];
for(int i = 0; i < height; i++){
if(i <= (height-1)/2){
mesh_y[i] = -1*i;
} else {
mesh_y[i] = height - i;
}
}
return mesh_y;
}
| 29.855856 | 95 | 0.561255 | [
"vector"
] |
315a8d5087bfc8c0faf642e4795e0639f927c132 | 2,407 | cpp | C++ | src/ResourceManager.cpp | inosphe/GIRenderer | 3856c2455b668d16c0bf41d453be895a39053217 | [
"MIT"
] | 2 | 2016-07-25T22:47:28.000Z | 2020-08-10T08:02:06.000Z | src/ResourceManager.cpp | inosphe/GIRenderer | 3856c2455b668d16c0bf41d453be895a39053217 | [
"MIT"
] | null | null | null | src/ResourceManager.cpp | inosphe/GIRenderer | 3856c2455b668d16c0bf41d453be895a39053217 | [
"MIT"
] | 1 | 2020-08-10T08:02:08.000Z | 2020-08-10T08:02:08.000Z | //
// Created by inosphe on 2016. 3. 28..
//
#include "ResourceManager.h"
#include <fstream>
#include <ios>
#include "Logger.h"
#include <fbxsdk.h>
#include <fbxsdk/fileio/fbxiosettings.h>
#include "FBXLoader.h"
#include "FBXModel.h"
#include "Image.h"
#include "RESOURCE_PATH.h"
#include "stb_image.h"
namespace Resource{
ResourceManager::ResourceManager()
{
}
ResourceManager::~ResourceManager() {
Clear();
}
bool ResourceManager::Init() {
m_pFBXLoader = new FBX::FBXLoader();
m_pFBXLoader->Init();
return true;
}
void ResourceManager::Clear() {
m_mapResourceCached.clear();
SAFE_DELETE(m_pFBXLoader);
}
std::vector<std::shared_ptr<IResource>> ResourceManager::LoadFBXFromConfig(const string& strConfig) {
std::ifstream fileStream(RESOURCE_PATH(strConfig));
fileStream.open(strConfig);
if(!fileStream.is_open()){
throw "file not opened.";
}
string strResourceName;
std::vector<std::shared_ptr<IResource>> ret;
while(std::getline(fileStream, strResourceName)){
ret.push_back(Load<RESOURCE_TYPE::FBX>(strResourceName, true));
}
return ret;
}
std::shared_ptr<Resource::Image> ResourceManager::LoadImageFromFile(string strFilepath) {
int w;
int h;
int comp;
// size_t pos = 0;
// while((pos = strFilepath.find('\\', pos))!=string::npos){
// strFilepath.replace(pos, 1, "/");
// }
std::replace(strFilepath.begin(), strFilepath.end(), '\\', '/');
BYTE* image = stbi_load(strFilepath.c_str(), &w, &h, &comp, STBI_rgb_alpha);
if(image)
return std::shared_ptr<Resource::Image>(new Resource::Image(image, w, h, comp));
else
return nullptr;
}
std::shared_ptr<IResource> ResourceManager::GetResource(const string &strFilepath) {
auto itr = m_mapResourceCached.find(strFilepath);
if(itr != m_mapResourceCached.end()){
return itr->second;
}
return std::shared_ptr<IResource>(nullptr);
}
template <>
std::shared_ptr<Resource::IResource> ResourceManager::Load<RESOURCE_TYPE::FBX>(const string& strFilepath, bool bStoreCache){
auto itr = m_mapResourceCached.find(strFilepath);
if(itr != m_mapResourceCached.end()){
return itr->second;
}
auto pResource = m_pFBXLoader->Load(strFilepath);
if(bStoreCache){
auto ret = m_mapResourceCached.insert(std::make_pair(strFilepath, pResource));
if(!ret.second){
// throw std::runtime_error("inserting cache failed.");
}
}
return pResource;
}
}
| 23.598039 | 125 | 0.700872 | [
"vector"
] |
315c97d05deffe29c7b55d00d1039f24a49ae91f | 26,772 | hpp | C++ | include/poac/util/net.hpp | ken-matsui/poac | e4503027f3993be493824f48dc31818029784238 | [
"Apache-2.0"
] | null | null | null | include/poac/util/net.hpp | ken-matsui/poac | e4503027f3993be493824f48dc31818029784238 | [
"Apache-2.0"
] | null | null | null | include/poac/util/net.hpp | ken-matsui/poac | e4503027f3993be493824f48dc31818029784238 | [
"Apache-2.0"
] | null | null | null | #ifndef POAC_UTIL_NET_HPP
#define POAC_UTIL_NET_HPP
// std
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <string>
#include <string_view>
#include <sstream>
#include <numeric>
#include <map>
#include <unordered_map>
#include <memory>
#include <variant>
#include <optional>
// external
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/version.hpp>
#include <boost/beast/http.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <fmt/core.h>
#include <fmt/ranges.h>
#include <mitama/result/result.hpp>
#include <plog/Log.h>
// internal
#include <poac/config.hpp>
#include <poac/util/meta.hpp>
#include <poac/util/misc.hpp>
#include <poac/util/pretty.hpp>
namespace poac::util::net {
// Create progress bar, [====> ]
std::string to_progress(const int& max_count, int now_count, const int& bar_size = 50) {
if (now_count > max_count) {
now_count = max_count;
}
const int percent = (now_count * 100) / max_count;
const int bar_pos = percent / 2;
if (now_count == max_count) {
return fmt::format(FMT_STRING("[{:=>{}}"), ">]", bar_size + 1);
} else if ((bar_pos - 1) > 0) {
return fmt::format(FMT_STRING("[{:=>{}}{:>{}}"), ">", bar_pos, "]", bar_size - bar_pos + 1);
} else if (bar_pos == 1) {
return fmt::format(FMT_STRING("[>{:>{}}"), "]", bar_size);
} else {
return fmt::format(FMT_STRING("[{:>{}}"), "]", bar_size + 1);
}
}
// Create byte progress bar, [====> ] 10.21B/21.28KB
std::string to_byte_progress(const int& max_count, int now_count) {
if (now_count > max_count) {
now_count = max_count;
}
return fmt::format(
FMT_STRING("{} {}/{}"),
to_progress(max_count, now_count),
util::pretty::to_byte(now_count),
util::pretty::to_byte(max_count)
);
}
namespace http = boost::beast::http;
using headers_t =
std::unordered_map<
std::variant<
boost::beast::http::field,
std::string>,
std::string>;
template <typename RequestBody>
http::request<RequestBody>
create_request(
http::verb method,
const std::string_view target,
const std::string_view host,
const headers_t& headers={}
) {
// Set up an HTTP request message, 10 -> HTTP/1.0, 11 -> HTTP/1.1
http::request<RequestBody> req{ method, std::string(target), 11 };
req.set(http::field::host, std::string(host)); // no matching member function for call to 'set'
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
for (const auto& [field, value] : headers) {
std::visit([&, v=value](const auto& f) { req.set(f, v); }, field);
}
return req;
}
std::pair<std::string, std::string>
parse_url(const std::string& url) {
// https://api.poac.pm/packages/deps -> api.poac.pm
const std::string host = util::misc::split(url, "://")[1];
// https://api.poac.pm/packages/deps -> /packages/deps
const std::string target(url, url.find(host) + host.size());
return { host, target };
}
class multi_part_form_t {
public:
~multi_part_form_t() = default;
multi_part_form_t(const multi_part_form_t&) = default;
multi_part_form_t& operator=(const multi_part_form_t&) = default;
multi_part_form_t(multi_part_form_t&&) = default;
multi_part_form_t& operator=(multi_part_form_t&&) = default;
public:
using file_name_type = std::string;
using file_path_type = std::filesystem::path;
using header_type = std::map<http::field, std::string>;
using self_reference = multi_part_form_t&;
using const_self_reference = const multi_part_form_t&;
private:
std::string m_crlf = "\r\n";
std::string m_header;
std::string m_boundary;
std::string m_footer;
std::string m_content_disposition = "Content-Disposition: form-data; ";
std::vector<std::string> m_form_param;
std::vector<std::tuple<file_name_type, file_path_type, header_type>> m_file_param;
public:
multi_part_form_t()
: m_boundary(boost::uuids::to_string(boost::uuids::random_generator{}()))
, m_footer(fmt::format("{}--{}--{}", m_crlf, m_boundary, m_crlf))
{}
std::string
get_header() const noexcept {
return m_header;
}
std::string
get_footer() const noexcept {
return m_footer;
}
void set(const file_name_type& name, const std::string& value) {
using namespace fmt::literals;
m_form_param.emplace_back(
fmt::format(
"--{boundary}{crlf}{cd}name=\"{name}\"{crlf}{crlf}{value}",
"boundary"_a=m_boundary,
"crlf"_a=m_crlf,
"cd"_a=m_content_disposition,
"name"_a=name,
"value"_a=value
)
);
generate_header(); // re-generate
}
void set(const file_name_type& name, const file_path_type& value, const header_type& h) {
m_file_param.emplace_back(name, value, h);
generate_header(); // re-generate
}
template <typename Request>
void set_req(const Request& req) {
std::stringstream ss;
ss << req;
m_form_param.insert(m_form_param.begin(), ss.str());
generate_header(); // re-generate
}
std::string content_type() const {
return fmt::format("multipart/form-data; boundary={}", m_boundary);
}
std::uintmax_t content_length() const {
return std::accumulate(m_file_param.begin(), m_file_param.end(), m_header.size() + m_footer.size(),
[](std::uintmax_t acc, const auto& f) {
return acc + std::filesystem::file_size(std::get<1>(f));
}
);
}
struct file_info_t {
std::string path;
std::uintmax_t size;
};
std::vector<file_info_t>
get_files() const {
std::vector<file_info_t> file_info;
for (const auto& f : m_file_param) {
const std::filesystem::path file_path = std::get<1>(f);
file_info.push_back({file_path.string(), std::filesystem::file_size(file_path)});
}
return file_info;
}
self_reference
body() noexcept {
return *this;
}
const_self_reference
body() const noexcept {
return *this;
}
const_self_reference
cbody() const noexcept {
return *this;
}
private:
void generate_header() {
m_header = fmt::format("{}{}", m_crlf, fmt::join(m_form_param, ""));
for (const auto& [name, filename, header] : m_file_param) {
std::string h = fmt::format(
"--{}{}{}name=\"{}\"; filename=\"{}\"",
m_boundary,
m_crlf,
m_content_disposition,
name,
filename.filename().string()
);
for (const auto& [field, content] : header) {
h += fmt::format("{}{}: {}", m_crlf, field, content);
}
m_header += m_crlf + h;
}
m_header += m_crlf + m_crlf;
}
};
// TODO: ioc, ctx, resolver,...等はget等を呼び出し後,解体し,host等は残すことで,連続で呼び出し可能にする.
// Only SSL usage
class requests {
public:
requests() = delete;
~requests() = default;
requests(const requests&) = delete;
requests& operator=(const requests&) = delete;
requests(requests&&) = default;
requests& operator=(requests&&) = default;
explicit requests(const std::string_view host)
: host(host)
, ioc(std::make_unique<boost::asio::io_context>())
, ctx(std::make_unique<boost::asio::ssl::context>(
boost::asio::ssl::context::sslv23)
)
, resolver(std::make_unique<boost::asio::ip::tcp::resolver>(*ioc))
, stream(
std::make_unique<
boost::asio::ssl::stream<
boost::asio::ip::tcp::socket
>>(*ioc, *ctx)
)
{}
template <
http::verb method,
typename ResponseBody,
typename Request,
typename Ofstream>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
request(Request&& req, Ofstream&& ofs) const {
ssl_prepare();
write_request(req);
return read_response<method, ResponseBody>(
std::forward<Request>(req),
std::forward<Ofstream>(ofs)
);
}
template <
typename RequestBody = http::empty_body,
typename Ofstream = std::nullptr_t,
typename ResponseBody =
std::conditional_t<
std::is_same_v<
util::meta::remove_cvref_t<Ofstream>,
std::ofstream>,
http::vector_body<unsigned char>,
http::string_body>>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
get(
const std::string_view target,
const headers_t& headers={},
Ofstream&& ofs=nullptr
) const {
const auto req = create_request<RequestBody>(
http::verb::get, target, host, headers
);
PLOG_DEBUG << req;
return request<http::verb::get, ResponseBody>(
std::move(req), std::forward<Ofstream>(ofs)
);
}
template <
typename BodyType,
typename Ofstream = std::nullptr_t,
typename RequestBody =
std::conditional_t<
std::is_same_v<
util::meta::remove_cvref_t<BodyType>,
multi_part_form_t>,
http::empty_body,
http::string_body>,
typename ResponseBody =
std::conditional_t<
std::is_same_v<
util::meta::remove_cvref_t<Ofstream>,
std::ofstream>,
http::vector_body<unsigned char>,
http::string_body>>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
post(
const std::string_view target,
BodyType&& body,
const headers_t& headers={},
Ofstream&& ofs=nullptr
) const {
auto req = create_request<RequestBody>(
http::verb::post, target, host, headers
);
if constexpr (
!std::is_same_v<
util::meta::remove_cvref_t<BodyType>,
multi_part_form_t>
) {
req.set(http::field::content_type, "application/json");
req.body() = body;
req.prepare_payload();
return request<http::verb::post, ResponseBody>(
std::forward<decltype(req)>(req),
std::forward<Ofstream>(ofs)
);
} else {
req.set(http::field::accept, "*/*");
req.set(http::field::content_type, body.content_type());
req.set(http::field::content_length, body.content_length());
body.set_req(req);
return request<http::verb::post, ResponseBody>(
std::forward<BodyType>(body),
std::forward<Ofstream>(ofs)
);
}
}
private:
std::string port = "443";
std::string host;
// The io_context is required for all I/O
std::unique_ptr<boost::asio::io_context> ioc;
// The SSL context is required, and holds certificates
std::unique_ptr<boost::asio::ssl::context> ctx;
// These objects perform our I/O
std::unique_ptr<boost::asio::ip::tcp::resolver> resolver;
std::unique_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>> stream;
template <
typename Request,
std::enable_if_t<
std::negation_v<
std::is_same<
util::meta::remove_cvref_t<
Request
>,
multi_part_form_t
>>,
std::nullptr_t
> = nullptr>
void write_request(const Request& req) const {
PLOG_DEBUG << "[util::net::requests] write type: string";
// Send the HTTP request to the remote host
http::write(*stream, req);
}
template <
typename Request,
std::enable_if_t<
std::is_same_v<
util::meta::remove_cvref_t<
Request
>,
multi_part_form_t
>,
std::nullptr_t
> = nullptr>
void write_request(const Request& req) const {
PLOG_DEBUG << "[util::net::requests] write type: multipart/form-data";
// Send the HTTP request to the remote host
stream->write_some(boost::asio::buffer(req.get_header()));
// Read file and write to stream
// TODO: 複数のファイル送信を想定していない.
// TODO: -> 複数ファイルだと,req.headerをちょびちょびで送る必要がある.
for (const auto& file : req.get_files()) {
std::ifstream ifs(file.path, std::ios::in | std::ios::binary);
constexpr std::size_t read_bites = 512;
char buf[read_bites];
// unsigned long cur_file_size = 0;
while (!ifs.eof()) {
ifs.read(buf, read_bites);
stream->write_some(boost::asio::buffer(buf, ifs.gcount()));
// Print progress bar TODO:
// std::cout << '\r' << term::info << "Uploading ";
// term::echo_byte_progress(file.size, cur_file_size += read_bites);
// std::cout << " ";
}
// std::cout << '\r' << term::clr_line << term::info << "Uploaded." << std::endl;
}
// Send footer to stream
stream->write_some(boost::asio::buffer(req.get_footer()));
PLOG_DEBUG << "[util::net::requests] waiting for server response...";
}
template <
http::verb method,
typename ResponseBody,
typename Request,
typename Ofstream>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
read_response(Request&& old_req, Ofstream&& ofs) const {
// This buffer is used for reading and must be persisted
boost::beast::flat_buffer buffer;
// Declare a container to hold the response
http::response<ResponseBody> res;
// Receive the HTTP response
http::read(*stream, buffer, res);
// Handle HTTP status code
return handle_status<method>(
std::forward<Request>(old_req),
std::move(res),
std::forward<Ofstream>(ofs)
);
}
template <
http::verb method,
typename Request,
typename Response,
typename Ofstream,
typename ResponseBody = typename Response::body_type>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
handle_status(Request&& old_req, Response&& res, Ofstream&& ofs) const
{
close_stream();
switch (res.base().result_int() / 100) {
case 2:
return mitama::success(parse_response(
std::forward<Response>(res),
std::forward<Ofstream>(ofs)
));
case 3:
return redirect<method>(
std::forward<Request>(old_req),
std::forward<Response>(res),
std::forward<Ofstream>(ofs)
);
default:
if constexpr (!std::is_same_v<util::meta::remove_cvref_t<Ofstream>, std::ofstream>) {
return mitama::failure(fmt::format(
"util::net received a bad response code: {}\n{}",
res.base().result_int(), res.body()
));
} else {
throw mitama::failure(fmt::format(
"util::net received a bad response code: {}",
res.base().result_int()
));
}
}
}
template <
typename Response,
typename Ofstream,
typename ResponseBody = typename Response::body_type>
typename ResponseBody::value_type
parse_response(Response&& res, Ofstream&& ofs) const {
if constexpr (!std::is_same_v<util::meta::remove_cvref_t<Ofstream>, std::ofstream>) {
PLOG_DEBUG << "[util::net::requests] read type: string";
return res.body();
} else {
PLOG_DEBUG << "[util::net::requests] read type: file with progress";
const typename ResponseBody::value_type response_body = res.body();
const auto content_length = response_body.size();
if (content_length < 100'000 /* 100KB */) {
for (const auto& r : response_body) {
ofs << r;
}
} else {
int acc = 0;
for (const auto& r : response_body) {
ofs << r;
if (++acc % 100 == 0) {
// To be accurate, not downloading.
IF_PLOG(plog::verbose) {
std::cout << '\r' << "Downloading "
<< to_byte_progress(content_length, acc)
<< " ";
}
}
}
}
return {};
}
}
template <
http::verb method,
typename Request,
typename Response,
typename Ofstream,
typename ResponseBody = typename Response::body_type>
[[nodiscard]] mitama::result<typename ResponseBody::value_type, std::string>
redirect(Request&& old_req, Response&& res, Ofstream&& ofs) const {
const std::string new_location(res.base()["Location"]);
const auto [new_host, new_target] = parse_url(new_location);
PLOG_DEBUG << fmt::format("Redirect to {}\n", new_location);
// FIXME: header information is gone.
const requests req(new_host);
if constexpr (method == http::verb::get) {
return req.get(new_target, {}, std::forward<Ofstream>(ofs));
} else if (method == http::verb::post) {
return req.post(new_target, old_req.body(), {}, std::forward<Ofstream>(ofs));
} else { // verb error
return mitama::failure("[util::net::requests] unknown verb used");
}
}
void close_stream() const {
// Gracefully close the stream
boost::system::error_code error;
stream->shutdown(error);
if (error == boost::asio::error::eof) {
// Rationale: https://stackoverflow.com/q/25587403
error.assign(0, error.category());
}
}
// Prepare ssl connection
void ssl_prepare() const {
ssl_set_tlsext();
lookup();
ssl_handshake();
}
void ssl_set_tlsext() const {
// Set SNI Hostname (many hosts need this to handshake successfully)
if(!SSL_set_tlsext_host_name(stream->native_handle(), std::string(host).c_str()))
{
boost::system::error_code error{
static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()
};
PLOG_DEBUG << error.message();
throw boost::system::system_error{ error };
}
}
void lookup() const {
// Look up the domain name
const auto results = resolver->resolve(host, port);
// Make the connection on the IP address we get from a lookup
boost::asio::connect(stream->next_layer(), results.begin(), results.end());
}
void ssl_handshake() const {
// Perform the SSL handshake
stream->handshake(boost::asio::ssl::stream_base::client);
}
};
} // end namespace
namespace poac::util::net::api {
[[nodiscard]] mitama::result<boost::property_tree::ptree, std::string>
search_impl(std::string_view body) noexcept {
try {
const requests request{ALGOLIA_SEARCH_INDEX_API_HOST};
headers_t headers;
headers.emplace("X-Algolia-API-Key", ALGOLIA_SEARCH_ONLY_KEY);
headers.emplace("X-Algolia-Application-Id", ALGOLIA_APPLICATION_ID);
const auto response = MITAMA_TRY(request.post(ALGOLIA_SEARCH_INDEX_API, body, headers));
std::stringstream response_body;
response_body << response.data();
boost::property_tree::ptree pt;
boost::property_tree::json_parser::read_json(response_body, pt);
return mitama::success(pt);
} catch (const std::exception& e) {
return mitama::failure(e.what());
} catch (...) {
return mitama::failure("unknown error caused when calling search api");
}
}
[[nodiscard]] mitama::result<boost::property_tree::ptree, std::string>
search(std::string_view query, const std::uint64_t& count = 0) noexcept {
boost::property_tree::ptree pt;
const std::string hits_per_page =
count != 0 ? fmt::format("&hitsPerPage={}", count) : "";
const std::string params = fmt::format("query={}{}", query, hits_per_page);
pt.put("params", params);
std::stringstream body;
boost::property_tree::json_parser::write_json(body, pt);
return search_impl(body.str());
}
[[nodiscard]] mitama::result<boost::property_tree::ptree, std::string>
all_indices() noexcept {
// ref: https://www.algolia.com/doc/
// guides/sending-and-managing-data/manage-your-indices/
// how-to/export-an-algolia-index/#exporting-the-index
// You can use an empty query to indicate
// that you want to retrieve all records.
return search("");
}
[[nodiscard]] auto
deps(std::string_view name, std::string_view version)
noexcept
-> mitama::result<
std::unordered_map<std::string, std::string>,
std::string>
{
const boost::property_tree::ptree res = MITAMA_TRY(search(name));
IF_PLOG(plog::debug) {
boost::property_tree::json_parser::write_json(std::cout, res);
}
for (const auto& child : res.get_child("hits")) {
const boost::property_tree::ptree& hits = child.second;
if (hits.get<std::string>("package.name") == name &&
hits.get<std::string>("package.version") == version)
{
return mitama::success(
util::meta::to_unordered_map<std::string>(
hits, "dependencies"
)
);
}
}
return mitama::failure(
fmt::format("no such package `{}: {}`", name, version)
);
}
[[nodiscard]] mitama::result<std::vector<std::string>, std::string>
versions(std::string_view name) {
const boost::property_tree::ptree res = MITAMA_TRY(search(name));
IF_PLOG(plog::debug) {
boost::property_tree::json_parser::write_json(std::cout, res);
}
std::vector<std::string> results;
for (const auto& child : res.get_child("hits")) {
const boost::property_tree::ptree& hits = child.second;
if (hits.get<std::string>("package.name") == name) {
results.emplace_back(hits.get<std::string>("package.version"));
}
}
PLOG_DEBUG <<
fmt::format(
"[util::net::api::versions] versions of {} are [{}]",
name, fmt::join(results, ", ")
);
return mitama::success(results);
}
[[nodiscard]] mitama::result<std::string, std::string>
package_repository(std::string_view name, std::string_view version) {
const boost::property_tree::ptree res = MITAMA_TRY(search(name));
IF_PLOG(plog::debug) {
boost::property_tree::json_parser::write_json(std::cout, res);
}
for (const auto& child : res.get_child("hits")) {
const boost::property_tree::ptree& hits = child.second;
if (hits.get<std::string>("package.name") == name &&
hits.get<std::string>("package.version") == version)
{
return mitama::success(
hits.get<std::string>("package.repository")
);
}
}
return mitama::failure(
fmt::format("no such package `{}: {}`", name, version)
);
}
} // end namespace
#endif // !POAC_UTIL_NET_HPP
| 38.082504 | 111 | 0.519311 | [
"vector"
] |
315f4d2b43b5037985c1c930ea1d2d075aa86429 | 2,795 | cc | C++ | chrome/browser/ui/app_list/crostini/crostini_app_item.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/app_list/crostini/crostini_app_item.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/app_list/crostini/crostini_app_item.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/crostini/crostini_app_item.h"
#include <utility>
#include "ash/public/cpp/app_list/app_list_constants.h"
#include "base/bind.h"
#include "chrome/browser/chromeos/crostini/crostini_util.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/app_list/crostini/crostini_app_context_menu.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#include "content/public/browser/browser_thread.h"
// static
const char CrostiniAppItem::kItemType[] = "CrostiniAppItem";
CrostiniAppItem::CrostiniAppItem(
Profile* profile,
AppListModelUpdater* model_updater,
const app_list::AppListSyncableService::SyncItem* sync_item,
const std::string& id,
const std::string& name)
: ChromeAppListItem(profile, id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
crostini_app_icon_.reset(
new CrostiniAppIcon(profile, id, app_list::kTileIconSize, this));
SetName(name);
UpdateIcon();
if (sync_item && sync_item->item_ordinal.IsValid()) {
UpdateFromSync(sync_item);
} else {
SetDefaultPositionIfApplicable();
}
// Set model updater last to avoid being called during construction.
set_model_updater(model_updater);
}
CrostiniAppItem::~CrostiniAppItem() {}
const char* CrostiniAppItem::GetItemType() const {
return CrostiniAppItem::kItemType;
}
void CrostiniAppItem::Activate(int event_flags) {
ChromeLauncherController::instance()->ActivateApp(
id(), ash::LAUNCH_FROM_APP_LIST, event_flags);
// TODO(timloh): Launching Crostini apps can take a few seconds if the
// container is not currently running. Hiding the launcher at least provides
// the user some feedback that they actually clicked an icon. We should make
// this better, e.g. by showing some sort of spinner. We also need to handle
// failures to start the container or app, as those are currently ignored.
if (!GetController()->IsHomeLauncherEnabledInTabletMode())
GetController()->DismissView();
}
void CrostiniAppItem::GetContextMenuModel(GetMenuModelCallback callback) {
context_menu_ = std::make_unique<CrostiniAppContextMenu>(profile(), id(),
GetController());
context_menu_->GetMenuModel(std::move(callback));
}
app_list::AppContextMenu* CrostiniAppItem::GetAppContextMenu() {
return context_menu_.get();
}
void CrostiniAppItem::UpdateIcon() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
SetIcon(crostini_app_icon_->image_skia());
}
void CrostiniAppItem::OnIconUpdated(CrostiniAppIcon* icon) {
UpdateIcon();
}
| 34.9375 | 78 | 0.748837 | [
"model"
] |
316042187ab3ef703dae1407b89b1334f01078a2 | 694 | hpp | C++ | player/playerlib/reader/ReaderStreamManager.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/reader/ReaderStreamManager.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/reader/ReaderStreamManager.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | #ifndef _STREAM_MANAGER_INTERFACE_HPP_
#define _STREAM_MANAGER_INTERFACE_HPP_
#include <ref/FFL_Ref.hpp>
#include "Stream.hpp"
namespace reader{
class ReaderBase;
class ReaderStreamManager {
public:
//
// 添加reader下的一个stream到管理中,返回当前这个stream的id
//
virtual int32_t addStream(ReaderBase* reader, StreamPtr stream) = 0;
//
// 添加reader下的所有stream到管理中,返回成功添加了几个流
//
//
virtual uint32_t addStreamVec(ReaderBase* reader, FFL::Vector < StreamPtr > streamVec) = 0;
//
// 根据流id获取一个流实例
//
virtual StreamPtr getStream(int32_t id) = 0;
//
// 获取这个reader下的所有流
//
virtual void getStreamVec(ReaderBase* reader, FFL::Vector < StreamPtr >& streamVec) = 0;
};
}
#endif
| 22.387097 | 93 | 0.716138 | [
"vector"
] |
3163e5fdcf890676c45dd320ee2b88b28020e4fc | 2,617 | cpp | C++ | Examples/DroppingBalls/AddRandomSphereBehavior.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 24 | 2015-01-19T16:18:59.000Z | 2022-03-13T03:29:11.000Z | Examples/DroppingBalls/AddRandomSphereBehavior.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 3 | 2018-12-21T14:54:08.000Z | 2022-03-14T12:38:07.000Z | Examples/DroppingBalls/AddRandomSphereBehavior.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 8 | 2015-04-10T19:45:36.000Z | 2022-02-02T17:00:59.000Z | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <string>
#include <sstream>
#include <stdlib.h>
#include "Examples/DroppingBalls/AddRandomSphereBehavior.h"
#include "SurgSim/Framework/Behavior.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Blocks/SphereElement.h"
#include "SurgSim/Math/Vector.h"
using SurgSim::Blocks::SphereElement;
using SurgSim::Framework::Behavior;
using SurgSim::Framework::SceneElement;
using SurgSim::Math::Vector3d;
/// \file
/// A Behavior that creates randomly positioned SphereElements at a fixed rate.
/// \sa SurgSim::Blocks::SphereElement
namespace SurgSim
{
namespace Blocks
{
AddRandomSphereBehavior::AddRandomSphereBehavior(const std::string& name):
Behavior(name), m_totalTime(0.0), m_numElements(0),
m_distribution_xz(0.0, 1.0), m_distribution_y(1.0, 2.0)
{
}
AddRandomSphereBehavior::~AddRandomSphereBehavior()
{
}
bool AddRandomSphereBehavior::doInitialize()
{
return true;
}
bool AddRandomSphereBehavior::doWakeUp()
{
return true;
}
void AddRandomSphereBehavior::update(double dt)
{
// Accumulate the time steps since the previous sphere was created.
m_totalTime += dt;
if (m_totalTime > 3.0)
{
m_totalTime = 0.0;
std::stringstream ss;
ss << ++ m_numElements;
// Generate a random position.
double m_x = m_distribution_xz(m_generator);
double m_y = m_distribution_y(m_generator);
double m_z = m_distribution_xz(m_generator);
std::string name = "sphereId_" + ss.str();
// Create the pose, with no rotation and the previously determined position.
SurgSim::Math::RigidTransform3d pose = SurgSim::Math::makeRigidTransform
(SurgSim::Math::Quaterniond::Identity(), Vector3d(m_x, m_y, m_z));
// Create the SphereElement.
std::shared_ptr<SceneElement> element = std::make_shared<SphereElement>(name);
element->setPose(pose);
// Add the SphereElement to the Scene.
getScene()->addSceneElement(element);
}
}
}; // namespace Blocks
}; // namespace SurgSim
| 26.979381 | 80 | 0.746274 | [
"vector"
] |
3165918911ff712ab557c4c92c67f1e2ce9730ac | 11,202 | hpp | C++ | source/TouhouDanmakufu/Common/StgItem.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | source/TouhouDanmakufu/Common/StgItem.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | source/TouhouDanmakufu/Common/StgItem.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | #pragma once
#include "../../GcLib/pch.h"
#include "StgCommon.hpp"
#include "StgIntersection.hpp"
//#include "StgShot.hpp"
class StgShotVertexBufferContainer;
class StgItemDataList;
class StgItemData;
struct StgItemDataFrame;
class StgItemObject;
//*******************************************************************
//StgItemManager
//*******************************************************************
class StgItemManager {
friend class StgItemRenderer;
public:
enum {
ITEM_MAX = 10000,
BLEND_COUNT = 8,
};
protected:
static std::array<BlendMode, BLEND_COUNT> blendTypeRenderOrder;
struct RenderQueue {
size_t count;
std::vector<StgItemObject*> listItem;
};
protected:
StgStageController* stageController_;
unique_ptr<SpriteList2D> listSpriteItem_;
unique_ptr<SpriteList2D> listSpriteDigit_;
unique_ptr<StgItemDataList> listItemData_;
std::list<ref_unsync_ptr<StgItemObject>> listObj_;
std::vector<RenderQueue> listRenderQueue_; //one for each render pri
std::list<DxCircle> listCircleToPlayer_;
DxRect<LONG> rcDeleteClip_;
D3DTEXTUREFILTERTYPE filterMin_;
D3DTEXTUREFILTERTYPE filterMag_;
bool bAllItemToPlayer_;
bool bCancelToPlayer_;
bool bDefaultBonusItemEnable_;
ID3DXEffect* effectItem_;
D3DXMATRIX matProj_;
public:
IDirect3DTexture9* pLastTexture_;
public:
StgItemManager(StgStageController* stageController);
virtual ~StgItemManager();
void Work();
void Render(int targetPriority);
void LoadRenderQueue();
void AddItem(ref_unsync_ptr<StgItemObject> obj) {
listObj_.push_back(obj);
}
size_t GetItemCount() { return listObj_.size(); }
ID3DXEffect* GetEffect() { return effectItem_; }
D3DXMATRIX* GetProjectionMatrix() { return &matProj_; }
SpriteList2D* GetItemRenderer() { return listSpriteItem_.get(); }
SpriteList2D* GetDigitRenderer() { return listSpriteDigit_.get(); }
StgItemDataList* GetItemDataList() { return listItemData_.get(); }
bool LoadItemData(const std::wstring& path, bool bReload = false);
ref_unsync_ptr<StgItemObject> CreateItem(int type);
void SetItemDeleteClip(const DxRect<LONG>& clip) { rcDeleteClip_ = clip; }
DxRect<LONG>* GetItemDeleteClip() { return &rcDeleteClip_; }
void SetTextureFilter(D3DTEXTUREFILTERTYPE min, D3DTEXTUREFILTERTYPE mag) {
filterMin_ = min;
filterMag_ = mag;
}
void CollectItemsAll();
void CollectItemsInCircle(const DxCircle& circle);
void CancelCollectItems();
std::vector<int> GetItemIdInCircle(int cx, int cy, int radius, int* itemType);
bool IsDefaultBonusItemEnable() { return bDefaultBonusItemEnable_; }
void SetDefaultBonusItemEnable(bool bEnable) { bDefaultBonusItemEnable_ = bEnable; }
};
//*******************************************************************
//StgItemDataList
//*******************************************************************
class StgItemDataList {
public:
//Repurpose StgShotVertexBufferContainer for this, since it'd have been the same code anyway
using VBContainerList = std::list<unique_ptr<StgShotVertexBufferContainer>>;
private:
std::map<std::wstring, VBContainerList> mapVertexBuffer_; //<shot data file, vb list>
std::vector<unique_ptr<StgItemData>> listData_;
void _ScanItem(std::map<int, unique_ptr<StgItemData>>& mapData, Scanner& scanner);
static void _ScanAnimation(StgItemData* itemData, Scanner& scanner);
void _LoadVertexBuffers(std::map<std::wstring, VBContainerList>::iterator placement,
shared_ptr<Texture> texture, std::vector<StgItemData*>& listAddData);
public:
StgItemDataList();
virtual ~StgItemDataList();
StgItemData* GetData(int id) { return (id >= 0 && id < listData_.size()) ? listData_[id].get() : nullptr; }
bool AddItemDataList(const std::wstring& path, bool bReload);
};
//*******************************************************************
//StgItemData
//*******************************************************************
class StgItemData {
friend StgItemDataList;
private:
StgItemDataList* listItemData_;
int typeItem_;
BlendMode typeRender_;
int alpha_;
unique_ptr<StgItemData> dataOut_;
std::vector<StgItemDataFrame> listFrame_;
size_t totalFrame_;
public:
StgItemData(StgItemDataList* listItemData);
virtual ~StgItemData();
int GetItemType() { return typeItem_; }
BlendMode GetRenderType() { return typeRender_; }
int GetAlpha() { return alpha_; }
StgItemData* GetOutData() { return dataOut_.get(); }
StgItemDataFrame* GetFrame(size_t frame);
size_t GetFrameCount() { return listFrame_.size(); }
};
struct StgItemDataFrame {
StgItemDataList* listItemData_;
StgShotVertexBufferContainer* pVertexBuffer_;
DWORD vertexOffset_;
DxRect<LONG> rcSrc_;
DxRect<float> rcDst_;
size_t frame_;
public:
StgItemDataFrame();
DxRect<LONG>* GetSourceRect() { return &rcSrc_; }
DxRect<float>* GetDestRect() { return &rcDst_; }
StgShotVertexBufferContainer* GetVertexBufferContainer() {
return pVertexBuffer_;
}
static DxRect<float> LoadDestRect(DxRect<LONG>* src);
};
//*******************************************************************
//StgItemObject
//*******************************************************************
class StgItemObject : public DxScriptShaderObject, public StgMoveObject, public StgIntersectionObject {
friend class StgItemManager;
public:
enum {
ITEM_1UP = -256 * 256,
ITEM_1UP_S,
ITEM_SPELL,
ITEM_SPELL_S,
ITEM_POWER,
ITEM_POWER_S,
ITEM_POINT,
ITEM_POINT_S,
ITEM_SCORE,
ITEM_BONUS,
ITEM_USER = 0,
COLLECT_PLAYER_SCOPE = 0,
COLLECT_PLAYER_LINE,
COLLECT_IN_CIRCLE,
COLLECT_ALL,
COLLECT_SINGLE,
CANCEL_PLAYER_DOWN = 0,
CANCEL_ALL,
CANCEL_SINGLE,
};
enum {
FLAG_MOVETOPL_NONE = 0x0,
FLAG_MOVETOPL_PLAYER_SCOPE = 0x1,
FLAG_MOVETOPL_COLLECT_ALL = 0x2,
FLAG_MOVETOPL_POC_LINE = 0x4,
FLAG_MOVETOPL_COLLECT_CIRCLE = 0x8,
FLAG_MOVETOPL_ALL = 0x1 | 0x2 | 0x4 | 0x8,
};
protected:
StgStageController* stageController_;
int typeItem_;
//D3DCOLOR color_;
int frameWork_;
int64_t score_;
bool bMoveToPlayer_; //Is the item supposed to be homing in on the player right now?
int moveToPlayerFlags_; //MoveToPlayer permissions
bool bDefaultScoreText_;
bool bAutoDelete_;
bool bIntersectEnable_;
uint32_t itemIntersectRadius_;
bool bDefaultCollectionMove_;
bool bRoundingPosition_;
protected:
void _DeleteInAutoClip();
void _CreateScoreItem();
void _NotifyEventToPlayerScript(gstd::value* listValue, size_t count);
void _NotifyEventToItemScript(gstd::value* listValue, size_t count);
public:
StgItemObject(StgStageController* stageController);
virtual bool HasNormalRendering() { return false; }
virtual void Work();
virtual void Activate() {}
virtual void SetRenderState() {}
virtual void Render() {};
virtual void Render(BlendMode targetBlend) {};
virtual void RenderOnItemManager();
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget) = 0;
virtual void SetX(float x) { posX_ = x; DxScriptRenderObject::SetX(x); }
virtual void SetY(float y) { posY_ = y; DxScriptRenderObject::SetY(y); }
virtual void SetColor(int r, int g, int b);
virtual void SetAlpha(int alpha);
void SetToPosition(D3DXVECTOR2& pos);
int GetFrameWork() { return frameWork_; }
int GetItemType() { return typeItem_; }
void SetItemType(int type) { typeItem_ = type; }
int64_t GetScore() { return score_; }
void SetScore(int64_t score) { score_ = score; }
bool IsMoveToPlayer() { return bMoveToPlayer_; }
void SetMoveToPlayer(bool b) { bMoveToPlayer_ = b; }
int GetMoveToPlayerEnableFlags() { return moveToPlayerFlags_; }
void SetMoveToPlayerEnableFlags(int moveFlags) { moveToPlayerFlags_ = moveFlags; }
void SetDefaultScoreText(bool b) { bDefaultScoreText_ = b; }
void SetAutoDelete(bool b) { bAutoDelete_ = b; }
void SetIntersectionEnable(bool b) { bIntersectEnable_ = b; }
void SetIntersectionRadius(int r) { itemIntersectRadius_ = r * r; }
bool IsIntersectionEnable() { return bIntersectEnable_; }
bool IsDefaultCollectionMovement() { return bDefaultCollectionMove_; }
void SetDefaultCollectionMovement(bool b) { bDefaultCollectionMove_ = b; }
void SetPositionRounding(bool b) { bRoundingPosition_ = b; }
int GetMoveType();
void SetMoveType(int type);
void NotifyItemCollectEvent(int type, uint64_t eventParam);
void NotifyItemCancelEvent(int type);
StgStageController* GetStageController() { return stageController_; }
};
class StgItemObject_1UP : public StgItemObject {
public:
StgItemObject_1UP(StgStageController* stageController);
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_Bomb : public StgItemObject {
public:
StgItemObject_Bomb(StgStageController* stageController);
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_Power : public StgItemObject {
public:
StgItemObject_Power(StgStageController* stageController);
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_Point : public StgItemObject {
public:
StgItemObject_Point(StgStageController* stageController);
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_Bonus : public StgItemObject {
public:
StgItemObject_Bonus(StgStageController* stageController);
virtual void Work();
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_ScoreText : public StgItemObject {
int frameDelete_;
public:
StgItemObject_ScoreText(StgStageController* stageController);
virtual void Work();
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
};
class StgItemObject_User : public StgItemObject {
int frameWork_;
int idImage_;
weak_ptr<Texture> renderTarget_;
protected:
inline StgItemData* _GetItemData();
public:
StgItemObject_User(StgStageController* stageController);
virtual void Work();
virtual void Render(BlendMode targetBlend);
virtual void RenderOnItemManager() {};
virtual void SetRenderTarget(shared_ptr<Texture> texture) { renderTarget_ = texture; }
virtual void Intersect(StgIntersectionTarget* ownTarget, StgIntersectionTarget* otherTarget);
void SetImageID(int id);
};
//*******************************************************************
//StgMovePattern_Item
//*******************************************************************
class StgMovePattern_Item : public StgMovePattern {
public:
enum {
MOVE_NONE,
MOVE_TOPOSITION_A, //Move to the specified target position
MOVE_DOWN, //Downwards, default
MOVE_TOPLAYER, //Yeet to player
MOVE_SCORE, //Yeet to player but score
};
protected:
int frame_;
int typeMove_;
double speed_;
double angDirection_;
D3DXVECTOR2 posTo_;
public:
StgMovePattern_Item(StgMoveObject* target);
virtual void Move();
int GetType() { return TYPE_OTHER; }
virtual double GetSpeed() { return speed_; }
virtual double GetDirectionAngle() { return angDirection_; }
void SetToPosition(D3DXVECTOR2& pos) { posTo_ = pos; }
int GetItemMoveType() { return typeMove_; }
void SetItemMoveType(int type) { typeMove_ = type; }
};
| 28.075188 | 108 | 0.725763 | [
"render",
"vector"
] |
317312870fd912e996192192ad0e5e0b7483e171 | 1,345 | cpp | C++ | Uncategorized/tle16c7p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/tle16c7p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/tle16c7p4.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define gc getchar()
#define pc(x) putchar(x)
template<typename T> void scan(T &x){x = 0;bool _=0;T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void printn(T n){bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=char(n%10+48);n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);}
template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);}
template<typename T> void print(T n){printn(n);pc(10);}
template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);}
using namespace std;
using ll = long long;
int main(){
int t; ll x;
scan(t);
while(t--){
scan(x);
int n = (int)__lg(x)+1;
vector<vector<int>> dp(2, vector<int>(n+1, 99));
vector<bool> a(n+1);
dp[0][n] = 0;
dp[1][n] = 2; //on + extra shift
for(int i = n-1; i >= 0; i--){
a[i] = x&(1LL<<i);
dp[0][i] = dp[a[i+1]][i+1];
dp[1][i] = dp[a[i+1]][i+1]+1;
for(int j = i+1; j <= n; j++){
if(a[j] == 0){
dp[1][i] = min(dp[1][i], dp[1][j]+1);
//"pop" that one bit to fill these
break;
}
}
}
print(dp[a[0]][0]+n-1);
}
} | 34.487179 | 175 | 0.533829 | [
"vector"
] |
3177d43792a52e2dbed638cd2bf8855775043039 | 5,847 | cc | C++ | TopQuarkAnalysis/TopJetCombination/plugins/TtFullLepHypGenMatch.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | TopQuarkAnalysis/TopJetCombination/plugins/TtFullLepHypGenMatch.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | TopQuarkAnalysis/TopJetCombination/plugins/TtFullLepHypGenMatch.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "TopQuarkAnalysis/TopJetCombination/plugins/TtFullLepHypGenMatch.h"
#include "AnalysisDataFormats/TopObjects/interface/TtFullLepEvtPartons.h"
#include "DataFormats/Math/interface/deltaR.h"
TtFullLepHypGenMatch::TtFullLepHypGenMatch(const edm::ParameterSet& cfg):
TtFullLepHypothesis( cfg ),
genEvtToken_( consumes<TtGenEvent>( edm::InputTag( "genEvt" ) ) )
{
}
TtFullLepHypGenMatch::~TtFullLepHypGenMatch() { }
void
TtFullLepHypGenMatch::buildHypo(edm::Event& evt,
const edm::Handle<std::vector<pat::Electron > >& elecs,
const edm::Handle<std::vector<pat::Muon> >& mus,
const edm::Handle<std::vector<pat::Jet> >& jets,
const edm::Handle<std::vector<pat::MET> >& mets,
std::vector<int>& match,
const unsigned int iComb)
{
// -----------------------------------------------------
// add jets
// -----------------------------------------------------
for(unsigned idx=0; idx<match.size(); ++idx){
if( isValid(match[idx], jets) ){
switch(idx){
case TtFullLepEvtPartons::B:
setCandidate(jets, match[idx], b_ , jetCorrectionLevel_); break;
case TtFullLepEvtPartons::BBar:
setCandidate(jets, match[idx], bBar_, jetCorrectionLevel_); break;
}
}
}
// -----------------------------------------------------
// add leptons
// -----------------------------------------------------
// get genEvent
edm::Handle<TtGenEvent> genEvt;
evt.getByToken(genEvtToken_, genEvt);
// push back fake indices if no leptons in genevent
if( !genEvt->isFullLeptonic() || !genEvt->lepton() || !genEvt->leptonBar() ){
match.push_back( -1 );
match.push_back( -1 );
match.push_back( -1 );
match.push_back( -1 );
}
else if(genEvt->isFullLeptonic(WDecay::kElec, WDecay::kElec) && elecs->size()>=2){
//search indices for electrons
int iLepBar = findMatchingLepton(genEvt->leptonBar(), elecs);
setCandidate(elecs, iLepBar, leptonBar_);
match.push_back( iLepBar );
int iLep = findMatchingLepton(genEvt->lepton(), elecs);
setCandidate(elecs, iLep, lepton_);
match.push_back( iLep );
// fake indices for muons
match.push_back( -1 );
match.push_back( -1 );
}
else if(genEvt->isFullLeptonic(WDecay::kElec, WDecay::kMuon) && !elecs->empty() && !mus->empty() ){
if(genEvt->leptonBar()->isElectron()){
// push back index for e+
int iLepBar = findMatchingLepton(genEvt->leptonBar(), elecs);
setCandidate(elecs, iLepBar, leptonBar_);
match.push_back( iLepBar );
// push back fake indices for e- and mu+
match.push_back( -1 );
match.push_back( -1 );
// push back index for mu-
int iLep = findMatchingLepton(genEvt->lepton(), mus);
setCandidate(mus, iLep, lepton_);
match.push_back( iLep );
}
else{
// push back fake index for e+
match.push_back( -1 );
// push back index for e-
int iLepBar = findMatchingLepton(genEvt->leptonBar(), mus);
setCandidate(mus, iLepBar, leptonBar_);
match.push_back( iLepBar );
// push back index for mu+
int iLep = findMatchingLepton(genEvt->lepton(), elecs);
setCandidate(elecs, iLep, lepton_);
match.push_back( iLep );
// push back fake index for mu-
match.push_back( -1 );
}
}
else if(genEvt->isFullLeptonic(WDecay::kMuon, WDecay::kMuon) && mus->size()>=2 ){
// fake indices for electrons
match.push_back( -1 );
match.push_back( -1 );
//search indices for electrons
int iLepBar = findMatchingLepton(genEvt->leptonBar(), mus);
setCandidate(mus, iLepBar, leptonBar_);
match.push_back( iLepBar );
int iLep = findMatchingLepton(genEvt->lepton(), mus);
setCandidate(mus, iLep, lepton_);
match.push_back( iLep );
}
else{ //this 'else' should happen if at least one genlepton is a tau
match.push_back( -1 );
match.push_back( -1 );
match.push_back( -1 );
match.push_back( -1 );
}
// -----------------------------------------------------
// add met and neutrinos
// -----------------------------------------------------
if( !mets->empty() ){
//setCandidate(mets, 0, met_);
buildMatchingNeutrinos(evt, mets);
}
}
template <typename O>
int
TtFullLepHypGenMatch::findMatchingLepton(const reco::GenParticle* genLep, const edm::Handle<std::vector<O> >& leps)
{
int idx=-1;
double minDR = -1;
for(unsigned i=0; i<leps->size(); ++i){
double dR = deltaR(genLep->eta(), genLep->phi(), (*leps)[i].eta(), (*leps)[i].phi());
if(minDR<0 || dR<minDR){
minDR=dR;
idx=i;
}
}
return idx;
}
void
TtFullLepHypGenMatch::buildMatchingNeutrinos(edm::Event& evt, const edm::Handle<std::vector<pat::MET> >& mets)
{
// get genEvent
edm::Handle<TtGenEvent> genEvt;
evt.getByToken(genEvtToken_, genEvt);
if( genEvt->isTtBar() && genEvt->isFullLeptonic() && genEvt->neutrino() && genEvt->neutrinoBar() ){
double momXNu = genEvt->neutrino() ->px();
double momYNu = genEvt->neutrino() ->py();
double momXNuBar = genEvt->neutrinoBar()->px();
double momYNuBar = genEvt->neutrinoBar()->py();
double momXMet = mets->at(0).px();
double momYMet = mets->at(0).py();
double momXNeutrino = 0.5*(momXNu - momXNuBar + momXMet);
double momYNeutrino = 0.5*(momYNu - momYNuBar + momYMet);
double momXNeutrinoBar = momXMet - momXNeutrino;
double momYNeutrinoBar = momYMet - momYNeutrino;
math::XYZTLorentzVector recNuFM(momXNeutrino,momYNeutrino,0,sqrt(momXNeutrino * momXNeutrino + momYNeutrino * momYNeutrino));
recNu = new reco::LeafCandidate(0,recNuFM);
math::XYZTLorentzVector recNuBarFM(momXNeutrinoBar,momYNeutrinoBar,0,sqrt(momXNeutrinoBar * momXNeutrinoBar + momYNeutrinoBar * momYNeutrinoBar));
recNuBar = new reco::LeafCandidate(0,recNuBarFM);
}
}
| 35.436364 | 150 | 0.616898 | [
"vector"
] |
317dae1cbf95f52e6c482b46ef88fd246227cf35 | 1,883 | hpp | C++ | src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/Structure/BinaryIndexedTree.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/Structure/BinaryIndexedTree.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/Structure/BinaryIndexedTree.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | #pragma once
#include <cassert>
#include <cstdint>
#include <iostream>
#include <vector>
template<class R = int64_t>
class BinaryIndexedTree {
const std::vector<R> &original;
std::vector<R> tree;
constexpr static int low_bit(int a) { return a & (-a); }
public:
explicit BinaryIndexedTree(const std::vector<R> &original) : original{original}, tree{original} {
for (int i = 1; i <= size(); ++i) {
//method 1: definition
for (int j = 1; j < low_bit(i); ++j) {
tree[i] += original[i - j];
}
//method 2: incorrect
// for (int j = 1; j < low_bit(i)>>1; ++j) {
// tree[i] += tree[i - j];
// }
}
//method 3: 与其让我去加他,不如让他来加我(这种方法慢,tle)
// for (int i = 1; i <= size(); ++i) {
// for (int j = i+1; j <= size(); j+=low_bit(j)-1) {
// tree[j]+=original[i];
// }
// }
}
// void addAmong(int first, int last, R value) {
// add(first, value);
// add(last + 1, -value);
// }
void add(int index, R value) {
for (; index <= size(); index += low_bit(index)) {
tree[index] += value;//我的low_bit左移一位的那个节点,包括了我所包括的。因此我要提醒它更新。
}
}
[[nodiscard]] R sumTo(int last) const {
R ans{0};
for (; last != 0; last -= low_bit(last)) {//之前答案管辖了low_bit个答案,没有管辖到前面的。
ans += tree[last]; // 当前是在答案中的,要加进去。
}
return ans;
}
[[nodiscard]] R get(int index) const {
return sumTo(index) - sumTo(index - 1);
}
[[nodiscard]] R sumAmong(int first, int last) const {
return sumTo(last) - sumTo(first - 1);
}
[[nodiscard]] int size() const noexcept {
return tree.size() - 1;//0不用的。
}
};
| 33.035088 | 101 | 0.473181 | [
"vector"
] |
31901387a0d46d67bc7883fafa585379c59b4d0d | 17,304 | cpp | C++ | src/tracking/tracking.cpp | sridhargunnam/tracking | 6ac997d407a2fe6090f1f87292b7218c31c9f4a9 | [
"Unlicense"
] | null | null | null | src/tracking/tracking.cpp | sridhargunnam/tracking | 6ac997d407a2fe6090f1f87292b7218c31c9f4a9 | [
"Unlicense"
] | null | null | null | src/tracking/tracking.cpp | sridhargunnam/tracking | 6ac997d407a2fe6090f1f87292b7218c31c9f4a9 | [
"Unlicense"
] | null | null | null | //
// Created by sgunnam on 10/4/20.
//
#include "tracking.h"
class KalmanWrapper{
cv::KalmanFilter kalman_filter_;
cv::Mat processNoise_;
cv::Mat measurement_ ;
cv::Mat measurementPrev_;
};
Tracking::Tracking(ConfigurationParams configuration_params) : configuration_params_(configuration_params)
{
switch (configuration_params.detection_type_) {
case DetectionType::DEPTH_AND_COLOR_CONTOUR: {
// Note: we m want to add exceptions for the 3 other cases
auto cam = CameraModule(configuration_params_.camera_type_);
//Create a depth cleaner instance
cv::rgbd::DepthCleaner depthc(CV_16U, 7, cv::rgbd::DepthCleaner::DEPTH_CLEANER_NIL);
cv::Ptr<cv::BackgroundSubtractor> pBackSub{ cv::createBackgroundSubtractorKNN(1, 100.0, true) };
cv::Ptr<cv::BackgroundSubtractor> pBackSubD{ cv::createBackgroundSubtractorMOG2(1, 100.0, false) };
cv::KalmanFilter kalmanFilter_(4, 2, 0);
cv::Mat kalmanState_(2, 1, CV_32F);
cv::Mat processNoise_(2, 1, CV_32F);
cv::Mat measurement_ = cv::Mat::zeros(2, 1, CV_32F);
cv::Mat measurementPrev_ = cv::Mat::zeros(2, 1, CV_32F);
// TODO refactor Kalman related states
cv::KalmanFilter kalmanFilter_D(6, 3, 0);
cv::Mat kalmanState_D(3, 1, CV_32F);
cv::Mat processNoise_D(3, 1, CV_32F);
cv::Mat measurement_D = cv::Mat::zeros(3, 1, CV_32F);
cv::Mat measurementPrev_D = cv::Mat::zeros(3, 1, CV_32F);
{
setIdentity(kalmanFilter_.measurementMatrix);
kalmanFilter_.transitionMatrix = (cv::Mat_<float>(4, 4) << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1);
// processNoise needs empirical estimation, it can't be just some random value. eg. for 1e-5 , ti stops tracking when there is no motion in the scene.
setIdentity(kalmanFilter_.processNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_.measurementNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_.errorCovPost, cv::Scalar::all(1));
//randn( kalmanState_, cv::Scalar::all(0), cv::Scalar::all(0.1) );
// x y z dx dy dz
// 1 0 0 1 0 0
// 0 1 0 0 1 0
// 0 0 1 0 0 1
// 0 0 0 1 0 0
// 0 0 0 0 1 0
// 0 0 0 0 0 1
// States
// x y z dx dx dz
setIdentity(kalmanFilter_D.measurementMatrix);
kalmanFilter_D.transitionMatrix = (cv::Mat_<float>(6, 6) << 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1);
// processNoise needs empirical estimation, it can't be just some random value. eg. for 1e-5 , ti stops tracking when there is no motion in the scene.
setIdentity(kalmanFilter_D.processNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_D.measurementNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_D.errorCovPost, cv::Scalar::all(1));
// TODO may need to fix statePost initialization
//randn(kalmanFilter_.statePost, cv::Scalar::all(0), cv::Scalar::all(0.1));
}
cv::Mat frame, fgMask, frame_orig;
cv::Rect rect_measured;
std::vector<std::vector<cv::Point>> maxAreaContours;
cv::Rect rect_tracking;
cam.GetCurrentFrame(frame);
int cnt = 0;
bool run_once = true;
// depth related
cv::Mat frameD, fgMaskD, frame_origD;
cv::Mat im8u;
cv::Rect rect_measuredD;
std::vector<std::vector<cv::Point>> maxAreaContoursD;
cv::Rect rect_trackingD;
cam.GetDepthFrame(frameD);
std::vector<std::vector<cv::Point>> contoursD;
while (true) {
std::cout << "At index " << cnt << " : -------------------------------------------------------------- " << std::endl;
++cnt;
maxAreaContours.clear();
maxAreaContoursD.clear();
contoursD.clear();
//rs2::frameset data = pipe.wait_for_frames(); // Wait for next set of frames from the camera
//rs2::frame depth_frame = data.get_depth_frame(); //Take the depth frame from the frameset
cam.GetCurrentFrame(frame);
cam.GetDepthFrame(frameD);
if (frame.empty() || frameD.empty()) {
std::cout << "input frame is empty\n";
break;
}
frame_orig = frame.clone();
frame_origD = frameD.clone();
frameD.convertTo(im8u, CV_8UC1, 0.1);
cv::Rect rect_detect;
cv::Rect rect_detectD;
if (run_once || (cv::theRNG().uniform(0, 100) < 100)) {
run_once = false;
// Color frame processing
FilterAndErode(frame);
pBackSub->apply(frame, fgMask, 0.99);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(fgMask, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
// Depth frame processing
CleanDepthMap(frameD);
pBackSubD->apply(frameD, fgMaskD, 0.99);
cv::findContours(fgMaskD, contoursD, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
if (!contoursD.empty() && !contours.empty()) {
std::sort(contoursD.begin(), contoursD.end(), [](auto &lhs, auto &rhs) {
return fabs(cv::contourArea(lhs) > fabs(cv::contourArea(rhs)));
});
std::sort(contours.begin(), contours.end(), [](auto &lhs, auto &rhs) {
return fabs(cv::contourArea(lhs) > fabs(cv::contourArea(rhs)));
});
maxAreaContours.push_back(contours[0]);
maxAreaContoursD.push_back(contoursD[0]);
//std::cout << " cv::contourArea(maxAreaContours[0]) " << cv::contourArea(maxAreaContours[0]) << "\n";
//std::cout << " cv::contourArea(maxAreaContoursD[0]) " << cv::contourArea(maxAreaContoursD[0]) << "\n";
if ((fabs(cv::contourArea(maxAreaContours[0])) > 100) && (fabs(cv::contourArea(maxAreaContoursD[0])) > 1000)) {
auto all_moments = cv::moments(maxAreaContours[0], true);
measurement_.at<float>(0, 0) = static_cast<float>((all_moments.m10 / all_moments.m00));
measurement_.at<float>(1, 0) = static_cast<float>((all_moments.m01 / all_moments.m00));
rect_detect = cv::boundingRect(maxAreaContours[0]);
//std::cout << "Vision all_moments.m00= " << all_moments.m00 << " ;";
measurement_.copyTo(measurementPrev_);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
auto all_momentsD = cv::moments(maxAreaContoursD[0], true);
measurement_D.at<float>(0, 0) = static_cast<float>((all_momentsD.m10 / all_momentsD.m00));
measurement_D.at<float>(1, 0) = static_cast<float>((all_momentsD.m01 / all_momentsD.m00));
int xpos = static_cast<int>(measurement_D.at<float>(0, 0));
int ypos = static_cast<int>(measurement_D.at<float>(1, 0));
measurement_D.at<float>(2, 0) = static_cast<float>(frame_origD.at<int>(xpos, ypos));
rect_detectD = cv::boundingRect(maxAreaContoursD[0]);
measurement_D.copyTo(measurementPrev_D);
std::cout << "Vision measurement x = " << measurement_.at<float>(0, 0) << " ";
std::cout << "Vision measurement y = " << measurement_.at<float>(1, 0) << std::endl;
std::cout << "Depth measurementD x = " << measurement_D.at<float>(0, 0) << " ";
std::cout << "Depth measurementD y = " << measurement_D.at<float>(1, 0) << std::endl;
std::cout << "Difference x = " << measurement_D.at<float>(0, 0) - measurement_.at<float>(0, 0) << " ";
std::cout << "Difference y = " << measurement_D.at<float>(1, 0) - measurement_.at<float>(1, 0) << std::endl;
} else {
//std::cout << "No motion: kalman state = " << kalmanState_ << std::endl;
measurementPrev_.copyTo(measurement_);
measurementPrev_D.copyTo(measurement_D);
}
}
cv::drawContours(frame_orig, maxAreaContours, 0, cv::Scalar(255, 0, 0), 3);
cv::drawContours(im8u, maxAreaContoursD, 0, cv::Scalar(255, 0, 0), 3);
//std::cout << "measure error point = " << measurement_ << std::endl;
kalmanFilter_.correct(measurement_);
kalmanState_ = kalmanFilter_.predict();
kalmanFilter_D.correct(measurement_D);
kalmanState_D = kalmanFilter_D.predict();
//rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, rect_detect.width, rect_detect.height);
cv::rectangle(frame_orig, rect_detect, cv::Scalar(0, 255, 0), 3);
cv::rectangle(im8u, rect_detectD, cv::Scalar(0, 255, 0), 3);
//std::cout << "kalman state = " << kalmanState_ << std::endl;
} else {
kalmanState_ = kalmanFilter_.predict();
kalmanState_D = kalmanFilter_D.predict();
//rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, 100, 100);
// cv::rectangle(frame_orig, rect_tracking, cv::Scalar(0, 0, 255), 3);
}
rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, 100, 100);
cv::rectangle(frame_orig, rect_tracking, cv::Scalar(0, 0, 255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//cv::rectangle(frame_orig, rect_measured, cv::Scalar(0,0,255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//show the current frame and the fg masks
imshow("Vision Frame", frame);
imshow("Vision FG Mask", fgMask);
imshow("Vision Contours", frame_orig);
rect_trackingD = cv::Rect(static_cast<int>(kalmanState_D.at<float>(0)) - rect_detectD.width / 2, static_cast<int>(kalmanState_D.at<float>(1)) - rect_detectD.height / 2, 100, 100);
cv::rectangle(im8u, rect_trackingD, cv::Scalar(0, 0, 255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//cv::rectangle(frame_orig, rect_measured, cv::Scalar(0,0,255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//show the current frame and the fg masks
imshow("Depth Frame", frameD);
imshow("Depth fgMaskD", fgMaskD);
imshow("Depth Contours", im8u);
//get the input from the keyboard
int keyboard = cv::waitKey(30);
if (keyboard == 'q' || keyboard == 27)
break;
}
break;
}
case DetectionType::COLOR_CONTOUR: {
//Note: To change to different camera change the type here.
auto cam = CameraModule(configuration_params_.camera_type_);
cv::Ptr<cv::BackgroundSubtractor> pBackSub{ cv::createBackgroundSubtractorKNN(1, 100.0, true) };
// TODO refactor Kalman related states
cv::KalmanFilter kalmanFilter_(4, 2, 0);
cv::Mat kalmanState_(2, 1, CV_32F);
cv::Mat processNoise_(2, 1, CV_32F);
cv::Mat measurement_ = cv::Mat::zeros(2, 1, CV_32F);
cv::Mat measurementPrev_ = cv::Mat::zeros(2, 1, CV_32F);
{
{
kalmanFilter_.statePre.at<double>(0) = 320;
kalmanFilter_.statePre.at<double>(1) = 240;
kalmanFilter_.statePre.at<double>(2) = 0;
kalmanFilter_.statePre.at<double>(3) = 0;
}
//randn( kalmanState_, cv::Scalar::all(0), cv::Scalar::all(0.1) );
// x y dx dy
// 1 0 1 0
// 0 1 0 1
// 0 0 1 0
// 0 0 0 1
setIdentity(kalmanFilter_.measurementMatrix);
kalmanFilter_.transitionMatrix = (cv::Mat_<float>(4, 4) << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1);
// processNoise needs empirical estimation, it can't be just some random value. eg. for 1e-5 , ti stops tracking when there is no motion in the scene.
setIdentity(kalmanFilter_.processNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_.measurementNoiseCov, cv::Scalar::all(1e-3));
setIdentity(kalmanFilter_.errorCovPost, cv::Scalar::all(1));
// TODO may need to fix statePost initialization
//randn(kalmanFilter_.statePost, cv::Scalar::all(0), cv::Scalar::all(0.1));
}
cv::Mat frame, fgMask, frame_orig;
cv::Rect rect_measured;
std::vector<std::vector<cv::Point>> maxAreaContours;
cam.GetCurrentFrame(frame);
int cnt = 0;
bool run_once = true;
cv::Rect rect_tracking;
while (true) {
std::cout << "At index " << cnt << " : " << std::endl;
++cnt;
maxAreaContours.clear();
cam.GetCurrentFrame(frame);
if (frame.empty())
break;
frame_orig = frame.clone();
cv::Rect rect_detect;
if (run_once || (cv::theRNG().uniform(0, 100) < 100)) {
run_once = false;
FilterAndErode(frame);
pBackSub->apply(frame, fgMask, 0.99);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(fgMask, contours, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
if (!contours.empty()) {
std::sort(contours.begin(), contours.end(), [](auto &lhs, auto &rhs) {
return fabs(cv::contourArea(lhs) > fabs(cv::contourArea(rhs)));
});
maxAreaContours.push_back(contours[0]);
if (fabs(cv::contourArea(maxAreaContours[0])) > 100) {
auto all_moments = cv::moments(maxAreaContours[0], true);
measurement_.at<float>(0, 0) = static_cast<float>((all_moments.m10 / all_moments.m00));
measurement_.at<float>(1, 0) = static_cast<float>((all_moments.m01 / all_moments.m00));
rect_detect = cv::boundingRect(maxAreaContours[0]);
//rect_detect.height = 50;
//rect_detect.width = 50;
//cv::rectangle(frame_orig, rect_detect, cv::Scalar(0, 255, 0), 3);
//measurement_ = kalmanFilter_.measurementMatrix*kalmanState_;
std::cout << "all_moments.m00= " << all_moments.m00 << " ;";
std::cout << "measurement 00 = " << measurement_.at<float>(0, 0) << " ";
std::cout << "measurement 01 = " << measurement_.at<float>(0, 1) << std::endl;
measurement_.copyTo(measurementPrev_);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
} else {
std::cout << "No motion: kalman state = " << kalmanState_ << std::endl;
measurementPrev_.copyTo(measurement_);
}
}
kalmanFilter_.correct(measurement_);
kalmanState_ = kalmanFilter_.predict();
//rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, rect_detect.width, rect_detect.height);
cv::rectangle(frame_orig, rect_detect, cv::Scalar(0, 255, 0), 3);
std::cout << "kalman state = " << kalmanState_ << std::endl;
} else {
kalmanState_ = kalmanFilter_.predict();
//rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, 100, 100);
// cv::rectangle(frame_orig, rect_tracking, cv::Scalar(0, 0, 255), 3);
}
rect_tracking = cv::Rect(static_cast<int>(kalmanState_.at<float>(0)) - rect_detect.width / 2, static_cast<int>(kalmanState_.at<float>(1)) - rect_detect.height / 2, 100, 100);
cv::rectangle(frame_orig, rect_tracking, cv::Scalar(0, 0, 255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//cv::rectangle(frame_orig, rect_measured, cv::Scalar(0,0,255), 3);
//cv::drawContours(frame_orig, maxAreaContours, -1, cv::Scalar(255, 0, 0), 3);
//show the current frame and the fg masks
imshow("Frame", frame);
imshow("FG Mask", fgMask);
imshow("Contours", frame_orig);
cv::Mat depth_frame;
cam.GetDepthFrame(depth_frame);
cv::imshow("depth_frame", depth_frame);
cv::waitKey(0);
//get the input from the keyboard
int keyboard = cv::waitKey(30);
if (keyboard == 'q' || keyboard == 27)
break;
}
break;
}
}
}
// Based on opencv squares.cpp sample
void Tracking::FilterAndErode(cv::Mat &img) const
{
cv::Size gaussian_kernel = cv::Size(25,25);
cv::GaussianBlur(img, img, gaussian_kernel, 0, 0);
cv::dilate(img, img, cv::Mat(), cv::Point(-1, -1), 5, 1, 1);
}
// Clean depth, fill holes
void Tracking::CleanDepthMap(cv::Mat &img) const
{
cv::rgbd::DepthCleaner depthc(CV_16U, 7, cv::rgbd::DepthCleaner::DEPTH_CLEANER_NIL);
const int w = img.rows;
const int h = img.cols;
cv::Mat cleanedDepth(cv::Size(w, h), CV_16U);
depthc.operator()(img, cleanedDepth);
cv::Mat cleanedDepth8U(cv::Size(w, h), CV_8UC1);
cleanedDepth.convertTo(cleanedDepth8U, CV_8UC1);
//int kernel_size = 7;
//cv::Size gaussian_kernel = cv::Size(kernel_size, kernel_size);
//cv::GaussianBlur(cleanedDepth8U, cleanedDepth8U, gaussian_kernel, 0, 0);
cv::adaptiveThreshold(cleanedDepth8U, img, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 7, 0 );
//cv::dilate(img, img, cv::Mat(), cv::Point(-1, -1), 5, 1, 1);
//cv::erode(img,img, cv::Mat(),cv::Point(-1,-1));
//cv::Mat kernel_mat = cv::Mat::ones(30,30, CV_8U);
//cv::morphologyEx(img, img, cv::MORPH_CLOSE, kernel_mat);
}
| 47.669421 | 213 | 0.621359 | [
"vector"
] |
3192cbfaeb4f0cf10f57c4b0b4accc5c71f54d2f | 302 | hh | C++ | transformations/hist/RebinN.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | 5 | 2019-10-14T01:06:57.000Z | 2021-02-02T16:33:06.000Z | transformations/hist/RebinN.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | transformations/hist/RebinN.hh | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "GNAObject.hh"
#include "Eigen/Sparse"
class RebinN: public GNAObject,
public TransformationBind<RebinN> {
public:
RebinN(size_t n);
void doRebin(FunctionArgs& fargs);
void doTypes(TypesFunctionArgs& fargs);
private:
size_t m_njoin;
};
| 16.777778 | 49 | 0.711921 | [
"vector"
] |
3193108b628e6e1bef420b420230b62195e98fab | 356 | cpp | C++ | Arrays/Easy/Running Sum of 1 D array.cpp | saubhagya0111/Leetcode-Solutions | 2bebcb225cb3c07733b15dc003fb61f6d50b371a | [
"MIT"
] | null | null | null | Arrays/Easy/Running Sum of 1 D array.cpp | saubhagya0111/Leetcode-Solutions | 2bebcb225cb3c07733b15dc003fb61f6d50b371a | [
"MIT"
] | null | null | null | Arrays/Easy/Running Sum of 1 D array.cpp | saubhagya0111/Leetcode-Solutions | 2bebcb225cb3c07733b15dc003fb61f6d50b371a | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
int element;
vector<int> v;
for(int i=0;i<nums.size();i++)
{
element=0;
for(int j=0;j<=i;j++)
{
element+=nums[j];
}
v.push_back(element);
}
return v;
}
};
| 19.777778 | 47 | 0.404494 | [
"vector"
] |
3193de437252e89843092206a788d972a3f6ee3b | 9,215 | hpp | C++ | stapl_release/stapl/skeletons/transformations/optimizers/zip_reduce.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/transformations/optimizers/zip_reduce.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/transformations/optimizers/zip_reduce.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_SKELETONS_COARSE_OPTIMIZERS_ZIP_REDUCE_HPP
#define STAPL_SKELETONS_COARSE_OPTIMIZERS_ZIP_REDUCE_HPP
#include <vector>
#include <stapl/skeletons/transformations/optimizer.hpp>
#include <stapl/skeletons/utility/utility.hpp>
#include <stapl/skeletons/utility/tags.hpp>
#include <stapl/skeletons/utility/skeleton.hpp>
#include <stapl/skeletons/utility/wf_iter_compare.hpp>
#include <stapl/skeletons/utility/dynamic_wf.hpp>
#include <stapl/skeletons/transformations/optimizers/utils.hpp>
namespace stapl {
namespace skeletons {
namespace optimizers {
template <typename SkeletonTag, typename ExecutionTag>
struct optimizer;
//////////////////////////////////////////////////////////////////////
/// @brief Helper recursive template that unrolls a zip_reduce
/// loop (iterator based) by the specified factor.
//////////////////////////////////////////////////////////////////////
template<std::size_t N>
struct zr_unroller
{
template<typename Return, typename Zip, typename Reduce, typename ...Iters>
static void apply(Return& ret, Zip& zip_op, Reduce& red_op, Iters&... iters)
{
helpers::reduce_assign(ret, red_op(ret, zip_op(*(++iters)...)));
zr_unroller<N-1>::apply(ret, zip_op, red_op, iters...);
}
};
//////////////////////////////////////////////////////////////////////
/// @brief Base case of the recursion. Call zip and reduction one more time.
//////////////////////////////////////////////////////////////////////
template<>
struct zr_unroller<1>
{
template<typename Return, typename Zip, typename Reduce, typename ...Iters>
static void apply(Return& ret, Zip& zip_op, Reduce& red_op, Iters&... iters)
{
helpers::reduce_assign(ret, red_op(ret, zip_op(*(++iters)...)));
}
};
//////////////////////////////////////////////////////////////////////
/// @brief A @c zip_reduce optimizer is used in the cases that both
/// views are local and their traversal would be fast which improves the
/// performance. Tagged with @ref tags::sequential_unroll allows directs
/// the optimizer to unroll the sequential loop with the specified factor.
///
/// @ingroup skeletonsTransformationsCoarse
//////////////////////////////////////////////////////////////////////
template <int arity, std::size_t factor>
struct optimizer<tags::zip_reduce<arity>, tags::sequential_unroll<factor>>
{
template <typename R>
struct result;
template <typename Optimizer, typename OutputValueType>
struct result<Optimizer(OutputValueType)>
{
using type = OutputValueType;
};
private:
//////////////////////////////////////////////////////////////////////
/// @brief Specialization of sequential execution when @ref paragraph_view
/// is required by the zip operation
//////////////////////////////////////////////////////////////////////
struct dynamic
{
template <typename R, typename S,
typename TGV,
typename IterComp, typename ...Iter>
static R apply(S&& skeleton, TGV tgv,
IterComp& iter_compare, Iter... iter)
{
auto red_op = skeleton.get_reduce_op();
auto zip_op = skeleton.get_zip_op();
R result = zip_op(tgv, *(iter++)...);
for (; iter_compare(iter...); helpers::no_op(++iter...)) {
helpers::reduce_assign(
result,
red_op(result, zip_op(tgv, *(iter)...)));
}
return result;
}
template <typename R, typename S, typename TGV,
typename V0, typename... V>
static R execute(S&& skeleton, TGV tgv,
V0&& view0, V&&... view)
{
stapl_assert(view0.size() > 0, "empty views cannot be zip-reduced");
wf_iter_compare<
typename std::decay<V0>::type,
typename std::decay<V>::type...> iter_compare(
std::forward<V0>(view0),
std::forward<V>(view)...);
return apply<R>(std::forward<S>(skeleton), tgv, iter_compare,
view0.begin(), view.begin()...);
}
}; // nested struct dynamic
//////////////////////////////////////////////////////////////////////
/// @brief Specialization of sequential execution when @ref paragraph_view
/// is not required by the zip operation
//////////////////////////////////////////////////////////////////////
struct non_dynamic
{
template <typename R, typename S,
typename IterComp, typename ...Iter>
static R apply_iterator(S&& skeleton, std::size_t size,
IterComp& iter_compare, Iter... iter)
{
auto red_op = skeleton.get_reduce_op();
auto zip_op = skeleton.get_zip_op();
R result = zip_op(*(iter)...);
if (size > 1)
{
for (size_t trip_count = (size-1)/factor; trip_count > 0; --trip_count)
zr_unroller<factor>::apply(result, zip_op, red_op, iter...);
for (size_t leftovers = (size-1)%factor; leftovers > 0; --leftovers)
helpers::reduce_assign(result, red_op(result, zip_op(*(++iter)...)));
}
return result;
}
template <typename R, typename S, typename... Tuple>
static R apply_domain(S&& skeleton,
std::size_t size, Tuple... t)
{
auto red_op = skeleton.get_reduce_op();
auto zip_op = skeleton.get_zip_op();
R result = zip_op(
helpers::referencer(std::get<0>(t), std::get<2>(t))...
);
helpers::no_op(
helpers::advance_domain(std::get<1>(t), std::get<2>(t))...);
for (std::size_t i = 0; i < size-1; ++i, helpers::no_op(
helpers::advance_domain(std::get<1>(t), std::get<2>(t))...))
helpers::reduce_assign(result, red_op(result,
zip_op(helpers::referencer(std::get<0>(t), std::get<2>(t))...)
));
return result;
}
template <typename R, typename S, typename... V>
static R apply(std::false_type, S&& skeleton, V&&... v)
{
const std::size_t size = helpers::view_size(std::forward<V>(v)...);
return apply_domain<R>(std::forward<S>(skeleton), size,
stapl::make_tuple(v, v.domain(), v.domain().first())...
);
}
template <typename R, typename S,
typename V0, typename...V>
static R apply(std::true_type, S&& skeleton,
V0&& view0, V&&... view)
{
stapl_assert(view0.size() > 0, "empty views cannot be zip-reduced");
wf_iter_compare<
typename std::decay<V0>::type,
typename std::decay<V>::type...> iter_compare(
std::forward<V0>(view0),
std::forward<V>(view)...);
return apply_iterator<R>(
std::forward<S>(skeleton),
helpers::view_size(std::forward<V0>(view0), std::forward<V>(view)...),
iter_compare,
view0.begin(), view.begin()...
);
}
template <typename R, typename S, typename... V>
static R execute(S&& skeleton, V&&... v)
{
return apply<R>(
typename helpers::pack_has_iterator<
typename std::decay<V>::type...
>::type(),
std::forward<S>(skeleton), std::forward<V>(v)...);
}
}; // nested struct non_dynamic
public:
//////////////////////////////////////////////////////////////////////
/// @brief Sequential zip_reduce optimizer dispatches the execution to
/// two different signatures based on the requirement of the given
/// zip operation. If the zip operations needs the @ref paragraph_view
/// the dynamic specialization is called, otherwise the non_dynamic
/// one is called.
///
/// @return the result of the zip_reduce operation (can be void)
//////////////////////////////////////////////////////////////////////
template <typename R, typename S, typename... Args>
static R execute(S&& skeleton, Args&&... args)
{
using dispatcher_t = typename std::conditional<
std::is_base_of<
dynamic_wf,
typename std::decay<S>::type::zip_op_type>::value,
dynamic,
non_dynamic>::type;
return dispatcher_t::template execute<R>(
std::forward<S>(skeleton),
std::forward<Args>(args)...);
}
};
//////////////////////////////////////////////////////////////////////
/// @brief A @c zip_reduce optimizer is used in the cases that both
/// views are local and their traversal would be fast which improves the
/// performance.
///
/// Calls the unrolled variant with factor = 1.
/// @ingroup skeletonsTransformationsCoarse
//////////////////////////////////////////////////////////////////////
template <int arity>
struct optimizer<tags::zip_reduce<arity>, tags::sequential_execution>
: optimizer<tags::zip_reduce<arity>, tags::sequential_unroll<1>>
{ };
} // namespace optimizers
} // namespace skeletons
} // namespace stapl
#endif // STAPL_SKELETONS_OPTIMIZERS_ZIP_REDUCE_HPP
| 35.717054 | 79 | 0.565708 | [
"vector"
] |
3195ab30aeb5be2f9a1f7c799c4d3faf778fa0d9 | 37,710 | cpp | C++ | SOURCES/sim/digi/waypoint.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/digi/waypoint.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/digi/waypoint.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include "stdhdr.h"
#include "digi.h"
#include "otwdrive.h"
#include "PilotInputs.h"
#include "campwp.h"
#include "simveh.h"
#include "fcc.h"
#include "simdrive.h"
#include "facbrain.h"
#include "mission.h"
#include "object.h"
#include "MsgInc\FACMsg.h"
#include "MsgInc\ATCMsg.h"
#include "MsgInc\RadioChatterMsg.h"
#include "MsgInc\TankerMsg.h"
#include "falcmesg.h"
#include "falcsess.h"
#include "aircrft.h"
#include "airframe.h"
#include "unit.h"
#include "falcsnd\conv.h"
#include "mesg.h"
#include "airunit.h"
#include "rules.h"
#include "atcbrain.h"
#include "wingorder.h"
// Brain Choices
#define GENERIC_BRAIN 0
#define SEAD_BRAIN 1
#define STRIKE_BRAIN 2
#define INTERCEPT_BRAIN 3
#define AIR_CAP_BRAIN 4
#define AIR_SWEEP_BRAIN 5
#define ESCORT_BRAIN 6
#define WAYPOINTER_BRAIN 7
float get_air_speed (float speed, int altitude);
extern float g_fAIRefuelRange;
extern int g_nSkipWaypointTime;
extern bool g_bAGTargetWPFix;
extern float g_fAIMinWPAlt; // Cobra - Min alt AI will fly Nav WP
void DigitalBrain::FollowWaypoints(void)
{
// edg double check groundAvoidNeeded if set -- could be stuck there
if ( groundAvoidNeeded && agApproach != AGA_DIVE) // Cobra - Let rocket and strafing attacks take care of avoidance
GroundCheck();
if (self->curWaypoint == NULL && self->FCC->GetStptMode() == FireControlComputer::FCCMarkpoint)
{
// self->af->SetSimpleMode(SIMPLE_MODE_AF);
self->SetAutopilot( AircraftClass::ThreeAxisAP );
throtl = UserStickInputs.throttle;
ThreeAxisAP();
return;
}
if (self->curWaypoint == NULL)
{
AddMode (LoiterMode);
return;
}
SimBaseClass* pobj = self->GetCampaignObject()->GetComponentEntity(0);
if (isWing && (atcstatus != noATC))
{ // if we are a wingman and we are taking off or landing
mpActionFlags[AI_FOLLOW_FORMATION] = FALSE; // don't follow formation
}
else if (isWing && !pobj)
{ // if we are a wingman and we can't find the leader's pointer
mpActionFlags[AI_FOLLOW_FORMATION] = FALSE; // don't follow formation
}
else if (isWing && (pobj && pobj->OnGround()))
{ // if we are a wingman and our leader is on the ground
mpActionFlags[AI_FOLLOW_FORMATION] = FALSE; // don't follow formation
mLeaderTookOff = FALSE; // reset leader take off flag
if (self->curWaypoint->GetWPAction() == WP_ASSEMBLE && (onStation == Arrived || onStation == Stabalizing || onStation == OnStation))
{ // if we are at the assemble point
if(SimLibElapsedTime < self->curWaypoint->GetWPDepartureTime() + 300000)
{ // if we have time to kill
AddMode (LoiterMode); // hang out for a while
}
}
}
else if(isWing && mLeaderTookOff == FALSE)
{ // if i'm a wing and we think that the leader hasn't taken off
mLeaderTookOff = TRUE; // tell ourselves that the leader tookoff. to get here the leader must have taken off.
mpActionFlags[AI_FOLLOW_FORMATION] = TRUE; // follow the leader
}
// check to see if we're heading at an IP waypoint
// if we are, see if the next waypoint is a ground attack type.
// if it is, setup a GA profile for the attack
if (((self->curWaypoint->GetWPFlags() & WPF_IP) || (GetTargetWPIndex() >= 0 && GetWaypointIndex() == GetTargetWPIndex()-1)) &&
agDoctrine == AGD_NONE )
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
if ((self != playerAC || (self->IsPlayer() && self->AutopilotType() == AircraftClass::CombatAP)) || playerAC->FCC->GetStptMode() == FireControlComputer::FCCWaypoint)
{ // VWF 5/25/98 for E3
// get next Waypoint action
switch (self->curWaypoint->GetNextWP()->GetWPAction())
{
case WP_GNDSTRIKE:
case WP_NAVSTRIKE:
case WP_STRIKE:
case WP_BOMB:
case WP_SAD:
case WP_SEAD:
case WP_CASCP:
case WP_RECON:
SetupAGMode( self->curWaypoint, self->curWaypoint->GetNextWP() );
break;
}
}
}
// check for on-the-fly ground attack
// check for on-the-fly ground attack
// 2001-06-02 MODIFIED BY S.G. DON'T DO IT IF WE'RE IN WEAPON HOLD (EXCEPT FOR THE LAST SECOND)
// else if ( agDoctrine != AGD_NONE )
else if ( agDoctrine != AGD_NONE && SimLibElapsedTime + 1000 >= missileShotTimer )
{
if ( groundTargetPtr )
{
// ground attack
GroundAttackMode();
return;
}
// no ground target, reset the doctrine back to nothing
agDoctrine = AGD_NONE;
}
// 2001-06-28 MODIFIED BY S.G. DO BOTH WPAction AND WPRouteAction IF NO SPECIFIC WAYPOINT ACTION
// switch (self->curWaypoint->GetWPAction())
switch (self->curWaypoint->GetWPAction() == WP_NOTHING ? self->curWaypoint->GetWPRouteAction() : self->curWaypoint->GetWPAction())
{
case WP_GNDSTRIKE:
case WP_NAVSTRIKE:
case WP_STRIKE:
case WP_BOMB:
case WP_SAD:
case WP_SEAD:
case WP_CASCP:
case WP_RECON:
// check to see if we've already got a profile
// 2001-06-02 ADDED BY S.G. DON'T DO IT IF WE'RE IN WEAPON HOLD (EXCEPT FOR THE LAST SECOND)
if (SimLibElapsedTime + 1000 < missileShotTimer)
{
self->theInputs->pickleButton = PilotInputs::Off;
if(((AircraftClass*) self)->af->GetSimpleMode())
{
SimpleGoToCurrentWaypoint();
}
else
{
GoToCurrentWaypoint();
}
}
// END OF ADDED SECTION EXCEPT FOR THE LINE INDENTS
else
{
if ( agDoctrine == AGD_NONE && onStation != Downwind)
{
SetupAGMode( self->curWaypoint, self->curWaypoint );
if(((AircraftClass*) self)->af->GetSimpleMode())
{
SimpleGoToCurrentWaypoint();
}
else
{
GoToCurrentWaypoint();
}
}
else
{
// fly the ground attack profile
GroundAttackMode();
}
}
break;
case WP_LAND:
Land();
break;
case WP_PICKUP:
case WP_AIRDROP:
DoPickupAirdrop();
break;
case WP_TAKEOFF:
AddMode(TakeoffMode);
TakeOff();
break;
case WP_REFUEL:
self->theInputs->pickleButton = PilotInputs::Off;
if(((AircraftClass*) self)->af->GetSimpleMode()) {
SimpleGoToCurrentWaypoint();
}
else {
GoToCurrentWaypoint();
}
// If close, set Refuel Mode
if (fabs(trackX - self->XPos()) < g_fAIRefuelRange * NM_TO_FT &&
fabs(trackY - self->YPos()) < g_fAIRefuelRange * NM_TO_FT &&
onStation == NotThereYet)
{
VU_ID TankerId = vuNullId;
AircraftClass *theTanker = NULL;
FalconTankerMessage *TankerMsg;
FlightClass *flight;
onStation = Arrived;
if(TankerId == FalconNullId)
flight = SimDriver.FindTanker(self);
else
{
flight = (Flight)vuDatabase->Find(TankerId);
if(!flight->IsFlight())
{
flight = SimDriver.FindTanker(SimDriver.GetPlayerEntity());
}
}
if(flight)
theTanker = (AircraftClass*) flight->GetComponentLead();
if (theTanker)
TankerMsg = new FalconTankerMessage (theTanker->Id(), FalconLocalGame);
else
TankerMsg = new FalconTankerMessage (FalconNullId, FalconLocalGame);
TankerMsg->dataBlock.type = FalconTankerMessage::RequestFuel;
TankerMsg->dataBlock.data1 = 1;
TankerMsg->dataBlock.caller = self->Id();
FalconSendMessage(TankerMsg);
}
break;
default:
self->theInputs->pickleButton = PilotInputs::Off;
if(((AircraftClass*) self)->af->GetSimpleMode())
{
SimpleGoToCurrentWaypoint();
}
else
{
GoToCurrentWaypoint();
}
break;
}
}
void DigitalBrain::SimpleGoToCurrentWaypoint(void)
{
float xerr, yerr;
float rng;
float desSpeed; //desSpeedAlt TJL 02/20/04
float ttg = 1.0;
WayPointClass* tmpWaypoint;
long timeDelta;
float gainCtrl;
int vehInFlight;
int flightIdx;
ACFormationData::PositionData *curPosition;
float rangeFactor;
//int thisWP;
//int nextWP;
// prevent too much gain in controls
// except when we're too close to ground
gainCtrl = 0.25f;
// Cobra - Make sure groundAvoidNeeded is not needed
// if (pullupTimer < SimLibElapsedTime)
// {
// groundAvoidNeeded = FALSE;
// pullupTimer = 0;
// }
// see if we're in a ag attack mode
if ( agDoctrine == AGD_NONE )
{
float tx, ty, tz;
self->curWaypoint->GetLocation (&tx, &ty, &tz);
SetTrackPoint(tx, ty, tz);
// Adjust position to avoid collision near waypoint
vehInFlight = ((FlightClass*)self->GetCampaignObject())->GetTotalVehicles();
flightIdx = ((FlightClass*)self->GetCampaignObject())->GetComponentIndex(self);
if (flightIdx != 0)
{
if(flightIdx == AiFirstWing && vehInFlight == 2)
{
curPosition = &(acFormationData->twoposData[mFormation]); // The four ship #2 slot position is copied in to the 2 ship formation array.
}
else if(flightIdx == AiSecondWing && mSplitFlight)
{
curPosition = &(acFormationData->twoposData[mFormation]);
}
else
{
curPosition = &(acFormationData->positionData[mFormation][flightIdx - 1]);
}
rangeFactor = curPosition->range * (2.0F * mFormLateralSpaceFactor);
trackX += rangeFactor * (float)cos(curPosition->relAz * mFormSide + self->Yaw());
trackY += rangeFactor * (float)sin(curPosition->relAz * mFormSide + self->Yaw());
if(curPosition->relEl)
{
trackZ += rangeFactor * (float)sin(-curPosition->relEl);
}
else
{
trackZ += (flightIdx * -100.0F);
}
}
}
else
{
SetTrackPoint(ipX, ipY, ipZ);
}
// edg: according to Kevin, waypoint Z's set for <= 5000.0f indicate
// terrain following, we'll modify our trackZ accordingly by looking
// 1 second and getting ground alt then setting ourselves to follow
// at 500ft.
// Cobra - externalized WP min altitude
if ( trackZ >= -5000.0f )
{
trackZ = OTWDriver.GetGroundLevel( self->XPos() + self->XDelta(),
self->YPos() + self->YDelta() );
// if we're below track alt, kick us up a bit harder so we don't plow
// into steeper slopes
if ( self->ZPos() - trackZ > -g_fAIMinWPAlt )
{
trackZ = trackZ - g_fAIMinWPAlt - ( self->ZPos() - trackZ + g_fAIMinWPAlt ) * 2.0f;
gainCtrl = 1.5f;
}
else
trackZ -= g_fAIMinWPAlt;
}
else
{
// check to make sure we're above everything around
float tfloor, tceil;
OTWDriver.GetAreaFloorAndCeiling( &tfloor, &tceil );
if ( trackZ > tceil - g_fAIMinWPAlt )
{
gainCtrl = 1.5f;
trackZ = tceil - g_fAIMinWPAlt;
}
}
if (curMode != lastMode)
{
onStation = NotThereYet;
}
/*---------------------------*/
/* Range to current waypoint */
/*---------------------------*/
xerr = trackX - self->XPos();
yerr = trackY - self->YPos();
rng = sqrtf(xerr * xerr + yerr * yerr)*FT_TO_NM;
/*---------------------------*/
/* Reached the next waypoint? */
/*---------------------------*/
// Cobra - Change rng to 2 nm (was 1 nm) to give AI a little more leeway in hitting the WP.
// Cobra - Added loitering timer check (agmergeTimer)
if(rng < 2.0f || (onStation != NotThereYet) || (SimLibElapsedTime > self->curWaypoint->GetWPDepartureTime()))
{
// Should we repeat?
if (self && self->curWaypoint && self->curWaypoint->GetWPFlags() & (WPF_REPEAT | WPF_REPEAT_CONTINUOUS))
{
if ((self->curWaypoint->GetWPFlags() & WPF_REPEAT_CONTINUOUS) ||
SimLibElapsedTime < self->curWaypoint->GetWPDepartureTime())
{
// Find prev waypoint
tmpWaypoint = self->curWaypoint->GetPrevWP ();
// Get travel time between points
timeDelta = self->curWaypoint->GetWPArrivalTime() - tmpWaypoint->GetWPDepartureTime();
// Reset arrival and departure points for first waypoint
tmpWaypoint->SetWPArrive (self->curWaypoint->GetWPArrivalTime() + timeDelta);
tmpWaypoint->SetWPDepartTime (self->curWaypoint->GetWPArrivalTime() + timeDelta);
// reset arrival time for end waypoint
self->curWaypoint->SetWPArrive (self->curWaypoint->GetWPArrivalTime() + 2 * timeDelta);
// If continuous, reset current departure time
if (self->curWaypoint->GetWPFlags() & WPF_REPEAT_CONTINUOUS)
{
self->curWaypoint->SetWPDepartTime (self->curWaypoint->GetWPArrivalTime() + 2 * timeDelta);
}
// set current waypoint to prev
self->curWaypoint = tmpWaypoint;
onStation = NotThereYet;
SetWaypointSpecificStuff();
}
else
{
SelectNextWaypoint();
}
SimpleTrack(SimpleTrackDist, 0.0F);
}
else if (onStation == NotThereYet)
{
onStation = Arrived;
SimpleTrack(SimpleTrackDist, 0.0F);
}
else if (rng < 2.0F && onStation == Arrived)
{
if (GetTargetWPIndex() >= 0 && GetWaypointIndex() <= GetTargetWPIndex())
{
SelectNextWaypoint();
SimpleTrack(SimpleTrackDist, 0.0F);
}
else if (GetWaypointIndex() != GetTargetWPIndex())
{
SelectNextWaypoint();
SimpleTrack(SimpleTrackDist, 0.0F);
}
}
// edg: if we're within 30 secs just go to next ....
else if (SimLibElapsedTime + g_nSkipWaypointTime > self->curWaypoint->GetWPDepartureTime())
{
/* 2002-04-05 MN
We have a problem here. With the new code that also allows AG missions to engage BVR/WVR, and the new flightmodels,
it can easily happen that a flight is too late at its target, especially for AG missions. So if we're on an AG mission,
have not yet completed the mission, are not in RTB mode or landing mode, don't skip the target waypoint.
A better fix would be having the AI increase speed if they are behind scheduled waypoint times, but for FalconSP3 this is
beyond our scope. */
//Cobra Caught the AI stuck in Crosswind with NULL groundTarget
// Cobra - Sead AI wouldn't move on when no targets left or exceeded loitering timer
//Adding in onStation == Crosswind; if we make it here, we are past our waypoint time
//already so this shouldn't be a problem?
if (((onStation == Crosswind || (onStation == NotThereYet && missionComplete)) &&
groundTargetPtr == NULL) || onStation == OnStation || !(g_bAGTargetWPFix &&
self->curWaypoint->GetWPFlags() & WPF_TARGET && !missionComplete && missionClass == AGMission &&
curMode != RTBMode && curMode != LandingMode))
{
// 2002-04-08 MN removed again - this stops AI from going to landing mode at all...
// JB 020315 Don't skip to the last waypoint unless we're OnStation. Otherwise we may go into landing mode too early.
// if (onStation == OnStation || self->curWaypoint->GetNextWP() && self->curWaypoint->GetNextWP()->GetWPAction() != WP_LAND)
// Cobra - Don't skip the WP after target WP
if (GetTargetWPIndex() >= 0 && GetWaypointIndex() <= GetTargetWPIndex())
SelectNextWaypoint();
}
SimpleTrack(SimpleTrackDist, 0.0F);
}
else
{
Loiter();
}
}
else
{
// Time left to target
if (self && self->curWaypoint)
ttg = (self->curWaypoint->GetWPArrivalTime() - SimLibElapsedTime) / (float)SEC_TO_MSEC;
//TJL 11/09/03 Make speed aircraft friendly. What about the A-10, it's not seeing 700.0f
// Changed to from 700.0F to 1.3 of corner
if (ttg < 0.0F)
{ // If we're late
desSpeed = 1.3F * cornerSpeed;
}
else
{
//TJL 02/20/04 TEST of new range/speed code
//desSpeed = (float) sqrt(rng) / ttg * FTPSEC_TO_KNOTS;
rng = sqrtf(xerr * xerr + yerr * yerr);
desSpeed = ((rng/ttg)*FTPSEC_TO_KNOTS);
}
//TJL 02/20/04 We don't need this. MinVcas should be set in ac.dat file
//as min speed Sea level. Sim will take into account that speed at altitude
//Mnvers.cpp will catch speed below min vcas
/* desSpeedAlt = get_air_speed (desSpeed, -1*FloatToInt32(self->ZPos()));
while (desSpeedAlt < af->MinVcas() * 0.85F)
{
desSpeed *= 1.1F;
desSpeedAlt = get_air_speed (desSpeed, -1*FloatToInt32(self->ZPos()));
}
*/
if (curMode == RTBMode)
desSpeed = cornerSpeed;
//TJL 02/20/04 Speed is in KNOTS
//TrackPoint(0.0F, desSpeed * KNOTS_TO_FTPSEC);
TrackPoint(0.0F, desSpeed);
}
// modify p and r stick settings by gain control
pStick *= gainCtrl;
// rStick *= gainCtrl;
}
void DigitalBrain::GoToCurrentWaypoint(void)
{
float rng, desHeading;
float desLoad;
float ttg, desSpeed;
float wpX, wpY, wpZ;
WayPointClass* tmpWaypoint;
long timeDelta;
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
if(self == playerAC && playerAC->FCC->GetStptMode() != FireControlComputer::FCCWaypoint) {
return; // VWF 5/25/98 for E3
}
self->curWaypoint->GetLocation (&wpX, &wpY, &wpZ);
SetTrackPoint(wpX, wpY, wpZ);
if (curMode != lastMode)
{
onStation = NotThereYet;
holdAlt = -wpZ;
waypointMode = 1;
}
/*---------------------------*/
/* Range to current waypoint */
/*---------------------------*/
rng = (wpX - self->XPos()) * (wpX - self->XPos()) + (wpY - self->YPos()) * (wpY - self->YPos());
/*------------------------------------*/
/* Heading error for current waypoint */
/*------------------------------------*/
desHeading = (float)atan2 ( wpY - self->YPos(), wpX - self->XPos()) - af->sigma;
if (desHeading > 180.0F * DTR)
desHeading -= 360.0F * DTR;
else if (desHeading < -180.0F * DTR)
desHeading += 360.0F * DTR;
/*------------------------------------*/
/* Radius of the turn at the waypoint */
/*------------------------------------*/
desLoad = 2.0F * maxGs * desHeading / (180.0F * DTR);
if (desLoad < 0.0F)
desLoad = -desLoad;
desLoad = min ( max (1.25F, desLoad), 2.0F);
/*---------------------------*/
/* Reached the next waypoint */
/*---------------------------*/
// 0.83 NM
// if (rng < (5000.0F * 5000.0F) || (onStation != NotThereYet) ||
// Cobra - Give AI plenty of leeway to reach WP
// 1.66 NM
if (rng < (10000.0F * 10000.0F) || (onStation != NotThereYet) ||
SimLibElapsedTime > self->curWaypoint->GetWPDepartureTime())
{
// Should we repeat?
if (self->curWaypoint->GetWPFlags() & (WPF_REPEAT | WPF_REPEAT_CONTINUOUS))
{
if ((self->curWaypoint->GetWPFlags() & WPF_REPEAT_CONTINUOUS) ||
SimLibElapsedTime < self->curWaypoint->GetWPDepartureTime())
{
// Find prev waypoint
tmpWaypoint = self->curWaypoint->GetPrevWP ();
// Get travel time between points
timeDelta = self->curWaypoint->GetWPArrivalTime() - tmpWaypoint->GetWPDepartureTime();
// Reset arrival and departure points for first waypoint
tmpWaypoint->SetWPArrive (self->curWaypoint->GetWPArrivalTime() + timeDelta);
tmpWaypoint->SetWPDepartTime (self->curWaypoint->GetWPArrivalTime() + timeDelta);
// reset arrival time for end waypoint
self->curWaypoint->SetWPArrive (self->curWaypoint->GetWPArrivalTime() + 2 * timeDelta);
// If continuous, reset current departure time
if (self->curWaypoint->GetWPFlags() & WPF_REPEAT_CONTINUOUS)
{
self->curWaypoint->SetWPDepartTime (self->curWaypoint->GetWPArrivalTime() + 2 * timeDelta);
}
// set current waypoint to prev
self->curWaypoint = tmpWaypoint;
onStation = NotThereYet;
SetWaypointSpecificStuff();
}
else
{
SelectNextWaypoint();
}
}
else if (onStation == NotThereYet)
{
holdAlt = -wpZ;
gammaHoldIError = 0.0F;
onStation = Arrived;
}
else if (SimLibElapsedTime + g_nSkipWaypointTime > self->curWaypoint->GetWPDepartureTime())
{
/* 2002-04-05 MN
We have a problem here. With the new code that also allows AG missions to engage BVR/WVR, and the new flightmodels,
it can easily happen that a flight is too late at its target, especially for AG missions. So if we're on an AG mission,
have not yet completed the mission, are not in RTB mode or landing mode, don't skip the target waypoint. */
// mind the ! check here !!!
if (onStation == OnStation || !(g_bAGTargetWPFix &&
self->curWaypoint->GetWPFlags() & WPF_TARGET &&
!missionComplete && missionClass == AGMission &&
curMode != RTBMode && curMode != LandingMode))
{
// JB 020315 Don't skip to the last waypoint unless we're OnStation. Otherwise we may go into landing mode too early.
if (onStation == OnStation || self->curWaypoint->GetNextWP() && self->curWaypoint->GetNextWP()->GetWPAction() != WP_LAND)
{
// Cobra - Don't skip the WP after target WP
if (GetTargetWPIndex() >= 0 && GetWaypointIndex() <= GetTargetWPIndex())
SelectNextWaypoint();
}
}
}
// Cobra - Give AI plenty of leeway to reach WP
// 1.66 NM
else if (rng < (10000.0F * 10000.0F))
SelectNextWaypoint();
desSpeed = cornerSpeed;
}
else
{
/*---------------------*/
/* Time left to target */
/*---------------------*/
ttg = (self->curWaypoint->GetWPArrivalTime() - SimLibElapsedTime) / (float)SEC_TO_MSEC;
if (ttg < 0.0)
// TJL 11/09/03 2.0? changed to something reasonable 1.3. Should help stop AI flameouts if late.
desSpeed = 1.3F * cornerSpeed;
else
desSpeed = (sqrtf(rng) / ttg) * FTPSEC_TO_KNOTS;
desSpeed = max (desSpeed, 200.0F);
}
if (curMode == RTBMode)
desSpeed = cornerSpeed;
/*--------------*/
/* On Station ? */
/*--------------*/
if (onStation != NotThereYet)
{
if (self->GetKias() < 0.8F * cornerSpeed && onStation == Arrived)
{
AltitudeHold(-wpZ);
MachHold(cornerSpeed, self->GetKias(), TRUE);
}
else
{
if (onStation == Arrived)
{
onStation = Stabalizing;
}
if (onStation == Stabalizing)
{
if (MachHold(cornerSpeed, self->GetKias(), TRUE))
{
onStation = OnStation;
LevelTurn (2.0F, 1.0F, waypointMode);
}
AltitudeHold (holdAlt);
}
else
{
LevelTurn(2.0F, 1.0F, FALSE);
}
}
}
/*-------------------------------------*/
/* Level turn if we are far off course */
/*-------------------------------------*/
else if (waypointMode != 2)
{
if (waypointMode != 0)
{
holdAlt = -self->ZPos();
}
if (desHeading > 3.0F * DTR)
{
LevelTurn (desLoad, 1.0F, waypointMode);
waypointMode = 0;
}
else if (desHeading < -3.0F * DTR)
{
LevelTurn (desLoad, -1.0F, waypointMode);
waypointMode = 0;
}
else
{
waypointMode = 2;
holdAlt = -wpZ;
}
}
else
{
/*--------------------------*/
/* Skid to nail the heading */
/*--------------------------*/
AltitudeHold(-trackZ);
SetYpedal( desHeading * 0.05F * RTD * self->GetVt()/cornerSpeed);
if (fabs(desHeading) > 10.0F * DTR)
{
waypointMode = 1;
}
}
MachHold(desSpeed, self->GetKias(), FALSE);
}
void DigitalBrain::SelectNextWaypoint(void)
{
WayPointClass* tmpWaypoint = self->curWaypoint;
WayPointClass* wlist = self->waypoint;
UnitClass *campUnit = NULL;
WayPointClass *campCurWP = NULL;
int waypointIndex,i;
ShiAssert(!self->OnGround());
// first get our current waypoint index in the list
for ( waypointIndex = 0;
wlist && wlist != tmpWaypoint;
wlist = wlist->GetNextWP(), waypointIndex++ );
// see if we're running in tactical or campaign. If so, we want to
// synch the campaign's waypoints with ours
// if ( SimDriver.RunningCampaignOrTactical() )
{
// get the pointer to our campaign unit
campUnit = (UnitClass *)self->GetCampaignObject();
if ( campUnit ) // sanity check
{
campCurWP = campUnit->GetFirstUnitWP();
// now get the camp waypoint that corresponds to our next in the
// list by index
for ( i = 0; i <= waypointIndex; i++ )
{
if ( campCurWP ) // sanity check
campCurWP = campCurWP->GetNextWP();
}
}
}
onStation = NotThereYet;
if (self->curWaypoint) // JB 011016 CTD fix
self->curWaypoint = self->curWaypoint->GetNextWP();
// KCK: This isn't working anyway - so I'm commentting it out in order to prevent bugs
// in the ATC and Campaign
// edg: this should be OK now that an obsolute waypoint index is used to
// synch the current WP between sim and camp units.
if ( campCurWP )
{
campUnit->SetCurrentUnitWP( campCurWP );
}
waypointMode = 0;
if (!self->curWaypoint)
{
// No current waypoint, so go home
// JB 010715 If the Digi has a ground target it may switch
// between the second to last and last waypoint continuously.
groundTargetPtr = NULL;
wlist = self->waypoint;
waypointIndex = 0;
while (wlist)
{
if (wlist->GetWPAction() == WP_LAND)
{
break;
}
waypointIndex ++;
wlist = wlist->GetNextWP();
}
if (wlist)
{
// get the pointer to our campaign unit
campUnit = (UnitClass *)self->GetCampaignObject();
if ( campUnit ) // sanity check
{
campCurWP = campUnit->GetFirstUnitWP();
// now get the camp waypoint that corresponds to our next in the
// list by index
for ( i = 0; i <= waypointIndex; i++ )
{
if ( campCurWP ) // sanity check
campCurWP = campCurWP->GetNextWP();
}
}
self->curWaypoint = wlist;
}
else
{
// go back to the beginning
self->curWaypoint = self->waypoint;
campUnit->SetCurrentUnitWP( campUnit->GetFirstUnitWP() );
}
}
else if (!(tmpWaypoint->GetWPFlags() & WPF_REPEAT) &&
(self->curWaypoint->GetWPFlags() & WPF_REPEAT))
{
if (self->curWaypoint->GetWPFlags() & WPF_IP)
{
SetATCFlag(ReachedIP);
}
if (!(moreFlags & SaidSunrise)) // only say sunrise once and only insert once into FAC list
{
moreFlags |= SaidSunrise;
switch (tmpWaypoint->GetWPAction())
{
case WP_FAC:
SimDriver.facList->ForcedInsert(self);
break;
case WP_ELINT:
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_TEAM;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcAWACSON;
radioMessage->dataBlock.edata[0] = -1;
radioMessage->dataBlock.edata[1] = -1;
radioMessage->dataBlock.edata[2] = self->GetCallsignIdx();
radioMessage->dataBlock.edata[3] = self->vehicleInUnit + 1;
FalconSendMessage(radioMessage, FALSE);
// PlayRadioMessage (rcAWACSON)
// self is a pointer to the AC that is going on-line
break;
}
}
}
else if ((tmpWaypoint->GetWPFlags() & WPF_REPEAT) &&
!(self->curWaypoint->GetWPFlags() & WPF_REPEAT))
{
switch (tmpWaypoint->GetWPAction())
{
case WP_FAC:
SimDriver.facList->Remove(self);
break;
case WP_ELINT:
if(((Flight)self->GetCampaignObject())->GetFlightLeadSlot() == self->vehicleInUnit)
{
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_TEAM;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcAWACSOFF;
radioMessage->dataBlock.edata[0] = -1;
radioMessage->dataBlock.edata[1] = -1;
radioMessage->dataBlock.edata[2] = self->GetCallsignIdx();
radioMessage->dataBlock.edata[3] = self->vehicleInUnit + 1;
FalconSendMessage(radioMessage, FALSE);
}
// PlayRadioMessage (rcAWACSOFF)
// self is a pointer to the AC that is going on-line
break; }
}
// 2001-07-04 ADDED BY S.G. RE_EVALUATE YOUR GROUND WEAPONS WHEN SWITCHING WAYPOINT...
if (!IsSetATC(HasAGWeapon) && (missionClass == AGMission)) {
MissionClassEnum tmpMission = missionClass;
//missionClass = AAMission; // Without this, SelectGroundWeapon might call SelectNextWaypoint which will result in a stack overflow
SelectGroundWeapon();
missionClass = tmpMission;
}
// END OF ADDED SECTION
SetWaypointSpecificStuff();
}
void DigitalBrain::SetWaypointSpecificStuff(void)
{
WayPointClass* wlist;
int waypointIndex;
if (self->curWaypoint)
{
switch (self->curWaypoint->GetWPAction())
{
case WP_AIRDROP:
if(RuleMode != rINSTANT_ACTION && RuleMode != rDOGFIGHT)
{
if(((Flight)self->GetCampaignObject())->GetFlightLeadSlot() == self->vehicleInUnit)
{
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_TEAM;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcAIRDROPAPPROACH;
radioMessage->dataBlock.edata[0] = self->GetCallsignIdx();
radioMessage->dataBlock.edata[1] = self->vehicleInUnit + 1;
FalconSendMessage(radioMessage, FALSE);
}
}
// PlayRadioMessage (rcAIRDROPDONE)
// self is a pointer to the AC that has dropped troops/cargo
break;
case WP_ELINT:
case WP_NOTHING:
case WP_TAKEOFF:
case WP_ASSEMBLE:
//TJL 11/10/03 Adding sounds?
case WP_POSTASSEMBLE:
case WP_REFUEL:
case WP_REARM:
case WP_LAND:
case WP_RECON:
case WP_RESCUE:
case WP_ASW:
case WP_TANKER:
case WP_JAM:
case WP_FAC:
break;
case WP_ESCORT:
break;
case WP_CA:
break;
case WP_CAP:
break;
case WP_INTERCEPT:
break;
case WP_GNDSTRIKE:
case WP_NAVSTRIKE:
case WP_STRIKE:
case WP_BOMB:
case WP_SAD:
//TJL 11/10/03 Sounds?
#if 0 // Retro 20May2004 - fixed logic
if (missionType == (AMIS_OCASTRIKE || AMIS_INTSTRIKE || AMIS_STRIKE || AMIS_DEEPSTRIKE || AMIS_STSTRIKE || AMIS_STRATBOMB) )
#else
if ((missionType == AMIS_OCASTRIKE) ||
(missionType == AMIS_INTSTRIKE) ||
(missionType == AMIS_STRIKE) ||
(missionType == AMIS_DEEPSTRIKE)||
(missionType == AMIS_STSTRIKE) ||
(missionType == AMIS_STRATBOMB) )
#endif // Retro 20May2004 - end
{
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_PACKAGE;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcFLIGHTIN;
radioMessage->dataBlock.edata[0] = ((Flight)this)->callsign_id;
radioMessage->dataBlock.edata[1] = ((Flight)this)->GetFlightLeadCallNumber();
radioMessage->dataBlock.edata[2] = rand()%12;
}
//End
if (missionType == AMIS_CAS)
{
FalconFACMessage* facMsg;
facMsg = new FalconFACMessage (self->Id(), FalconLocalGame);
facMsg->dataBlock.type = FalconFACMessage::CheckIn;
FalconSendMessage (facMsg,FALSE);
}
break;
case WP_SEAD:
break;
default:
// MonoPrint ("Why am I here (Digi GetBrain)\n");
break;
}
}
else
{
}
// For a player, make sure the HUD and ICP know the current waypoint
if (self == SimDriver.GetPlayerEntity())
{
for ( waypointIndex = 0, wlist = self->waypoint;
wlist && wlist != self->curWaypoint;
wlist = wlist->GetNextWP(), waypointIndex++ );
self->FCC->SetWaypointNum (waypointIndex);
}
// Marco edit - set Formation depending on waypoint selected
if (SimDriver.GetPlayerEntity() != self && !isWing && self->curWaypoint->GetWPFormation() != mCurFormation)
{
mCurFormation = self->curWaypoint->GetWPFormation() ;
AiSendCommand (self, mCurFormation, AiFlight, FalconNullId);
}
// End Marco Edit
}
// Cobra - Utility to get current WP index
int DigitalBrain::GetWaypointIndex(void)
{
WayPointClass* tmpWaypoint = self->curWaypoint;
WayPointClass* wlist = self->waypoint;
int waypointIndex;
// get our current waypoint index in the list
for ( waypointIndex = 0;
wlist && wlist != tmpWaypoint;
wlist = wlist->GetNextWP(), waypointIndex++ );
return waypointIndex;
}
// Cobra - Utility to get target WP index
int DigitalBrain::GetTargetWPIndex(void)
{
WayPointClass* wlist = self->waypoint;
int waypointIndex = 0;
// get the target waypoint index in the list
while (wlist)
{
if (wlist->GetWPFlags() & WPF_TARGET)
break;
wlist = wlist->GetNextWP();
waypointIndex++ ;
}
if (wlist)
return waypointIndex;
else
return -1;
}
/*
** DoPickupAirdrop: This is a cheesy routine to allow troops to be picked
** up or airdropped. Given time constraints we're just going to fly in
** low and slow and pick them up or drop them off with the campaign calls.
*/
void
DigitalBrain::DoPickupAirdrop(void)
{
float xerr, yerr;
float rng;
float desSpeed, desAlt;
float gainCtrl;
Unit cargo, unit;
GridIndex x,y;
// prevent too much gain in controls
// except when we're too close to ground
gainCtrl = 0.25f;
onStation = NotThereYet; // jpo - force it to keep going to pickup
// get where we're supposed to go
float tx, ty, tz;
self->curWaypoint->GetLocation (&tx, &ty, &tz);
SetTrackPoint(tx, ty, tz);
// range info
xerr = trackX - self->XPos();
yerr = trackY - self->YPos();
rng = xerr * xerr + yerr * yerr;
// if we're still far away just use the regular waypoint stuff
if ( rng > 10000.0f * 10000.0f )
{
if(((AircraftClass*) self)->af->GetSimpleMode())
{
SimpleGoToCurrentWaypoint();
}
else
{
GoToCurrentWaypoint();
}
return;
}
// now pick our speed based on final approach range
if ( rng < 5000.0f * 5000.0f )
{
desSpeed = 50.0f * KNOTS_TO_FTPSEC;
desAlt = 40.0f;
}
else
{
desSpeed = 150.0f * KNOTS_TO_FTPSEC;
desAlt = 500.0f;
}
// terrain follwing....
trackZ = OTWDriver.GetGroundLevel( self->XPos() + self->XDelta(),
self->YPos() + self->YDelta() );
// if we're below track alt, kick us up a bit harder so we don't plow
// into steeper slopes
if ( self->ZPos() - trackZ > -desAlt )
{
trackZ = trackZ - 500.0f - ( self->ZPos() - trackZ + 500.0f ) * 2.0f;
gainCtrl = 1.5f;
}
else
trackZ -= desAlt;
// are we there yet?
if ( rng < 500.0f * 500.0f )
{
if ( self->curWaypoint->GetWPAction() == WP_PICKUP )
{
// Load the airborne battalion.
cargo = (Unit) self->curWaypoint->GetWPTarget();
unit = (Unit)self->GetCampaignObject();
if (cargo && unit)
{
unit->SetCargoId(cargo->Id());
cargo->SetCargoId(unit->Id());
cargo->SetInactive(1);
unit->LoadUnit(cargo);
if(RuleMode != rINSTANT_ACTION && RuleMode != rDOGFIGHT)
{
if(((Flight)self->GetCampaignObject())->GetFlightLeadSlot() == self->vehicleInUnit)
{
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_TEAM;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcPACKJOINED; // best I can find - JPO
radioMessage->dataBlock.edata[0] = self->GetCallsignIdx();
radioMessage->dataBlock.edata[1] = self->vehicleInUnit + 1;
FalconSendMessage(radioMessage, FALSE);
}
}
}
}
else if ( self->curWaypoint->GetWPAction() == WP_AIRDROP )
{
// Load the airborne battalion.
cargo = (Unit) self->curWaypoint->GetWPTarget();
unit = (Unit)self->GetCampaignObject();
if (cargo && unit && unit->Cargo())
{
unit->UnloadUnit();
cargo->SetCargoId(FalconNullId);
cargo->SetInactive(0);
self->curWaypoint->GetWPLocation(&x,&y);
cargo->SetLocation(x,y);
if(RuleMode != rINSTANT_ACTION && RuleMode != rDOGFIGHT)
{
if(((Flight)self->GetCampaignObject())->GetFlightLeadSlot() == self->vehicleInUnit)
{
FalconRadioChatterMessage* radioMessage = new FalconRadioChatterMessage( self->Id(), FalconLocalSession );
radioMessage->dataBlock.from = self->Id();
radioMessage->dataBlock.to = MESSAGE_FOR_TEAM;
radioMessage->dataBlock.voice_id = ((Flight)(self->GetCampaignObject()))->GetPilotVoiceID(self->vehicleInUnit);
radioMessage->dataBlock.message = rcAIRDROPDONE;
radioMessage->dataBlock.edata[0] = self->GetCallsignIdx();
radioMessage->dataBlock.edata[1] = self->vehicleInUnit + 1;
FalconSendMessage(radioMessage, FALSE);
}
}
}
}
SelectNextWaypoint();
}
// head to track point
TrackPoint(0.0F, desSpeed );
// modify p and r stick settings by gain control
pStick *= gainCtrl;
// rStick *= gainCtrl;
}
| 31.011513 | 168 | 0.622753 | [
"object"
] |
3196807bb0ca5bab2b36a28cb31cebd2fd8a7b42 | 4,368 | cc | C++ | src/monitor.cc | mithro/hgdb | 8a028b9ee8751a2cc77cd1c889e96059747b2f18 | [
"BSD-2-Clause"
] | null | null | null | src/monitor.cc | mithro/hgdb | 8a028b9ee8751a2cc77cd1c889e96059747b2f18 | [
"BSD-2-Clause"
] | null | null | null | src/monitor.cc | mithro/hgdb | 8a028b9ee8751a2cc77cd1c889e96059747b2f18 | [
"BSD-2-Clause"
] | null | null | null | #include "monitor.hh"
#include "debug.hh"
namespace hgdb {
Monitor::Monitor() {
// everything is 0 if not set up
get_value = [](const std::string&) { return 0; };
}
Monitor::Monitor(std::function<std::optional<int64_t>(const std::string&)> get_value)
: get_value(std::move(get_value)) {}
uint64_t Monitor::add_monitor_variable(const std::string& full_name, WatchType watch_type) {
// we assume full name is checked already
// need to search if we have the same name already
auto watched = is_monitored(full_name, watch_type);
if (watched) {
return *watched;
}
// old clang-tidy reports memory leak for .value = make_shared
auto value_ptr = std::make_shared<std::optional<int64_t>>();
auto w = WatchVariable{.type = watch_type, .full_name = full_name, .value = value_ptr};
watched_variables_.emplace(watch_id_count_, w);
return watch_id_count_++;
}
uint64_t Monitor::add_monitor_variable(const std::string& full_name, WatchType watch_type,
std::shared_ptr<std::optional<int64_t>> value) {
auto v = add_monitor_variable(full_name, watch_type);
watched_variables_.at(v).value = std::move(value);
return v;
}
void Monitor::remove_monitor_variable(uint64_t watch_id) {
if (watched_variables_.find(watch_id) != watched_variables_.end()) {
watched_variables_.erase(watch_id);
}
}
std::optional<uint64_t> Monitor::is_monitored(const std::string& full_name,
WatchType watch_type) const {
for (auto const& [id, var] : watched_variables_) {
if (var.full_name == full_name && var.type == watch_type) [[unlikely]] {
// reuse the existing ID
return id;
}
}
return std::nullopt;
}
std::shared_ptr<std::optional<int64_t>> Monitor::get_watched_value_ptr(
const std::unordered_set<std::string>& var_names, WatchType type) const {
for (auto const& [id, var] : watched_variables_) {
if (var_names.find(var.full_name) != var_names.end() && var.type == type) {
// reuse the existing ID
return var.value;
}
}
return nullptr;
}
std::vector<std::pair<uint64_t, std::string>> Monitor::get_watched_values(WatchType type) {
std::vector<std::pair<uint64_t, std::string>> result;
// this is the maximum size
result.reserve(watched_variables_.size());
for (auto& [watch_id, watch_var] : watched_variables_) {
if (watch_var.type != type) continue;
switch (watch_var.type) {
case WatchType::breakpoint:
case WatchType::clock_edge: {
auto value = get_value(watch_var.full_name);
std::string str_value;
if (value) {
str_value = std::to_string(*value);
} else {
str_value = Debugger::error_value_str;
}
result.emplace_back(std::make_pair(watch_id, str_value));
break;
}
case WatchType::data:
case WatchType::changed: {
// only if values are changed
auto [changed, value] = var_changed(watch_id);
if (changed) {
auto str_value = std::to_string(*value);
result.emplace_back(std::make_pair(watch_id, str_value));
}
break;
}
}
}
return result;
}
uint64_t Monitor::num_watches(const std::string& name, WatchType type) const {
uint64_t result = 0;
for (auto const& iter : watched_variables_) {
if (iter.second.full_name == name && iter.second.type == type) {
result++;
}
}
return result;
}
std::pair<bool, std::optional<int64_t>> Monitor::var_changed(uint64_t id) {
if (watched_variables_.find(id) == watched_variables_.end()) [[unlikely]] {
return {false, {}};
}
auto& watch_var = watched_variables_.at(id);
auto value = get_value(watch_var.full_name);
if (value) {
bool changed = false;
if (!watch_var.value->has_value() || watch_var.value->value() != *value) changed = true;
if (changed) {
*watch_var.value = value;
}
return {changed, value};
}
return {false, {}};
}
} // namespace hgdb | 34.393701 | 96 | 0.598214 | [
"vector"
] |
319cc1f802067dd572fce491ba0263e9bd3de7f9 | 6,740 | cxx | C++ | main/sd/source/ui/slidesorter/model/SlsPageDescriptor.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sd/source/ui/slidesorter/model/SlsPageDescriptor.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sd/source/ui/slidesorter/model/SlsPageDescriptor.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#include <svx/svdopage.hxx>
#include <svx/svdpagv.hxx>
#include <svx/sdr/contact/viewcontact.hxx>
#include <svx/sdr/contact/viewobjectcontact.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
namespace sd { namespace slidesorter { namespace model {
PageDescriptor::PageDescriptor (
const Reference<drawing::XDrawPage>& rxPage,
SdPage* pPage,
const sal_Int32 nIndex)
: mpPage(pPage),
mxPage(rxPage),
mpMasterPage(NULL),
mnIndex(nIndex),
maBoundingBox(),
maVisualState(nIndex),
mbIsSelected(false),
mbWasSelected(false),
mbIsVisible(false),
mbIsFocused(false),
mbIsCurrent(false),
mbIsMouseOver(false),
mbHasTransition(false)
{
OSL_ASSERT(mpPage);
OSL_ASSERT(mpPage == SdPage::getImplementation(rxPage));
if (mpPage != NULL)
{
if (mpPage->TRG_HasMasterPage())
mpMasterPage = &mpPage->TRG_GetMasterPage();
if (mpPage->getTransitionType() > 0)
mbHasTransition = true;
}
}
PageDescriptor::~PageDescriptor (void)
{
}
SdPage* PageDescriptor::GetPage (void) const
{
return mpPage;
}
Reference<drawing::XDrawPage> PageDescriptor::GetXDrawPage (void) const
{
return mxPage;
}
sal_Int32 PageDescriptor::GetPageIndex (void) const
{
return mnIndex;
}
void PageDescriptor::SetPageIndex (const sal_Int32 nNewIndex)
{
mnIndex = nNewIndex;
maVisualState.mnPageId = nNewIndex;
}
bool PageDescriptor::UpdateMasterPage (void)
{
const SdrPage* pMaster = NULL;
if (mpPage!=NULL && mpPage->TRG_HasMasterPage())
pMaster = &mpPage->TRG_GetMasterPage();
if (mpMasterPage != pMaster)
{
mpMasterPage = pMaster;
return true;
}
else
return false;
}
bool PageDescriptor::UpdateTransitionFlag (void)
{
bool bHasSlideTransition (false);
if (mpPage != NULL)
bHasSlideTransition = mpPage->getTransitionType() > 0;
if (bHasSlideTransition != mbHasTransition)
{
mbHasTransition = bHasSlideTransition;
return true;
}
else
return false;
}
bool PageDescriptor::HasState (const State eState) const
{
switch (eState)
{
case ST_Visible:
return mbIsVisible;
case ST_Selected:
return mbIsSelected;
case ST_WasSelected:
return mbWasSelected;
case ST_Focused:
return mbIsFocused;
case ST_MouseOver:
return mbIsMouseOver;
case ST_Current:
return mbIsCurrent;
case ST_Excluded:
return mpPage!=NULL && mpPage->IsExcluded();
default:
OSL_ASSERT(false);
return false;
}
}
bool PageDescriptor::SetState (const State eState, const bool bNewStateValue)
{
bool bModified (false);
switch (eState)
{
case ST_Visible:
bModified = (bNewStateValue!=mbIsVisible);
if (bModified)
mbIsVisible = bNewStateValue;
break;
case ST_Selected:
bModified = (bNewStateValue!=mbIsSelected);
if (bModified)
mbIsSelected = bNewStateValue;
break;
case ST_WasSelected:
bModified = (bNewStateValue!=mbWasSelected);
if (bModified)
mbWasSelected = bNewStateValue;
break;
case ST_Focused:
bModified = (bNewStateValue!=mbIsFocused);
if (bModified)
mbIsFocused = bNewStateValue;
break;
case ST_MouseOver:
bModified = (bNewStateValue!=mbIsMouseOver);
if (bModified)
mbIsMouseOver = bNewStateValue;
break;
case ST_Current:
bModified = (bNewStateValue!=mbIsCurrent);
if (bModified)
mbIsCurrent = bNewStateValue;
break;
case ST_Excluded:
// This is a state of the page and has to be handled differently
// from the view-only states.
if (mpPage != NULL)
if (bNewStateValue != (mpPage->IsExcluded()==sal_True))
{
mpPage->SetExcluded(bNewStateValue);
bModified = true;
}
break;
}
if (bModified)
maVisualState.UpdateVisualState(*this);
return bModified;
}
VisualState& PageDescriptor::GetVisualState (void)
{
return maVisualState;
}
bool PageDescriptor::GetCoreSelection (void)
{
if (mpPage!=NULL && (mpPage->IsSelected()==sal_True) != mbIsSelected)
return SetState(ST_Selected, !mbIsSelected);
else
return false;
}
void PageDescriptor::SetCoreSelection (void)
{
if (mpPage != NULL)
if (HasState(ST_Selected))
mpPage->SetSelected(sal_True);
else
mpPage->SetSelected(sal_False);
else
{
OSL_ASSERT(mpPage!=NULL);
}
}
Rectangle PageDescriptor::GetBoundingBox (void) const
{
Rectangle aBox (maBoundingBox);
const Point aOffset (maVisualState.GetLocationOffset());
aBox.Move(aOffset.X(), aOffset.Y());
return aBox;
}
Point PageDescriptor::GetLocation (const bool bIgnoreOffset) const
{
if (bIgnoreOffset)
return maBoundingBox.TopLeft();
else
return maBoundingBox.TopLeft() + maVisualState.GetLocationOffset();
}
void PageDescriptor::SetBoundingBox (const Rectangle& rBoundingBox)
{
maBoundingBox = rBoundingBox;
}
} } } // end of namespace ::sd::slidesorter::model
| 21.812298 | 77 | 0.617953 | [
"model"
] |
31a2066c89eb6742bd843b1a4108382d6f1f9995 | 2,240 | cpp | C++ | booserver/batch_config.cpp | sundersb/booserver | c91dcdd33af3aba590d177f50dafe994a16ba24b | [
"BSD-2-Clause"
] | 1 | 2019-03-03T04:40:07.000Z | 2019-03-03T04:40:07.000Z | booserver/batch_config.cpp | sundersb/booserver | c91dcdd33af3aba590d177f50dafe994a16ba24b | [
"BSD-2-Clause"
] | null | null | null | booserver/batch_config.cpp | sundersb/booserver | c91dcdd33af3aba590d177f50dafe994a16ba24b | [
"BSD-2-Clause"
] | null | null | null | #include "batch_config.h"
#include <dirent.h>
#include <sys/stat.h>
const std::string PREFIX_COLOR("color_");
const std::string SUFFIX_COLOR(".conf");
const std::string SUFFIX_IMAGE("_2160.png");
std::vector<std::string> readDir(const std::string &path) {
std::vector<std::string> result;
struct dirent *entry;
struct stat attr;
DIR *dir = opendir(path.c_str());
if (dir) {
while (entry = readdir(dir)) {
if (stat(entry->d_name, &attr) == 0) {
if (S_ISREG(attr.st_mode))
result.push_back(std::string(entry->d_name));
}
}
closedir(dir);
}
return result;
}
bool startsWith(const std::string &lhs, const std::string &rhs) {
if (lhs.empty() != rhs.empty())
return false;
if (lhs.length() < rhs.length())
return false;
return lhs.compare(0, rhs.length(), rhs) == 0;
}
bool endsWith(const std::string &lhs, const std::string &rhs) {
if (lhs.empty() != rhs.empty())
return false;
if (lhs.length() < rhs.length())
return false;
return lhs.compare(lhs.length() - rhs.length(), rhs.length(), rhs) == 0;
}
isColor(const std::string &fileName) {
return startsWith(fileName, PREFIX_COLOR)
&& endsWith(fileName, SUFFIX_COLOR);
}
isImage(const std::string &fileName) {
return endsWith(fileName, SUFFIX_IMAGE);
}
BatchFile getColorConfig(const std::string &fileName) {
std::string title = fileName.substr(PREFIX_COLOR.length(),
fileName.length() - SUFFIX_COLOR.length() - PREFIX_COLOR.length());
return BatchFile(fileName, title);
}
BatchFile getImageConfig(const std::string &fileName) {
std::string title = fileName.substr(0, fileName.length() - SUFFIX_IMAGE.length());
return BatchFile(fileName, title);
}
BatchFile::BatchFile(const std::string &name, const std::string &title):
name(name),
title(title) {}
BatchConfig::BatchConfig(){
}
BatchConfig BatchConfig::get(const std::string &path) {
BatchConfig result;
std::vector<std::string> files = readDir(path);
for (const std::string &file : files) {
if (isColor(file))
result.colors.emplace_back(getColorConfig(file));
else if (isImage(file))
result.images.emplace_back(getImageConfig(file));
}
return result;
}
| 24.347826 | 84 | 0.661161 | [
"vector"
] |
31a404688c4cbfcd2e99adcab077c8adc1865046 | 772 | cpp | C++ | GeeksForGeeks/Bottom View of Binary Tree.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Bottom View of Binary Tree.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Bottom View of Binary Tree.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <bitset>
#include <climits>
#include <queue>
#include <stack>
using namespace std;
// TREE
void preorder(vector<int> &ve, Node * root){
if(!root)
return;
preorder(ve, root->left);
if(root->left == NULL){
ve.push_back(root->data);
}
else if(root->right == NULL){
ve.push_back(root->data);
}
else{
if(root->left->left == NULL && root->right->right == NULL){
ve.push_back(root->data);
}
}
preorder(ve, root->right);
}
vector <int> bottomView(Node *root){
vector<int> ve;
if(!root)
return ve;
preorder(ve, root);
} | 19.3 | 67 | 0.582902 | [
"vector"
] |
b3b369e5e57f03ffe55f57f94e41c038578cc8b7 | 1,555 | hpp | C++ | src/util/usage_log_t.hpp | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | src/util/usage_log_t.hpp | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | src/util/usage_log_t.hpp | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | #ifndef PROJ_LIB_UTIL_USAGE_LOG_H
#define PROJ_LIB_UTIL_USAGE_LOG_H
#include <QDebug>
#include <memory> // gets us pointer_traits
#include <string>
namespace project
{
// TODO: consider adding a template arg for __LINE__, using https://stackoverflow.com/q/3773378/10278
template <class WrappedPtrIsh> // WrappedPtrIsh can be a raw pointer or a smart ptr
class Log
{
public:
typedef typename std::pointer_traits<WrappedPtrIsh>::element_type obj_type;
// Look for uses of this helper throughout view_model_collection.cc to see
// how it makes it less tedious to comprehensively log all interactions with
// any member-object you with to track.
explicit Log( std::string s, const WrappedPtrIsh& wrapped )
: str( s ), w( wrapped )
{
}
obj_type* operator->()
{
// Clearly label these special log lines, so that anyone who gets
// curious about them can locate this template class and understand why
// these log lines are a bit different.
constexpr char PREFIX[] = "usage_log_t. (uses name mangling) about to call:";
std::string nextFuncCall = "::" + str;
// typeid().name yields a MANGLED type name, but it is "close enough"
nextFuncCall = typeid( obj_type ).name() + nextFuncCall;
qInfo() << PREFIX << nextFuncCall.c_str();
return &*w; // <-- this looks funny, but works for raw pointer and unique_ptr
}
private:
const std::string str;
const WrappedPtrIsh& w;
};
} // namespace project
#endif // PROJ_LIB_UTIL_USAGE_LOG_H
| 33.085106 | 101 | 0.688746 | [
"object"
] |
b3b3f59603ef00745f135d95fccd87474068cc26 | 974 | hpp | C++ | VSProject/LeetCodeSol/Src/TwoSumII.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | VSProject/LeetCodeSol/Src/TwoSumII.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | VSProject/LeetCodeSol/Src/TwoSumII.hpp | wangxiaotao1980/leetCodeCPP | 1806c00cd89eacddbdd20a7c33875f54400a20a8 | [
"MIT"
] | null | null | null | /*******************************************************************************************
* @file TwoSumII-InputAArrayIsSorted.hpp 2019\2\3 17:14:32 $
* @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试)
* @note Leetcode 167. Two Sum II - Input array is sorted
*******************************************************************************************/
#ifndef TWOSUMII_INPUTAARRAYISSORTED_A2BEE5A1_FF49_4FEE_97CE_9E3498EAB565_HPP__
#define TWOSUMII_INPUTAARRAYISSORTED_A2BEE5A1_FF49_4FEE_97CE_9E3498EAB565_HPP__
#include <vector>
/*******************************************************************************************/
/**
* The class <code>TwoSumII<code>
*
*/
class TwoSumII
{
public:
std::vector<int> twoSum(std::vector<int>& numbers, int target);
};
/*******************************************************************************************/
#endif// TWOSUMII_INPUTAARRAYISSORTED_A2BEE5A1_FF49_4FEE_97CE_9E3498EAB565_HPP__
| 40.583333 | 93 | 0.477413 | [
"vector"
] |
b3bd00555df23920958a020fbf3e90055da0c2ca | 2,325 | cpp | C++ | moses/moses/TranslationModel/RuleTable/LoaderFactory.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-01-25T00:51:56.000Z | 2022-01-07T15:09:38.000Z | moses/moses/TranslationModel/RuleTable/LoaderFactory.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2021-11-25T18:08:22.000Z | 2021-11-25T18:08:22.000Z | moses/moses/TranslationModel/RuleTable/LoaderFactory.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-06-08T08:36:27.000Z | 2021-12-26T20:36:16.000Z | /***********************************************************************
Moses - statistical machine translation system
Copyright (C) 2006-2011 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "LoaderFactory.h"
#include "moses/UserMessage.h"
#include "moses/Util.h"
#include "moses/InputFileStream.h"
#include "LoaderCompact.h"
#include "LoaderHiero.h"
#include "LoaderStandard.h"
#include <sstream>
#include <iostream>
using namespace std;
namespace Moses
{
// Determines the rule table type by peeking inside the file then creates
// a suitable RuleTableLoader object.
std::auto_ptr<RuleTableLoader> RuleTableLoaderFactory::Create(
const std::string &path)
{
InputFileStream input(path);
std::string line;
bool cont = std::getline(input, line);
if (cont) {
std::vector<std::string> tokens;
Tokenize(tokens, line);
if (tokens.size() == 1) {
if (tokens[0] == "1") {
return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderCompact());
}
std::stringstream msg;
msg << "Unsupported compact rule table format: " << tokens[0];
UserMessage::Add(msg.str());
return std::auto_ptr<RuleTableLoader>();
}
else if (tokens[0] == "[X]" && tokens[1] == "|||") {
return std::auto_ptr<RuleTableLoader>(new
RuleTableLoaderHiero());
}
return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderStandard());
}
else
{ // empty phrase table
return std::auto_ptr<RuleTableLoader>(new RuleTableLoaderStandard());
}
}
} // namespace Moses
| 31.849315 | 79 | 0.664516 | [
"object",
"vector"
] |
b3bd604afae9b7978e85be3ea827c5539873c7cf | 36,937 | cpp | C++ | Mapf-solver/src/LNS.cpp | Jiaoyang-Li/Flatland | 6667f181d6f39f8c1d63f38799d7fce21ab4e87b | [
"BSD-4-Clause-UC"
] | 21 | 2021-01-14T09:39:07.000Z | 2022-03-25T16:19:13.000Z | Mapf-solver/src/LNS.cpp | lj086/Flatland | 6667f181d6f39f8c1d63f38799d7fce21ab4e87b | [
"BSD-4-Clause-UC"
] | 1 | 2022-03-07T08:05:55.000Z | 2022-03-07T08:05:55.000Z | Mapf-solver/src/LNS.cpp | lj086/Flatland | 6667f181d6f39f8c1d63f38799d7fce21ab4e87b | [
"BSD-4-Clause-UC"
] | 9 | 2021-01-14T09:39:08.000Z | 2022-03-24T11:16:44.000Z | /*
* @author: Team An_old_driver
* @created: 09-2020
* Copyright (c) 2020 The University of Southern California. All Rights Reserved.
* Copyrights licensed under an Academic/non-profit use license.
* See the accompanying LICENSE file for terms.
*/
#include "LNS.h"
bool LNS::run(float _hard_time_limit, float _soft_time_limit, float success_rate, int max_iterations)
{
start_time = Time::now();
hard_time_limit = _hard_time_limit;
soft_time_limit = min(_soft_time_limit, hard_time_limit);
if(! skip_pp) {
if (!getInitialSolution(success_rate,max_iterations)) { // get initial solution
return false;
}
}
int solution_cost = 0;
int sum_of_showup_time = 0;
for (const auto& path : al.paths_all)
{
if (path.empty())
{
solution_cost += al.constraintTable.length_max;
initial_makespan = al.constraintTable.length_max;
}
else
{
solution_cost += (int)path.size() - 1;
initial_makespan = max((int)path.size() - 1, initial_makespan);
for (int t = 0; t < (int)path.size(); t++)
{
if (path[t].location >= 0)
{
sum_of_showup_time += t;
break;
}
}
}
}
runtime = ((fsec)(Time::now() - start_time)).count();
initial_runtime = runtime;
initial_sum_of_costs = solution_cost;
makespan = initial_makespan;
if (options1.debug)
cout << "Initial solution cost = " << solution_cost << ", "
<< "travel time = " << solution_cost - sum_of_showup_time << ", "
<< "makespan = " << initial_makespan << ", "
<< "runtime = " << runtime << endl;
// iteration_stats.emplace_back(al.agents_all.size(), 0, runtime, runtime, makespan, solution_cost,
// destroy_strategy, (double)(solution_cost) / max_timestep / al.agents_all.size(), 0, 0, 0);
if(pp_only || al.getNumOfAllAgents() == 1) {
if (max_iterations>0 && this->complete!= nullptr && this->complete->load()<0) {
this->complete->store(solution_cost);
}
else if( max_iterations == 0 && this->complete!= nullptr && this->agent_priority_strategy==3){
this->complete->store(solution_cost);
}
else if( max_iterations == 0 && this->complete!= nullptr && this->agent_priority_strategy!=3){
if (solution_cost < -this->complete->load()) {
this->complete->store(-solution_cost);
}
}
return true;
}
if (destroy_strategy == 3)
{
adaptive_destroy = true;
iterative_destroy = false;
destroy_heuristics.assign(3, 1);
}
else if (destroy_strategy == 4)
{
adaptive_destroy = false;
iterative_destroy = true;
}
else // fixed destroy strategy
{
adaptive_destroy = false;
iterative_destroy = false;
}
boost::unordered_set<int> tabu_list;
bool succ;
auto old_runtime = runtime;
iterations = 0;
while (runtime < soft_time_limit && iterations < max_iterations)
{
if (this->complete!= nullptr &&
((this->agent_priority_strategy==3 && solution_cost > -this->complete->load())
||(this->agent_priority_strategy!=3 && (this->complete->load()>=0 ||solution_cost > -this->complete->load() )))){
break;
}
iterations++;
runtime =((fsec)(Time::now() - start_time)).count();
if (al.getNumOfAllAgents() < 2 * max_group_size)
{
neighbors.resize(al.getNumOfAllAgents());
for (int i = 0; i < al.getNumOfAllAgents(); i++)
neighbors[i] = i;
sortNeighborsRandomly();
neighbors.resize(min(max_group_size, al.getNumOfAllAgents()));
replanByPP();
runtime = ((fsec)(Time::now() - start_time)).count();
solution_cost += delta_costs;
if (options1.debug)
cout << "Iteration " << iterations << ", "
<< "group size = " << neighbors.size() << ", "
<< "solution cost = " << solution_cost << ", "
<< "remaining time = " << soft_time_limit - runtime << endl;
//iteration_stats.emplace_back(neighbors.size(), 0, runtime, runtime - old_runtime, makespan, solution_cost,
// destroy_strategy, (double)(solution_cost) / max_timestep / al.agents_all.size(), 0, 0, 0);
old_runtime = runtime;
continue;
}
if (adaptive_destroy)
{
double sum = 0;
for (const auto& h : destroy_heuristics)
sum += h;
if (options1.debug)
{
cout << "destroy heuristics = ";
for (const auto& h : destroy_heuristics)
cout << h / sum << ",";
}
double r = (double) rand() / RAND_MAX;
if (r * sum < destroy_heuristics[0])
destroy_strategy = 0;
else if (r * sum < destroy_heuristics[0] + destroy_heuristics[1])
destroy_strategy = 1;
else
destroy_strategy = 2;
if (options1.debug)
cout << "Choose destroy strategy " << destroy_strategy << endl;
}
else if (iterative_destroy)
{
destroy_strategy = (destroy_strategy + 1) % 3;
}
switch (destroy_strategy)
{
case 0:
generateNeighborByRandomWalk(tabu_list);
break;
case 1:
succ = generateNeighborByStart();
if(!succ) { // no two agents have the same start locations
if(this->complete!= nullptr && this->agent_priority_strategy==3){
this->complete->store(solution_cost);
}
else if( this->complete!= nullptr && this->agent_priority_strategy!=3){
if (solution_cost < -this->complete->load()) {
this->complete->store(-solution_cost);
}
}
return true;
}
break;
case 2:
//if (rand() % 2)
succ = generateNeighborByIntersection();
//else
// succ = generateNeighborByTemporalIntersection();
if(!succ) // the selected intersection has fewer than 2 agents
continue;
break;
default:
cout << "Wrong neighbor generation strategy" << endl;
exit(0);
}
assert(replan_strategy == 1);
switch (prirority_ordering_strategy) // generate priority ordering for prioritized planning
{
case 0:
sortNeighborsRandomly();
break;
case 1:
sortNeighborsByRegrets();
break;
default:
cout << "Wrong prirority ordering strategy" << endl;
exit(0);
}
replanByPP();
if (adaptive_destroy) // update destroy heuristics
{
if (delta_costs < 0)
destroy_heuristics[destroy_strategy] = reaction_factor * (-delta_costs)
+ (1 - reaction_factor) * destroy_heuristics[destroy_strategy];
else
destroy_heuristics[destroy_strategy] = (1 - decay_factor) * destroy_heuristics[destroy_strategy];
}
runtime = ((fsec)(Time::now() - start_time)).count();
solution_cost += delta_costs;
if (options1.debug)
cout << "Iteration " << iterations << ", "
<< "group size = " << neighbors.size() << ", "
<< "solution cost = " << solution_cost << ", "
<< "remaining time = " << soft_time_limit - runtime << endl;
//iteration_stats.emplace_back(neighbors.size(), 0, runtime, runtime - old_runtime, makespan, solution_cost,
// destroy_strategy, (double)(solution_cost) / max_timestep / al.agents_all.size(), 0, 0, 0);
old_runtime = runtime;
if (replan_strategy == 0 && max_group_size > al.agents_all.size()) {
if(this->complete!= nullptr && this->agent_priority_strategy==3){
this->complete->store(solution_cost);
}
else if( this->complete!= nullptr && this->agent_priority_strategy!=3){
if (solution_cost < -this->complete->load()) {
this->complete->store(-solution_cost);
}
}
return true; // CBS has replanned paths for all agents. No need for further iterations
}
}
for (const auto& path : al.paths_all)
{
if (path.empty())
{
sum_of_costs += al.constraintTable.length_max;
makespan = al.constraintTable.length_max;
}
else
{
sum_of_costs += (int)path.size() - 1;
makespan = max(makespan, (int)path.size() - 1);
}
}
cout << "LNS improves the solution to: Sum of costs = " << sum_of_costs << " and makespan = " << makespan <<" runtime "<< runtime<< " priority "<<this->agent_priority_strategy<< endl;
if(this->complete!= nullptr && this->agent_priority_strategy==3){
this->complete->store(solution_cost);
}
else if( this->complete!= nullptr && this->agent_priority_strategy!=3){
if (solution_cost < -this->complete->load()) {
this->complete->store(-solution_cost);
}
}
return true;
}
//bool LNS::replan(float time_limit)
//{
// start_time = Time::now();
// max_timestep = al.constraintTable.length_max;
// al.num_of_agents = 1;
// al.agents.resize(1);
//
// map<int, list<int>> agent_groups; // key = path length, value = list of agents
// int makespan = 0;
// for (int i = 0; i < al.getNumOfAllAgents(); i++)
// {
// if (al.agents_all[i].status >= 2)
// continue;
// if (al.paths_all[i].empty())
// {
// makespan = max_timestep * 2;
// agent_groups[max_timestep * 2].push_back(i);
// }
// else
// {
// makespan = max(makespan, (int) al.paths_all[i].size() - 1);
// if (al.agents_all[i].status == 0)
// agent_groups[al.paths_all[i].size() - 1].push_back(i);
// }
// }
// bool empty_path = false;
// for (auto it = agent_groups.rbegin(); it != agent_groups.rend() && !empty_path; ++it) // replan paths from the longest to the shortest
// {
//
// for (auto i : it->second)
// {
// runtime = ((fsec) (Time::now() - start_time)).count();
// if (runtime >= time_limit)
// return true;
//
// auto copy = al.paths_all[i];
// al.constraintTable.delete_path(i, al.paths_all[i]);
// runtime = ((fsec) (Time::now() - start_time)).count();
// al.agents[0] = &al.agents_all[i];
// SIPP planner(ml,al,f_w,time_limit - runtime,options1);
// planner.search();
// assert(planner.path.size() <= copy.size());
// if (planner.path.empty())
// {
// addAgentPath(i, copy);
// empty_path = true;
// if (it->first < max_timestep * 2)
// break;
// }
// else
// {
// addAgentPath(i, planner.path);
// if (copy.size() == planner.path.size()) // fail to decrease the makespan
// {
// return true;
// }
// }
// }
// }
// return true;
//}
bool LNS::replan(float time_limit)
{
start_time = Time::now();
max_timestep = al.constraintTable.length_max;
set<int> tabu_list; // record the agents already been replanned
al.num_of_agents = 1;
al.agents.resize(1);
list<list<pair<int, int>>> agent_groups;
for (const auto& mal_agent : al.new_malfunction_agents)
{
// find the intersections in front of the mal_agent
list<tuple<int, int, int> > future_intersections; // <location, timestep>
int t = 0;
if (al.agents_all[mal_agent].status == 0) // the mal agent is still in the station
{
for (;t < (int) al.paths_all[mal_agent].size(); t++)
{
if (al.paths_all[mal_agent][t].location > 0)
{
future_intersections.emplace_back(al.agents_all[mal_agent].initial_location,
t + 1, al.agents_all[mal_agent].malfunction_left + 1); // replan agents at the start location
break;
}
}
}
for (;t < (int) al.paths_all[mal_agent].size(); t++)
{
int loc = al.paths_all[mal_agent][t].location;
if (loc < 0)
continue;
if (ml.getDegree(loc) > 2 && (future_intersections.empty() || get<0>(future_intersections.back()) != loc)) {
future_intersections.emplace_back(loc, t + 1, t + al.agents_all[mal_agent].malfunction_left + 1);
}
}
for (const auto &intersection : future_intersections)
{
// get agents that pass through the intersection after the mal agent
list<pair<int, int>> agents; // <agent_id, timestep>
al.constraintTable.get_agents(agents, mal_agent, intersection); // TODO: get this information from MCP instead of constraint table
runtime = ((fsec) (Time::now() - start_time)).count();
for (const auto &agent : agents) // replan the agents one by one
{
if (runtime >= time_limit)
return true;
int i = agent.first;
int t = agent.second;
if (tabu_list.count(i) > 0 || // the agent has already been replanned, or
(get<1>(intersection) - 1 > 0 && // the agent is following the mal_agent. We do not replan them
al.paths_all[i][t - 1].location >= 0 &&
al.paths_all[i][t - 1].location == al.paths_all[mal_agent][get<1>(intersection) - 2].location)
)
continue;
auto copy = al.paths_all[i];
al.constraintTable.delete_path(i, al.paths_all[i]);
runtime = ((fsec) (Time::now() - start_time)).count();
al.agents[0] = &al.agents_all[i];
SIPP planner(ml, al, f_w, time_limit - runtime, options1);
planner.search();
replan_times++;
tabu_list.insert(i);
if (!planner.path.empty()) {
addAgentPath(i, planner.path);
} else if (!copy.empty() &&
(al.agents_all[i].status > 0 || copy.back().location == al.agents_all[i].goal_location)) {
addAgentPath(i, copy);
} else {
al.paths_all[i].clear();
}
runtime = ((fsec) (Time::now() - start_time)).count();
//if (runtime < time_limit && planner.path.empty())
// dead_agent = true;
}
agent_groups.push_back(agents);
}
}
// replan the skipped agents
/*for (const auto &agents : agent_groups)
{
for (const auto &agent : agents) // replan the agents one by one
{
runtime = ((fsec) (Time::now() - start_time)).count();
if (runtime >= time_limit)
return true;
int i = agent.first;
int t = agent.second;
if (tabu_list.count(i) > 0)
continue;
auto copy = al.paths_all[i];
al.constraintTable.delete_path(i, al.paths_all[i]);
runtime = ((fsec) (Time::now() - start_time)).count();
al.agents[0] = &al.agents_all[i];
SIPP planner(ml,al,f_w,time_limit - runtime,options1);
planner.search();
replan_times++;
if (planner.path.empty())
{
addAgentPath(i, copy);
}
else
{
addAgentPath(i, planner.path);
tabu_list.insert(i);
}
}
}*/
return true;
}
bool LNS::replan(list<int>& to_be_replanned, float time_limit)
{
start_time = Time::now();
max_timestep = al.constraintTable.length_max;
set<int> tabu_list; // record the agents already been replanned
al.num_of_agents = 1;
al.agents.resize(1);
runtime = ((fsec)(Time::now() - start_time)).count();
while (!to_be_replanned.empty() && runtime < time_limit)
{
int i = to_be_replanned.front();
to_be_replanned.pop_front();
if (tabu_list.count(i) > 0)
continue;
auto copy = al.paths_all[i];
al.constraintTable.delete_path(i, al.paths_all[i]);
runtime = ((fsec) (Time::now() - start_time)).count();
al.agents[0] = &al.agents_all[i];
SIPP planner(ml, al, f_w, time_limit - runtime, options1);
planner.search();
//cout << ((fsec)(Time::now() - start_time)).count() - runtime << ",";
runtime = ((fsec) (Time::now() - start_time)).count();
if (!planner.path.empty()) {
addAgentPath(i, planner.path);
}
else if (runtime > time_limit)
{
to_be_replanned.push_back(i);
}
}
return true;
}
bool LNS::getInitialSolution(float success_rate, int max_iterations)
{
if (options1.debug)
cout << "Prioritized planning" << endl;
int screen;
screen = options1.debug;
if (options1.debug)
cout << "Sort the agents" << endl;
neighbors.resize(al.agents_all.size());
for (int i = 0; i < (int)al.agents_all.size(); i++)
neighbors[i] = i;
sortNeighborsByStrategy();
al.num_of_agents = 1;
al.agents.resize(1);
int remaining_agents = (int)neighbors.size();
int dead_agents = 0;
int sum_of_costs = al.sum_of_distances;
int makespan = 0;
runtime = ((fsec)(Time::now() - start_time)).count();
for (auto agent : neighbors)
{
if ( ( this->complete!= nullptr &&
((this->agent_priority_strategy==3 && sum_of_costs > -this->complete->load())
||(this->agent_priority_strategy!=3 && (this->complete->load()>=0 ||sum_of_costs > -this->complete->load() ))))
|| runtime >= hard_time_limit
|| al.getNumOfAllAgents() - remaining_agents >= success_rate * al.getNumOfAllAgents())
{
cout << "Find a solution for " << al.getNumOfAllAgents() - remaining_agents - dead_agents << " agents" <<
" with " << dead_agents << " agents dead and " << remaining_agents << " agents unplanned" << "agent priority "<< agent_priority_strategy<< endl;
cout << "Sum of costs = " << sum_of_costs << " and makespan = " << makespan << endl;
if(this->complete!= nullptr && this->agent_priority_strategy==3 ){
this->complete->store(sum_of_costs);
}
//if agent_priority_strategy != 3 and stop here, means it's solution is worse no signal needed
return false;
}
al.agents[0] = &al.agents_all[agent];
if (options1.debug)
cout << "Remaining agents = " << remaining_agents <<
", remaining time = " << hard_time_limit - runtime << " seconds. " << endl
<< "Agent " << al.agents[0]->agent_id << endl;
//runtime = ((fsec)(Time::now() - start_time)).count();
SIPP planner(ml, al, f_w, hard_time_limit - runtime, options1);
planner.search();
//cout << ((fsec)(Time::now() - start_time)).count() - runtime << ",";
updateCBSResults(planner);
addAgentPath(agent, planner.path);
runtime = ((fsec)(Time::now() - start_time)).count();
if (!planner.path.empty()) // TODO: can be deleted in the submission verison
{
sum_of_costs += (int) planner.path.size() - 1 - al.agents_all[agent].distance_to_goal;
makespan = max((int) planner.path.size() - 1, makespan);
remaining_agents--;
}
else if (runtime < hard_time_limit)
{
dead_agents++;
sum_of_costs += al.constraintTable.length_max - al.agents_all[agent].distance_to_goal;
makespan = al.constraintTable.length_max;
remaining_agents--;
}
}
cout << endl << "Find a solution for " << al.getNumOfAllAgents() - remaining_agents - dead_agents << " agents" <<
" with " << dead_agents << " agents dead and " << remaining_agents << " agents unplanned" << "agent priority "<< agent_priority_strategy<<endl;
cout << "Sum of costs = " << sum_of_costs << " and makespan = " << makespan << "runtime ="<<runtime<< endl;
return true;
}
bool LNS::generateNeighborByStart()
{
if (start_locations.empty())
{
for (int i = 0; i < (int)al.agents_all.size(); i++)
{
auto start = al.agents_all[i].initial_location;
start_locations[start].push_back(i);
}
auto it = start_locations.begin();
while(it != start_locations.end()) // delete start locations that have only one agent
{
if (it->second.size() == 1)
it = start_locations.erase(it);
else
++it;
}
}
if (start_locations.empty())
return false;
auto step = rand() % start_locations.size();
auto it = start_locations.begin();
advance(it, step);
neighbors.assign(it->second.begin(), it->second.end());
if (neighbors.size() > max_group_size ||
(replan_strategy == 0 && neighbors.size() > max_group_size)) // resize the group for CBS
{
sortNeighborsRandomly();
neighbors.resize(max_group_size);
}
if (options1.debug)
cout << "Generate " << neighbors.size() << " neighbors by start location " << it->first << endl;
return true;
}
bool LNS::generateNeighborByTemporalIntersection()
{
if (intersections.empty())
{
for (int i = 0; i < ml.map_size(); i++)
{
if (ml.getDegree(i) > 2)
intersections.push_back(i);
}
}
set<int> neighbors_set;
int location = intersections[rand() % intersections.size()];
al.constraintTable.get_agents(neighbors_set, max_group_size, location);
if (neighbors_set.size() <= 1)
return false;
neighbors.assign(neighbors_set.begin(), neighbors_set.end());
if (options1.debug)
cout << "Generate " << neighbors.size() << " neighbors by intersection " << location << endl;
return true;
}
bool LNS::generateNeighborByIntersection()
{
if (intersections.empty())
{
for (int i = 0; i < ml.map_size(); i++)
{
if (ml.getDegree(i) > 2)
intersections.push_back(i);
}
}
set<int> neighbors_set;
int location = intersections[rand() % intersections.size()];
al.constraintTable.get_agents(neighbors_set, location);
if (neighbors_set.size() <= 1)
return false;
neighbors.assign(neighbors_set.begin(), neighbors_set.end());
if (neighbors.size() > max_group_size || (replan_strategy == 0 && neighbors.size() > max_group_size)) // resize the group for CBS
{
sortNeighborsRandomly();
neighbors.resize(max_group_size);
}
if (options1.debug)
cout << "Generate " << neighbors.size() << " neighbors by intersection " << location << endl;
return true;
}
void LNS::generateNeighborByRandomWalk(boost::unordered_set<int>& tabu_list)
{
if (max_group_size >= (int)al.paths_all.size())
{
neighbors.resize(al.paths_all.size());
for (int i = 0; i < (int)al.paths_all.size(); i++)
neighbors[i] = i;
return;
}
// find the agent with max regret
int a = -1;
for (int i = 0; i < al.paths_all.size(); i++)
{
if (tabu_list.find(i) != tabu_list.end())
continue;
if (a < 0 || compareByRegrets(i, a))
{
a = i;
}
}
if (tabu_list.size() > al.paths_all.size() / 2)
tabu_list.clear();
else
tabu_list.insert(a);
set<int> neighbors_set;
neighbors_set.insert(a);
int T = al.paths_all[a].size();
int count = 0;
while (neighbors_set.size() < max_group_size && count < 10 && T > 0)
{
int t = rand() % T;
randomWalk(a, al.paths_all[a][t], t, neighbors_set, max_group_size, (int) al.paths_all[a].size() - 1);
T = t;
count++;
}
while (neighbors_set.size() < max_group_size)
{
int new_agent = rand() % al.paths_all.size();
neighbors_set.insert(new_agent);
}
neighbors.assign(neighbors_set.begin(), neighbors_set.end());
if (options1.debug)
cout << "Generate " << neighbors.size() << " neighbors by random walks of agent " << a
<< "(" << al.agents_all[a].distance_to_goal << "->" << al.paths_all[a].size() - 1 << ")" << endl;
}
void LNS::replanByPP()
{
updateNeighborPaths();
deleteNeighborPaths();
al.num_of_agents = 1;
al.agents.resize(1);
list<Path> new_paths;
int sum_of_costs = 0;
int sum_of_showup_time = 0;
int makespan = 0;
for (const auto& agent : neighbors)
{
runtime = ((fsec)(Time::now() - start_time)).count();
if (runtime >= soft_time_limit)
{ // change back to the original paths
auto path = neighbor_paths.begin();
for (const auto& agent : neighbors)
{
al.paths_all[agent] = *path;
++path;
}
return;
}
al.agents[0] = &al.agents_all[agent];
// MultiMapICBSSearch<FlatlandLoader> icbs(&ml, &al, f_w, c, 0, options1.debug? 3 : 0, options1);
// icbs.runICBSSearch();
// updateCBSResults(icbs);
// addAgentPath(agent, *icbs.paths[0]);
SIPP planner(ml,al,f_w,0,options1);
planner.search();
updateCBSResults(planner);
addAgentPath(agent, planner.path);
assert(planner.path.back().location == al.paths_all[agent].back().location);
if (planner.path.empty())
{
sum_of_costs += max_timestep;
makespan = max_timestep;
}
else
{
sum_of_costs += (int)planner.path.size() - 1;
makespan = max(makespan, (int)planner.path.size() - 1);
for (int t = 0; t < (int)planner.path.size(); t++)
{
if (planner.path.at(t).location >= 0)
{
sum_of_showup_time += t;
break;
}
}
}
}
if (sum_of_costs < neighbor_sum_of_costs ||
(sum_of_costs == neighbor_sum_of_costs && sum_of_showup_time > neighbor_sum_of_showup_time) ||
(sum_of_costs == neighbor_sum_of_costs && sum_of_showup_time == neighbor_sum_of_showup_time && makespan < neighbor_makespan))
{
delta_costs = sum_of_costs - neighbor_sum_of_costs;
}
else
{ // change back to the original paths
deleteNeighborPaths();
auto path = neighbor_paths.begin();
for (auto agent : neighbors)
{
addAgentPath(agent, *path);
++path;
}
delta_costs = 0;
}
}
void LNS::updateNeighborPaths()
{
if (options1.debug)
cout << "Agents ids: ";
neighbor_sum_of_costs = 0;
neighbor_sum_of_showup_time = 0;
neighbor_makespan = 0;
neighbor_paths.clear();
for (auto i : neighbors)
{
if (options1.debug)
cout << i << ",";
neighbor_paths.emplace_back(al.paths_all[i]);
if (al.paths_all[i].empty())
{
neighbor_sum_of_costs += max_timestep;
neighbor_makespan = max_timestep;
}
else
{
neighbor_sum_of_costs += (int)al.paths_all[i].size() - 1;
neighbor_makespan = max(neighbor_makespan, (int)al.paths_all[i].size() - 1);
for (int t = 0; t < (int)al.paths_all[i].size(); t++)
{
if (al.paths_all[i][t].location >= 0)
{
neighbor_sum_of_showup_time += t;
break;
}
}
}
}
if (options1.debug)
cout << endl;
}
void LNS::updateNeighborPathsCosts()
{
if (options1.debug)
cout << "Agents ids: ";
neighbor_sum_of_costs = 0;
neighbor_makespan = 0;
neighbor_paths.clear();
for (auto i : neighbors)
{
if (options1.debug)
cout << i << ",";
neighbor_sum_of_costs += (int)al.paths_all[i].size() - 1;
neighbor_makespan = max(neighbor_makespan, (int)al.paths_all[i].size() - 1);
}
if (options1.debug)
cout << endl;
}
void LNS::addAgentPath(int agent, const Path& path)
{
assert(agent == al.agents_all[agent].agent_id);
if(!al.constraintTable.insert_path(agent, path))
exit(10);
al.paths_all[agent] = path;
}
void LNS::deleteNeighborPaths()
{
for (auto i : neighbors)
{
assert(i == al.agents_all[i].agent_id);
al.constraintTable.delete_path(i, al.paths_all[i]);
}
}
void LNS::sortNeighborsRandomly()
{
std::random_shuffle(neighbors.begin(), neighbors.end());
if (options1.debug) {
for (auto agent : neighbors) {
cout << agent << "(" << al.agents_all[agent].distance_to_goal << "->" << al.paths_all[agent].size() - 1
<< "), ";
}
cout << endl;
}
}
void LNS::sortNeighborsByRegrets()
{
quickSort(neighbors, 0, neighbors.size() - 1, true);
if (options1.debug) {
for (auto agent : neighbors) {
cout << agent << "(" << al.agents_all[agent].distance_to_goal << "->" << al.paths_all[agent].size() - 1
<< "), ";
}
cout << endl;
}
}
void LNS::sortNeighborsByStrategy()
{
if (agent_priority_strategy == 5)
{
// decide the agent priority for agents at the same start location
start_locations.clear(); // map the agents to their start locations
for (auto i : neighbors)
start_locations[al.agents_all[i].initial_location].push_back(i);
for (auto& agents : start_locations)
{
vector<int> agents_vec(agents.second.begin(), agents.second.end());
quickSort(agents_vec, 0, agents_vec.size() - 1, false);
for (int i = 0; i < (int)agents.second.size(); i++)
{
al.agents_all[agents_vec[i]].priority = i;
}
}
}
else if (agent_priority_strategy == 6)
{
// decide the agent priority for agents at the same start location
start_locations.clear(); // map the agents to their start locations
for (auto i : neighbors)
start_locations[al.agents_all[i].initial_location].push_back(i);
int idx = 0;
for (auto& agents : start_locations)
{
for (auto& i : agents.second)
{
al.agents_all[i].priority = idx;
}
idx++;
}
}
// sort the agents
if (agent_priority_strategy != 0)
quickSort(neighbors, 0, (int)neighbors.size() - 1, false);
}
void LNS::quickSort(vector<int>& agent_order, int low, int high, bool regret)
{
if (low >= high)
return;
int pivot = agent_order[high]; // pivot
int i = low; // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than or equal to pivot
if ((regret && compareByRegrets(agent_order[j], pivot)) ||
al.compareAgent(al.agents_all[agent_order[j]], al.agents_all[pivot], agent_priority_strategy))
{
std::swap(agent_order[i], agent_order[j]);
i++; // increment index of smaller element
}
}
std::swap(agent_order[i], agent_order[high]);
quickSort(agent_order, low, i - 1, regret); // Before i
quickSort(agent_order, i + 1, high, regret); // After i
}
void LNS::randomWalk(int agent_id, const PathEntry& start, int start_timestep,
set<int>& conflicting_agents, int neighbor_size, int upperbound)
{
// a random walk with path that is shorter than upperbound and has conflicting with neighbor_size agents
int speed = al.agents_all[agent_id].speed;
const auto& heuristics = *al.agents_all[agent_id].heuristics;
int loc = start.location;
int heading = start.heading;
auto position_fraction = start.position_fraction;
auto exit_heading = start.exit_heading;
int exit_loc = start.exit_loc;
int h_val;
if (loc < 0)
{
int initial_location = al.agents_all[agent_id].initial_location;
h_val = heuristics[initial_location].get_hval(heading) / speed + 1;
}
else
{
h_val = heuristics[loc].get_hval(heading) / speed;
if (exit_loc >= 0 && speed < 1)
{
int h1 = heuristics[loc].get_hval(heading);
int h2 = heuristics[exit_loc].get_hval(exit_heading);
h_val = h1 / speed - (h2 - h1)*position_fraction;
}
}
for (int t = start_timestep; t < upperbound; t++)
{
list<Transition> transitions;
if(loc == -1){
Transition move;
move.location = loc;
move.heading = heading;
move.position_fraction = position_fraction;
move.exit_loc = exit_loc;
move.exit_heading = exit_heading;
transitions.push_back(move);
Transition move2;
move2.location = al.agents_all[agent_id].initial_location;
move2.heading = heading;
move2.position_fraction = position_fraction;
move2.exit_loc = exit_loc;
move2.exit_heading = exit_heading;
transitions.push_back(move2);
}
else if (position_fraction + speed >= 0.97)
{
if (position_fraction == 0)
{
ml.get_transitions(transitions, loc, heading, false);
assert(!transitions.empty());
}
else {
Transition move;
move.location = exit_loc;
move.heading = exit_heading;
move.position_fraction = 0;
transitions.push_back(move);
}
}
else if (position_fraction == 0)
{
ml.get_exits(transitions, loc, heading, speed, false);
assert(!transitions.empty());
}
else { //<0.97 and po_frac not 0
Transition move2;
move2.location = loc;
move2.heading = heading;
move2.position_fraction = position_fraction + al.agents[agent_id]->speed;
move2.exit_loc = exit_loc;
move2.exit_heading = exit_heading;
transitions.push_back(move2);
}
while(!transitions.empty())
{
int step = rand() % transitions.size();
auto it = transitions.begin();
advance(it, step);
int next_h_val;
if (it->location == -1)
next_h_val = h_val;
else if (exit_loc >= 0 && speed < 1)
{
int h1 = heuristics[it->location].get_hval(it->heading);
int h2 = heuristics[it->exit_loc].get_hval(it->exit_heading);
next_h_val = h1 / speed - (h2 - h1) * (it->position_fraction / speed);
}
else
next_h_val = heuristics[it->location].get_hval(it->heading) / speed;
if (t + 1 + next_h_val < upperbound) // move to this location
{
loc = it->location;
heading = it->heading;
position_fraction = it->position_fraction;
exit_heading = it->exit_heading;
exit_loc = it->exit_loc;
h_val = next_h_val;
assert(agent_id == al.agents_all[agent_id].agent_id);
al.constraintTable.get_conflicting_agents(agent_id, conflicting_agents, loc, t + 1);
break;
}
transitions.erase(it);
}
if (transitions.empty() || conflicting_agents.size() >= neighbor_size || h_val == 0)
break;
}
} | 36.462981 | 187 | 0.539594 | [
"vector"
] |
b3d3ee1c1a7e127660aaafab039f18ccb175213e | 14,164 | cc | C++ | src/image/ImageTransform.cc | sgherbst/simple-base-lib | 6c5f96fd0f8d588b3b9eebbe542465a618f08d96 | [
"MIT"
] | 1 | 2022-02-21T19:14:10.000Z | 2022-02-21T19:14:10.000Z | src/image/ImageTransform.cc | sgherbst/simple-base-lib | 6c5f96fd0f8d588b3b9eebbe542465a618f08d96 | [
"MIT"
] | null | null | null | src/image/ImageTransform.cc | sgherbst/simple-base-lib | 6c5f96fd0f8d588b3b9eebbe542465a618f08d96 | [
"MIT"
] | 3 | 2017-01-05T08:12:05.000Z | 2022-02-21T20:39:49.000Z | // Licensed under MIT license; see license.txt.
#include <sbl/image/ImageTransform.h>
#include <sbl/math/MathUtil.h>
#ifdef USE_OPENCV
#include <opencv/cv.h>
#include <opencv/highgui.h>
#endif
namespace sbl {
//-------------------------------------------
// IMAGE TRANSFORMATION
//-------------------------------------------
/// extract sub-image
// fix(clean): should unify with grayscale version
template<> aptr<ImageColorU> crop( const ImageColorU &input, int xMin, int xMax, int yMin, int yMax ) {
assertDebug( xMin >= 0 && xMax < input.width() );
assertDebug( yMin >= 0 && yMax < input.height() );
int newWidth = xMax - xMin + 1;
int newHeight = yMax - yMin + 1;
aptr<ImageColorU> output( new ImageColorU( newWidth, newHeight ) );
for (int y = yMin; y <= yMax; y++)
for (int x = xMin; x <= xMax; x++)
for (int c = 0; c < 3; c++)
output->data( x - xMin, y - yMin, c ) = input.data( x, y, c );
return output;
}
/// extract sub-image
// fix(faster): use memcpy
template <typename ImageType> aptr<ImageType> crop( const ImageType &input, int xMin, int xMax, int yMin, int yMax ) {
assertDebug( xMin >= 0 && xMax < input.width() );
assertDebug( yMin >= 0 && yMax < input.height() );
int newWidth = xMax - xMin + 1;
int newHeight = yMax - yMin + 1;
aptr<ImageType> output( new ImageType( newWidth, newHeight ) );
for (int y = yMin; y <= yMax; y++)
for (int x = xMin; x <= xMax; x++)
output->data( x - xMin, y - yMin ) = input.data( x, y );
return output;
}
template aptr<ImageGrayU> crop( const ImageGrayU &input, int xMin, int xMax, int yMin, int yMax );
template aptr<ImageGrayF> crop( const ImageGrayF &input, int xMin, int xMax, int yMin, int yMax );
/// shrink or zoom image
template <typename ImageType> aptr<ImageType> resize( const ImageType &input, int newWidth, int newHeight, bool filter ) {
aptr<ImageType> output( new ImageType( newWidth, newHeight ) );
#ifdef USE_OPENCV
int width = input.width();
cvResize( input.iplImage(), output->iplImage(), filter ? (newWidth > width ? CV_INTER_LINEAR : CV_INTER_AREA) : CV_INTER_NN );
#else
fatalError( "not implemented" );
#endif
return output;
}
template aptr<ImageGrayU> resize( const ImageGrayU &input, int newWidth, int newHeight, bool filter );
template aptr<ImageGrayF> resize( const ImageGrayF &input, int newWidth, int newHeight, bool filter );
template aptr<ImageColorU> resize( const ImageColorU &input, int newWidth, int newHeight, bool filter );
/// translate and scale an image
template <typename ImageType> aptr<ImageType> shiftScale( const ImageType &input, float xOffset, float yOffset, float xScale, float yScale, int outputWidth, int outputHeight ) {
aptr<ImageType> output( new ImageType( outputWidth, outputHeight ) );
#ifdef USE_OPENCV
CvMat *map = cvCreateMat( 2, 3, CV_32FC1 );
cvmSet( map, 0, 0, xScale );
cvmSet( map, 0, 1, 0);
cvmSet( map, 0, 2, xOffset );
cvmSet( map, 1, 0, 0);
cvmSet( map, 1, 1, yScale);
cvmSet( map, 1, 2, yOffset );
cvWarpAffine( input.iplImage(), output->iplImage(), map, CV_INTER_CUBIC + CV_WARP_FILL_OUTLIERS, cvScalarAll( 255 ) );
// fix(later): use cvGetQuadrangleSubPix?
cvReleaseMat( &map );
#else
fatalError( "not implemented" );
#endif
return output;
}
template aptr<ImageGrayU> shiftScale( const ImageGrayU &input, float xOffset, float yOffset, float xScale, float yScale, int outputWidth, int outputHeight );
template aptr<ImageGrayF> shiftScale( const ImageGrayF &input, float xOffset, float yOffset, float xScale, float yScale, int outputWidth, int outputHeight );
template aptr<ImageColorU> shiftScale( const ImageColorU &input, float xOffset, float yOffset, float xScale, float yScale, int outputWidth, int outputHeight );
/// apply linear transformation to image
template <typename ImageType> aptr<ImageType> warpAffine( const ImageType &input, float xOffset, float yOffset, float x1, float y1, float x2, float y2, int outputWidth, int outputHeight, int fillColor ) {
aptr<ImageType> output( new ImageType( outputWidth, outputHeight ) );
#ifdef USE_OPENCV
CvMat *map = cvCreateMat( 2, 3, CV_32FC1 );
cvmSet( map, 0, 0, x1 );
cvmSet( map, 0, 1, x2 );
cvmSet( map, 0, 2, xOffset );
cvmSet( map, 1, 0, y1 );
cvmSet( map, 1, 1, y2 );
cvmSet( map, 1, 2, yOffset );
cvWarpAffine( input.iplImage(), output->iplImage(), map, CV_INTER_CUBIC + CV_WARP_FILL_OUTLIERS, cvScalarAll( fillColor ) );
// fix(later): use cvGetQuadrangleSubPix?
cvReleaseMat( &map );
#else
fatalError( "not implemented" );
#endif
return output;
}
template aptr<ImageGrayU> warpAffine( const ImageGrayU &input, float xOffset, float yOffset, float x1, float y1, float x2, float y2, int outputWidth, int outputHeight, int fillColor );
template aptr<ImageGrayF> warpAffine( const ImageGrayF &input, float xOffset, float yOffset, float x1, float y1, float x2, float y2, int outputWidth, int outputHeight, int fillColor );
template aptr<ImageColorU> warpAffine( const ImageColorU &input, float xOffset, float yOffset, float x1, float y1, float x2, float y2, int outputWidth, int outputHeight, int fillColor );
/// flip image vertically (about horizontal axis)
template <typename ImageType> aptr<ImageType> flipVert( const ImageType &input ) {
aptr<ImageType> output( new ImageType( input.width(), input.height() ) );
#ifdef USE_OPENCV
cvConvertImage( input.iplImage(), output->iplImage(), CV_CVTIMG_FLIP );
#else
fatalError( "not implemented" );
#endif
return output;
}
template aptr<ImageGrayU> flipVert( const ImageGrayU &input );
template aptr<ImageGrayF> flipVert( const ImageGrayF &input );
template aptr<ImageColorU> flipVert( const ImageColorU &input );
/// flip image horizontally (about vertical axis)
template <typename ImageType> aptr<ImageType> flipHoriz( const ImageType &input ) {
aptr<ImageType> output( new ImageType( input.width(), input.height() ) );
#ifdef USE_OPENCV
cvFlip(input.iplImage(), output->iplImage(), 1);
#else
fatalError( "not implemented" );
#endif
return output;
}
template aptr<ImageGrayU> flipHoriz( const ImageGrayU &input );
template aptr<ImageGrayF> flipHoriz( const ImageGrayF &input );
template aptr<ImageColorU> flipHoriz( const ImageColorU &input );
// /// flip image horizontally (about vertical axis)
// // fix(clean): use opencv and templates
// aptr<ImageGrayU> flipHoriz( const ImageGrayU &input ) {
// aptr<ImageGrayU> output( new ImageGrayU( input.width(), input.height() ) );
// int width = input.width(), height = input.height();
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// output->data( x, y ) = input.data( width - x - 1, y );
// }
// }
// return output;
// }
/// rotate image 180 degrees
// fix(clean): use opencv
template <typename ImageType> aptr<ImageType> rotate180( const ImageType &input ) {
aptr<ImageType> output( new ImageType( input.width(), input.height() ) );
int width = input.width(), height = input.height(), cc = input.channelCount();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (int c = 0; c< cc ; c++) {
output->data( x, y, c ) = input.data( width - x - 1, height - y - 1, c );
}
}
}
return output;
}
template aptr<ImageGrayU> rotate180( const ImageGrayU &input );
template aptr<ImageGrayF> rotate180( const ImageGrayF &input );
template aptr<ImageColorU> rotate180( const ImageColorU &input );
/// rotate 90 degrees (counter-clockwise)
// fix(clean): use opencv
template <typename ImageType> aptr<ImageType> rotate90(const ImageType& input) {
int newWidth = input.height();
int newHeight = input.width();
int cc = input.channelCount();
aptr<ImageType> output(new ImageType(newWidth, newHeight));
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++) {
for (int c = 0; c < cc; c++) {
output->data(x, y, c) = input.data(y, newWidth - x - 1, c);
}
}
}
return output;
}
template aptr<ImageGrayU> rotate90( const ImageGrayU &input );
template aptr<ImageGrayF> rotate90( const ImageGrayF &input );
template aptr<ImageColorU> rotate90( const ImageColorU &input );
/// rotate 270 degrees (counter-clockwise)
// fix(clean): use opencv
template <typename ImageType> aptr<ImageType> rotate270( const ImageType &input ) {
int newWidth = input.height();
int newHeight = input.width();
int cc = input.channelCount();
aptr<ImageType> output( new ImageType( newWidth, newHeight ) );
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++) {
for (int c = 0; c< cc ; c++) {
output->data( x, y, c ) = input.data( newHeight - y, x , c );
}
}
}
return output;
}
template aptr<ImageGrayU> rotate270( const ImageGrayU &input );
template aptr<ImageGrayF> rotate270( const ImageGrayF &input );
template aptr<ImageColorU> rotate270( const ImageColorU &input );
/// rotate arbitrary amount (counter-clockwise)
template <typename ImageType> aptr<ImageType> rotate( const ImageType &input, float angleDegrees, int fillColor ) {
int width = input.width(), height = input.height();
float theta = angleDegrees * 3.14159f / 180.0f;
float c = cosf( theta );
float s = sinf( theta );
float x1 = c;
float y1 = s;
float x2 = -s;
float y2 = c;
float xCenter = (float) width * 0.5f;
float yCenter = (float) height * 0.5f;
float xOffset = (1.0f - c) * xCenter + s * yCenter;
float yOffset = -s * xCenter + (1.0f - c) * yCenter;
int outputWidth = width;
int outputHeight = height;
if (fAbs( s ) > fAbs( c )) {
outputWidth = height;
outputHeight = width;
}
aptr<ImageType> output = warpAffine( input, xOffset, yOffset, x1, y1, x2, y2, outputWidth, outputHeight, fillColor );
return output;
}
template aptr<ImageGrayU> rotate( const ImageGrayU &input, float angleDegrees, int fillColor );
template aptr<ImageGrayF> rotate( const ImageGrayF &input, float angleDegrees, int fillColor );
template aptr<ImageColorU> rotate( const ImageColorU &input, float angleDegrees, int fillColor );
//-------------------------------------------
// IMAGE TRANSFORM CLASS
//-------------------------------------------
/// create a translation transformation
ImageTransform::ImageTransform( float xOffset, float yOffset ) {
m_params.setLength( 2 );
m_params[ 0 ] = xOffset;
m_params[ 1 ] = yOffset;
}
/// create an affine transformation
ImageTransform::ImageTransform( float xOffset, float yOffset, float xScale, float yScale ) {
m_params.setLength( 6 );
m_params[ 0 ] = xOffset;
m_params[ 1 ] = yOffset;
m_params[ 2 ] = xScale;
m_params[ 3 ] = 0;
m_params[ 4 ] = 0;
m_params[ 5 ] = yScale;
}
/// load transformation parameters from file
ImageTransform::ImageTransform( File &file ) {
m_params = file.readVector<float>();
}
/// save transformation parameters to file
void ImageTransform::save( File &file ) const {
file.writeVector( m_params );
}
/// compute the inverse of the transformation
aptr<ImageTransform> ImageTransform::inverse() const {
aptr<ImageTransform> invTransform;
if (m_params.length() == 2) {
VectorF invParams( 2 );
invParams[ 0 ] = -m_params[ 0 ];
invParams[ 1 ] = -m_params[ 1 ];
invTransform.reset( new ImageTransform( invParams ) );
} else if (m_params.length() == 6) {
VectorF invParams( 6 );
float a = m_params[ 2 ];
float b = m_params[ 4 ];
float c = m_params[ 3 ];
float d = m_params[ 5 ];
float factor = 1.0f / (a * d - b * c);
invParams[ 2 ] = d * factor;
invParams[ 4 ] = -b * factor;
invParams[ 3 ] = -c * factor;
invParams[ 5 ] = a * factor;
invParams[ 0 ] = -(invParams[ 2 ] * m_params[ 0 ] + invParams[ 4 ] * m_params[ 1 ]);
invParams[ 1 ] = -(invParams[ 3 ] * m_params[ 0 ] + invParams[ 5 ] * m_params[ 1 ]);
invTransform.reset( new ImageTransform( invParams ) );
} else {
fatalError( "ImageTransform::inverse: not implemented" );
}
return invTransform;
}
/// map an image forward according to the transformation
aptr<ImageGrayU> ImageTransform::mapForward( const ImageGrayU &img, int outputWidth, int outputHeight, int fillColor ) const {
if (m_params.length() == 6)
return warpAffine( img, m_params[ 0 ], m_params[ 1 ], m_params[ 2 ], m_params[ 3 ], m_params[ 4 ], m_params[ 5 ], outputWidth, outputHeight, fillColor );
assertAlways( m_params.length() == 2)
return shiftScale( img, m_params[ 0 ], m_params[ 1 ], 1, 1, outputWidth, outputHeight );
}
/// map an image forward according to the transformation
aptr<ImageColorU> ImageTransform::mapForward( const ImageColorU &img, int outputWidth, int outputHeight, int fillColor ) const {
if (m_params.length() == 6)
return warpAffine( img, m_params[ 0 ], m_params[ 1 ], m_params[ 2 ], m_params[ 3 ], m_params[ 4 ], m_params[ 5 ], outputWidth, outputHeight, fillColor );
assertAlways( m_params.length() == 2)
return shiftScale( img, m_params[ 0 ], m_params[ 1 ], 1, 1, outputWidth, outputHeight );
}
/// map an image back using the inverse transformation
aptr<ImageGrayU> ImageTransform::mapBackward( const ImageGrayU &img, int outputWidth, int outputHeight, int fillColor ) const {
aptr<ImageTransform> inverseTransform = inverse();
return inverseTransform->mapForward( img, outputWidth, outputHeight, fillColor );
}
/// map a point forward according to the transformation
Point2 ImageTransform::mapForward( const Point2 &pt ) const {
assertAlways( m_params.length() == 2 ); // fix(soon): handle affine xforms
return Point2( pt.x + m_params[ 0 ], pt.y + m_params[ 1 ] );
}
/// map a point backward according to the inverse transformation
Point2 ImageTransform::mapBackward( const Point2 &pt ) const {
assertAlways( m_params.length() == 2 ); // fix(soon): handle affine xforms
return Point2( pt.x - m_params[ 0 ], pt.y - m_params[ 1 ] );
}
/// display transformation parameters
void ImageTransform::display( int indent ) {
if (m_params.length() == 2) {
disp( indent, "x: %f, y: %f", m_params[ 0 ], m_params[ 1 ] );
} else if (m_params.length() == 6) {
disp( indent, "x: %f, y: %f, x1: %f, y1: %f, x2: %ff, y2: %f", m_params[ 0 ], m_params[ 1 ], m_params[ 2 ], m_params[ 3 ], m_params[ 4 ], m_params[ 5 ] );
} else {
fatalError( "ImageTransform::display: not implemented" );
}
}
} // end namespace sbl
| 38.912088 | 204 | 0.680316 | [
"transform"
] |
b3d6453f766197a3cf627138d676990c5b963408 | 17,008 | cpp | C++ | src/externalpotential.cpp | rc83/faunus | 0325913ab5ae6216b19491cd7f93054983e05067 | [
"MIT"
] | null | null | null | src/externalpotential.cpp | rc83/faunus | 0325913ab5ae6216b19491cd7f93054983e05067 | [
"MIT"
] | 3 | 2019-04-24T08:45:06.000Z | 2019-05-10T05:40:08.000Z | src/externalpotential.cpp | rc83/faunus | 0325913ab5ae6216b19491cd7f93054983e05067 | [
"MIT"
] | null | null | null | #include "externalpotential.h"
#include "multipole.h"
#include "aux/eigensupport.h"
#include "functionparser.h"
#include "space.h"
#include "spdlog/spdlog.h"
namespace Faunus {
namespace Energy {
// ------------ Energybase -------------
void Energybase::to_json(json &) const {}
void Energybase::sync(Energybase *, Change &) {}
void Energybase::init() {}
void to_json(json &j, const Energybase &base) {
assert(not base.name.empty());
if (base.timer)
j[base.name]["relative time"] = base.timer.result();
if (not base.citation_information.empty())
j[base.name]["reference"] = base.citation_information;
base.to_json(j[base.name]);
}
// ------------ ExternalPotential -------------
/**
* @param group Group to calculate energy of
* @return Energy of group in kT
*
* - Calculates the interaction of a whole group with the applied external potential
* - The group is ignored if not part of the `molecule_id_list`
* - If `act_on_mass_center` is true, the external potential is applied on a
* fictitious particle placed at the COM and with a net-charge of the group.
*/
double ExternalPotential::groupEnergy(const Group<Particle> &group) const {
double u = 0;
if (molecule_ids.find(group.id) != molecule_ids.end()) {
if (act_on_mass_center and not group.atomic) { // apply only to center of mass
if (group.size() == group.capacity()) { // only apply if group is active
Particle mass_center; // temp. particle representing molecule
mass_center.charge = Faunus::monopoleMoment(group.begin(), group.end());
mass_center.pos = group.cm;
return externalPotentialFunc(mass_center);
}
} else {
for (auto &particle : group) { // loop over active particles
u += externalPotentialFunc(particle);
if (std::isnan(u)) {
break;
}
}
}
}
return u;
}
ExternalPotential::ExternalPotential(const json &j, Space &spc) : space(spc) {
name = "external";
act_on_mass_center = j.value("com", false);
molecule_names = j.at("molecules").get<decltype(molecule_names)>(); // molecule names
auto _ids = Faunus::names2ids(Faunus::molecules, molecule_names); // names --> molids
molecule_ids = std::set<int>(_ids.begin(), _ids.end()); // vector --> set
if (molecule_ids.empty()) {
throw std::runtime_error(name + ": molecule list is empty");
}
}
double ExternalPotential::energy(Change &change) {
assert(externalPotentialFunc != nullptr);
double energy = 0.0;
if (change.dV or change.all or change.dN) {
for (auto &group : space.groups) { // loop over all groups
energy += groupEnergy(group);
if (not std::isfinite(energy)) {
break; // stop summing if not finite
}
}
} else {
for (auto &group_change : change.groups) { // loop over all changed groups
auto &group = space.groups.at(group_change.index); // check specified groups
if (group_change.all or act_on_mass_center) { // check all atoms in group
energy += groupEnergy(group); // groupEnergy also checks for molecule id
} else { // only specified atoms in group
if (molecule_ids.find(group.id) != molecule_ids.end()) {
for (int index : group_change.atoms) { // loop over changed atoms in group
energy += externalPotentialFunc(group[index]);
}
}
}
if (not std::isfinite(energy)) {
break; // stop summing if not finite
}
}
}
return energy; // in kT
}
void ExternalPotential::to_json(json &j) const {
j["molecules"] = molecule_names;
j["com"] = act_on_mass_center;
}
TEST_CASE("[Faunus] ExternalPotential") {
using doctest::Approx;
Faunus::atoms = R"([
{ "A": { "sigma": 4.0, "tfe": 1.0 } },
{ "B": { "sigma": 2.4, "tfe": 1.0 } }
])"_json.get<decltype(atoms)>();
Faunus::molecules = R"([
{ "M": { "atoms": ["A", "B"], "atomic": true } }
])"_json.get<decltype(molecules)>();
json j = R"({
"geometry": {"type": "sphere", "radius": 100 },
"insertmolecules": [ { "M": { "N": 1 } } ]
})"_json;
SUBCASE("ParticleSelfEnergy") {
Space spc = j;
ParticleSelfEnergy pot(spc, [](const Particle &) { return 0.5; });
Change change;
change.all = true; // if both particles have changed
CHECK(pot.energy(change) == Approx(0.5 + 0.5));
}
}
// ------------ Confine -------------
Confine::Confine(const json &j, Tspace &spc) : ExternalPotential(j, spc) {
name = "confine";
k = value_inf(j, "k") * 1.0_kJmol; // get floating point; allow inf/-inf
type = m.at(j.at("type"));
if (type == sphere or type == cylinder) {
radius = j.at("radius");
origo = j.value("origo", origo);
scale = j.value("scale", scale);
if (type == cylinder)
dir = {1, 1, 0};
externalPotentialFunc = [&radius = radius, origo = origo, k = k, dir = dir](const Particle &p) {
double d2 = (origo - p.pos).cwiseProduct(dir).squaredNorm() - radius * radius;
if (d2 > 0)
return 0.5 * k * d2;
return 0.0;
};
// If volume is scaled, also scale the confining radius by adding a trigger
// to `Space::scaleVolume()`
if (scale)
spc.scaleVolumeTriggers.push_back(
[&radius = radius](Tspace &, double Vold, double Vnew) { radius *= std::cbrt(Vnew / Vold); });
}
if (type == cuboid) {
low = j.at("low").get<Point>();
high = j.at("high").get<Point>();
externalPotentialFunc = [low = low, high = high, k = k](const Particle &p) {
double u = 0;
Point d = low - p.pos;
for (int i = 0; i < 3; ++i)
if (d[i] > 0)
u += d[i] * d[i];
d = p.pos - high;
for (int i = 0; i < 3; ++i)
if (d[i] > 0)
u += d[i] * d[i];
return 0.5 * k * u;
};
}
}
void Confine::to_json(json &j) const {
if (type == cuboid)
j = {{"low", low}, {"high", high}};
if (type == sphere or type == cylinder)
j = {{"radius", radius}};
if (type == sphere) {
j["origo"] = origo;
j["scale"] = scale;
}
for (auto &i : m)
if (i.second == type)
j["type"] = i.first;
j["k"] = k / 1.0_kJmol;
ExternalPotential::to_json(j);
_roundjson(j, 5);
}
// ------------ ExternalAkesson -------------
ExternalAkesson::ExternalAkesson(const json &j, Tspace &spc) : ExternalPotential(j, spc) {
name = "akesson";
citation_information = "doi:10/dhb9mj";
nstep = j.at("nstep").get<unsigned int>();
dielectric_constant = j.at("epsr").get<double>();
fixed_potential = j.value("fixed", false);
phi_update_interval = j.value("nphi", 10);
half_box_length_z = 0.5 * spc.geo.getLength().z();
bjerrum_length = pc::bjerrumLength(dielectric_constant);
dz = j.value("dz", 0.2); // read z resolution
charge_profile.setResolution(dz, -half_box_length_z, half_box_length_z);
rho.setResolution(dz, -half_box_length_z, half_box_length_z);
phi.setResolution(dz, -half_box_length_z, half_box_length_z);
filename = j.value("file", "mfcorr.dat"s);
load_rho();
externalPotentialFunc = [&phi = phi](const typename Tspace::Tparticle &p) { return p.charge * phi(p.pos.z()); };
}
double ExternalAkesson::energy(Change &change) {
if (not fixed_potential) { // phi(z) unconverged, keep sampling
if (key == ACCEPTED_MONTE_CARLO_STATE) { // only sample on accepted configs
num_density_updates++;
if (num_density_updates % nstep == 0) {
update_rho();
}
if (num_density_updates % nstep * phi_update_interval == 0) {
update_phi();
}
}
}
return ExternalPotential::energy(change);
}
ExternalAkesson::~ExternalAkesson() {
// save only if still updating and if energy type is `ACCEPTED_MONTE_CARLO_STATE`,
// that is, accepted configurations (not trial)
if (not fixed_potential and key == ACCEPTED_MONTE_CARLO_STATE) {
save_rho();
}
}
void ExternalAkesson::to_json(json &j) const {
j = {{"lB", bjerrum_length}, {"dz", dz}, {"nphi", phi_update_interval}, {"epsr", dielectric_constant},
{"file", filename}, {"nstep", nstep}, {"Nupdates", num_rho_updates}, {"fixed", fixed_potential}};
ExternalPotential::to_json(j);
_roundjson(j, 5);
}
void ExternalAkesson::save_rho() {
if (auto stream = std::ofstream(filename); stream) {
stream.precision(16);
stream << rho;
} else
throw std::runtime_error("cannot save file '"s + filename + "'");
}
void ExternalAkesson::load_rho() {
if (auto stream = std::ifstream(filename); stream) {
rho << stream;
update_phi();
} else {
faunus_logger->warn("density file {} not loaded", filename);
}
}
/**
* This is Eq. 15 of the mol. phys. 1996 paper by Greberg et al.
* (sign typo in manuscript: phi^infty(z) should be "-2*pi*z" on page 413, middle)
*/
double ExternalAkesson::phi_ext(double z, double a) const {
double a2 = a * a, z2 = z * z;
return -2 * pc::pi * z - 8 * a * std::log((std::sqrt(2 * a2 + z2) + a) / std::sqrt(a2 + z2)) +
2 * z * (0.5 * pc::pi + std::asin((a2 * a2 - z2 * z2 - 2 * a2 * z2) / std::pow(a2 + z2, 2)));
}
void ExternalAkesson::sync(Energybase *basePtr, Change &) {
if (not fixed_potential) {
auto other = dynamic_cast<ExternalAkesson *>(basePtr);
assert(other);
if (other->key == ACCEPTED_MONTE_CARLO_STATE) { // only trial energy (new) requires sync
if (num_density_updates != other->num_density_updates) {
assert(num_density_updates < other->num_density_updates);
num_density_updates = other->num_density_updates;
rho = other->rho;
phi = other->phi;
}
}
}
}
void ExternalAkesson::update_rho() {
num_rho_updates++;
Point L = space.geo.getLength();
if (L.x() not_eq L.y() or 0.5 * L.z() != half_box_length_z) {
throw std::runtime_error("Requires box Lx=Ly and Lz=const.");
}
charge_profile.clear();
for (auto &group : space.groups) { // loop over all groups
for (auto &particle : group) { // ...and their active particles
charge_profile(particle.pos.z()) += particle.charge;
}
}
double area = L.x() * L.y();
for (double z = -half_box_length_z; z <= half_box_length_z; z += dz) {
rho(z) += charge_profile(z) / area;
}
}
void ExternalAkesson::update_phi() {
auto L = space.geo.getLength();
double a = 0.5 * L.x();
for (double z = -half_box_length_z; z <= half_box_length_z; z += dz) {
double s = 0;
for (double zn = -half_box_length_z; zn <= half_box_length_z; zn += dz) {
if (rho(zn).cnt > 0) {
s += rho(zn).avg() * phi_ext(std::fabs(z - zn), a); // Eq. 14 in Greberg's paper
}
}
phi(z) = bjerrum_length * s;
}
}
// ------------ createGouyChapman -------------
std::function<double(const Particle &)> createGouyChapmanPotential(const json &j, const Geometry::Chameleon &geo) {
if (geo.boundaryConditions().direction.z() != Geometry::FIXED) {
throw std::runtime_error("Gouy-Chapman requires non-periodicity in z-direction");
}
double rho = 0; // surface charge density (charge per area)
double bjerrum_length = pc::bjerrumLength(j.at("epsr").get<double>());
double molarity = j.at("molarity").get<double>();
double kappa = 1.0 / Faunus::debyeLength(molarity, {1, 1}, bjerrum_length);
double phi0 = j.value("phi0", 0.0); // Unitless potential = beta*e*phi0
if (std::fabs(phi0) > 0) {
rho = std::sqrt(2.0 * molarity / (pc::pi * bjerrum_length)) *
std::sinh(0.5 * phi0); // Evans&Wennerstrom,Colloidal Domain p. 138-140
} else { // phi0 was not provided
double area_per_charge = j.value("rhoinv", 0.0);
if (std::fabs(area_per_charge) > 0) {
rho = 1.0 / area_per_charge;
} else {
rho = j.at("rho").get<double>();
}
phi0 = 2.0 * std::asinh(rho * std::sqrt(0.5 * bjerrum_length * pc::pi / molarity)); // [Evans..]
}
double gamma0 = std::tanh(phi0 / 4.0); // assuming z=1 [Evans..]
faunus_logger->trace("generated Gouy-Chapman potential with {} A^2/charge ", 1.0 / rho);
if (j.value("linearise", false)) {
return [=, &geo](const Particle &p) {
double surface_z_pos = -0.5 * geo.getLength().z();
return p.charge * phi0 * std::exp(-kappa * std::fabs(surface_z_pos - p.pos.z()));
};
} else {
return [=, &geo](const Particle &p) {
double surface_z_pos = -0.5 * geo.getLength().z();
double x = gamma0 * std::exp(-kappa * std::fabs(surface_z_pos - p.pos.z()));
return 2.0 * p.charge * std::log((1.0 + x) / (1.0 - x));
};
}
}
TEST_CASE("[Faunus] Gouy-Chapman") {
using doctest::Approx;
Geometry::Slit slit(50, 50, 50);
Geometry::Chameleon geometry(slit, Geometry::SLIT);
json j = {{"molarity", 0.1}, {"epsr", 80}, {"linearise", false}, {"rhoinv", 100.0}};
auto phi = Energy::createGouyChapmanPotential(j, geometry);
Particle p;
p.charge = 1.0;
p.pos = {0, 0, -25}; // potential at charged surface
CHECK(phi(p) == doctest::Approx(0.2087776151)); // = phi_0
p.pos = {0, 0, 0}; // potential at mid-plane
CHECK(phi(p) == doctest::Approx(0.0160227029));
j = {{"molarity", 0.1}, {"epsr", 80}, {"linearise", false}, {"phi0", 0.2087776151}};
phi = Energy::createGouyChapmanPotential(j, geometry);
CHECK(phi(p) == doctest::Approx(0.0160227029));
j = {{"molarity", 0.1}, {"epsr", 80}, {"linearise", false}, {"rho", 0.01}};
phi = Energy::createGouyChapmanPotential(j, geometry);
CHECK(phi(p) == doctest::Approx(0.0160227029));
j = {{"molarity", 0.1}, {"epsr", 80}, {"linearise", true}, {"rho", 0.01}};
phi = Energy::createGouyChapmanPotential(j, geometry);
CHECK(phi(p) == doctest::Approx(0.0160371645));
}
// ------------ CustomExternal -------------
CustomExternal::CustomExternal(const json &j, Space &spc) : ExternalPotential(j, spc), json_input_backup(j) {
name = "customexternal";
auto &constants = json_input_backup["constants"];
if (std::string function = j.at("function"); function == "gouychapman") {
externalPotentialFunc = createGouyChapmanPotential(constants, spc.geo);
} else if (function == "some-new-potential") { // add new potentials here
// func = createSomeNewPotential(...);
} else { // nothing found above; assume `function` is an expression
if (constants == nullptr) {
constants = json::object();
}
constants["e0"] = pc::e0;
constants["kB"] = pc::kB;
constants["kT"] = pc::kT();
constants["Nav"] = pc::Nav;
constants["T"] = pc::temperature;
expr = std::make_unique<ExprFunction<double>>();
expr->set(
j,
{{"q", &particle_data.charge}, {"x", &particle_data.x}, {"y", &particle_data.y}, {"z", &particle_data.z}});
externalPotentialFunc = [&](const Particle &a) {
particle_data.x = a.pos.x();
particle_data.y = a.pos.y();
particle_data.z = a.pos.z();
particle_data.charge = a.charge;
return expr->operator()();
};
}
}
void CustomExternal::to_json(json &j) const {
j = json_input_backup;
ExternalPotential::to_json(j);
}
// ------------- ParticleSelfEnergy ---------------
/*
* Upon construction, make sure the ExternalPotential base class loop
* over all groups and particles (com=false)
*/
ParticleSelfEnergy::ParticleSelfEnergy(Space &spc, std::function<double(const Particle &)> selfEnergy)
: ExternalPotential({{"molecules", {"*"}}, {"com", false}}, spc) {
assert(selfEnergy && "selfEnergy is not callable");
externalPotentialFunc = selfEnergy;
#ifndef NDEBUG
// test if self energy can be called
assert(not Faunus::atoms.empty());
Particle myparticle;
myparticle.id=0;
if (this->externalPotentialFunc) {
double u = this->externalPotentialFunc(myparticle);
assert(std::isfinite(u));
}
#endif
name = "particle-self-energy";
}
} // namespace Energy
} // namespace Faunus
| 38.049217 | 119 | 0.567909 | [
"geometry",
"object",
"vector"
] |
b3d646795481bdf58b961139fc6b971733b4072a | 10,323 | cpp | C++ | src/Topology.cpp | stepanvanecek/sys-sage | c92ea3d21e2cb85cde04553c2ec3e65b23149bf6 | [
"MIT"
] | 1 | 2022-01-31T22:20:34.000Z | 2022-01-31T22:20:34.000Z | src/Topology.cpp | stepanvanecek/sys-sage | c92ea3d21e2cb85cde04553c2ec3e65b23149bf6 | [
"MIT"
] | null | null | null | src/Topology.cpp | stepanvanecek/sys-sage | c92ea3d21e2cb85cde04553c2ec3e65b23149bf6 | [
"MIT"
] | null | null | null | #include "Topology.hpp"
void Component::PrintSubtree() { PrintSubtree(0); }
void Component::PrintSubtree(int level)
{
//cout << "---PrintSubtree---" << endl;
for (int i = 0; i < level; ++i)
cout << " " ;
cout << GetComponentTypeStr() << " (name " << name << ") id " << id << " - children: " << children.size() << endl;
if(!children.empty())
{
for(auto it = begin(children); it != end(children); ++it)
{
(*it)->PrintSubtree(level+1);
}
}
}
void Component::PrintAllDataPathsInSubtree()
{
vector<Component*> subtreeList;
GetSubtreeNodeList(&subtreeList);
for(auto it = std::begin(subtreeList); it != std::end(subtreeList); ++it)
{
vector<DataPath*>* dp_in = (*it)->GetDataPaths(SYS_SAGE_DATAPATH_INCOMING);
vector<DataPath*>* dp_out = (*it)->GetDataPaths(SYS_SAGE_DATAPATH_OUTGOING);
if(dp_in->size() > 0 || dp_out->size() > 0 )
{
cout << "DataPaths regarding Component (" << (*it)->GetComponentTypeStr() << ") id " << (*it)->GetId() << endl;
for(auto it2 = std::begin(*dp_out); it2 != std::end(*dp_out); ++it2)
{
cout << " ";
(*it2)->Print();
}
for(auto it2 = std::begin(*dp_in); it2 != std::end(*dp_in); ++it2)
{
cout << " ";
(*it2)->Print();
}
}
}
}
void Component::InsertChild(Component * child)
{
child->SetParent(this);
children.push_back(child);
}
Component* Component::GetChild(int _id)
{
for(auto it = begin(children); it != end(children); ++it)
{
if((*it)->id == _id)
return (Component*)(*it);
}
return NULL;
}
int Component::GetNumThreads()
{
if(componentType == SYS_SAGE_COMPONENT_THREAD)
return 1;
int numPu = 0;
for(auto it = std::begin(children); it != std::end(children); ++it)
{
numPu+=(*it)->GetNumThreads();
}
return numPu;
}
int Component::GetTopoTreeDepth()
{
if(children.empty()) //is leaf
return 1;
int maxDepth = 0;
for(auto it = std::begin(children); it != std::end(children); ++it)
{
int subtreeDepth = (*it)->GetTopoTreeDepth();
if(subtreeDepth > maxDepth)
maxDepth = subtreeDepth;
}
return maxDepth+1;
}
void Component::GetComponentsNLevelsDeeper(vector<Component*>* outArray, int depth)
{
if(depth <= 0)
{
outArray->push_back(this);
return;
}
for(auto it = std::begin(children); it != std::end(children); ++it)
{
(*it)->GetComponentsNLevelsDeeper(outArray, depth-1);
}
return;
}
void Component::GetSubcomponentsByType(vector<Component*>* outArray, int _componentType)
{
if(_componentType == componentType)
{
outArray->push_back(this);
}
for(auto it = std::begin(children); it != std::end(children); ++it)
{
(*it)->GetSubcomponentsByType(outArray, _componentType);
}
}
void Component::GetSubtreeNodeList(vector<Component*>* outArray)
{
outArray->push_back(this);
for(auto it = std::begin(children); it != std::end(children); ++it)
{
(*it)->GetSubtreeNodeList(outArray);
}
return;
}
Component* Component::FindSubcomponentById(int _id, int _componentType)
{
if(componentType == _componentType && id == _id){
//cout << " found component " << GetId() << " (" << GetComponentType() << ") found .." << _id << " " << _componentType << endl;
return this;
}
for(auto it = std::begin(children); it != std::end(children); ++it)
{
Component* ret = (*it)->FindSubcomponentById(_id, _componentType);
if(ret != NULL)
{
return ret;
}
}
return NULL;
}
Component* Component::FindParentByType(int _componentType)
{
if(componentType == _componentType){
return this;
}
if(parent != NULL){
cout << " passing through component " << GetId() << " " << GetComponentType() << "(" << GetComponentTypeStr() << ") - searching for " << _componentType << endl;
return parent->FindParentByType(_componentType);
}
return NULL;
}
void Component::AddDataPath(DataPath* p, int orientation)
{
if(orientation == SYS_SAGE_DATAPATH_OUTGOING)
dp_outgoing.push_back(p);
else if(orientation == SYS_SAGE_DATAPATH_INCOMING)
dp_incoming.push_back(p);
}
vector<DataPath*>* Component::GetDataPaths(int orientation)
{
if(orientation == SYS_SAGE_DATAPATH_INCOMING)
return &dp_incoming;
else if(orientation == SYS_SAGE_DATAPATH_OUTGOING)
return &dp_outgoing;
else //TODO
return NULL;
}
string Component::GetComponentTypeStr()
{
switch(componentType)
{
case SYS_SAGE_COMPONENT_NONE:
return "None";
case SYS_SAGE_COMPONENT_THREAD:
return "HW_thread";
case SYS_SAGE_COMPONENT_CORE:
return "Core";
case SYS_SAGE_COMPONENT_CACHE:
return "Cache";
case SYS_SAGE_COMPONENT_NUMA:
return "NUMA";
case SYS_SAGE_COMPONENT_CHIP:
return "Chip";
case SYS_SAGE_COMPONENT_NODE:
return "Node";
case SYS_SAGE_COMPONENT_TOPOLOGY:
return "Topology";
}
return "";
}
int Component::GetTopologySize(unsigned * out_component_size, unsigned * out_dataPathSize)
{
return GetTopologySize(out_component_size, out_dataPathSize, NULL);
}
int Component::GetTopologySize(unsigned * out_component_size, unsigned * out_dataPathSize, std::set<DataPath*>* counted_dataPaths)
{
if(counted_dataPaths == NULL)
counted_dataPaths = new std::set<DataPath*>();
int component_size = 0;
switch(componentType)
{
case SYS_SAGE_COMPONENT_NONE:
break;
case SYS_SAGE_COMPONENT_THREAD:
component_size += sizeof(Thread);
break;
case SYS_SAGE_COMPONENT_CORE:
component_size += sizeof(Core);
break;
case SYS_SAGE_COMPONENT_CACHE:
component_size += sizeof(Cache);
break;
case SYS_SAGE_COMPONENT_SUBDIVISION:
component_size += sizeof(Subdivision);
break;
case SYS_SAGE_COMPONENT_NUMA:
component_size += sizeof(Numa);
break;
case SYS_SAGE_COMPONENT_CHIP:
component_size += sizeof(Chip);
break;
case SYS_SAGE_COMPONENT_MEMORY:
component_size += sizeof(Memory);
break;
case SYS_SAGE_COMPONENT_STORAGE:
component_size += sizeof(Storage);
break;
case SYS_SAGE_COMPONENT_NODE:
component_size += sizeof(Node);
break;
case SYS_SAGE_COMPONENT_TOPOLOGY:
component_size += sizeof(Topology);
break;
}
component_size += attrib.size()*(sizeof(string)+sizeof(void*)); //TODO improve
component_size += children.size()*sizeof(Component*);
(*out_component_size) += component_size;
int dataPathSize = 0;
dataPathSize += dp_incoming.size()*sizeof(DataPath*);
dataPathSize += dp_outgoing.size()*sizeof(DataPath*);
for(auto it = std::begin(dp_incoming); it != std::end(dp_incoming); ++it) {
if(!counted_dataPaths->count((DataPath*)(*it))) {
//cout << "new datapath " << (DataPath*)(*it) << endl;
dataPathSize += sizeof(DataPath);
dataPathSize += (*it)->attrib.size()*(sizeof(string)+sizeof(void*)); //TODO improve
counted_dataPaths->insert((DataPath*)(*it));
}
}
for(auto it = std::begin(dp_outgoing); it != std::end(dp_outgoing); ++it) {
if(!counted_dataPaths->count((DataPath*)(*it))){
//cout << "new datapath " << (DataPath*)(*it) << endl;
dataPathSize += sizeof(DataPath);
dataPathSize += (*it)->attrib.size()*(sizeof(string)+sizeof(void*)); //TODO improve
counted_dataPaths->insert((DataPath*)(*it));
}
}
(*out_dataPathSize) += dataPathSize;
int subtreeSize = 0;
for(auto it = std::begin(children); it != std::end(children); ++it) {
subtreeSize += (*it)->GetTopologySize(out_component_size, out_dataPathSize, counted_dataPaths);
}
return component_size + dataPathSize + subtreeSize;
}
Component* Component::GetParent(){return parent;}
vector<Component*>* Component::GetChildren(){return &children;}
int Component::GetComponentType(){return componentType;}
string Component::GetName(){return name;}
int Component::GetId(){return id;}
void Component::SetParent(Component* _parent){parent = _parent;}
int Numa::GetSize(){return size;}
int Cache::GetCacheLevel(){return cache_level;}
long long Cache::GetCacheSize(){return cache_size;}
int Cache::GetCacheAssociativityWays(){return cache_associativity_ways;}
Component::Component(int _id, string _name, int _componentType) : id(_id), name(_name), componentType(_componentType){}
Component::Component() :Component(0,"unknown",SYS_SAGE_COMPONENT_NONE){}
Topology::Topology():Component(0, "topology", SYS_SAGE_COMPONENT_TOPOLOGY){}
Memory::Memory():Component(0, "Memory", SYS_SAGE_COMPONENT_MEMORY){}
Storage::Storage():Component(0, "Storage", SYS_SAGE_COMPONENT_STORAGE){}
Node::Node(int _id):Component(_id, "sys-sage node", SYS_SAGE_COMPONENT_NODE){}
Node::Node():Node(0){}
Chip::Chip(int _id):Component(_id, "Chip", SYS_SAGE_COMPONENT_CHIP){}
Chip::Chip():Chip(0){}
Cache::Cache(int _id, int _cache_level, unsigned long long _cache_size, int _associativity): Component(_id, "cache", SYS_SAGE_COMPONENT_CACHE), cache_level(_cache_level), cache_size(_cache_size), cache_associativity_ways(_associativity){}
Cache::Cache():Cache(0,0,0,0){}
Subdivision::Subdivision(int _id, string _name, int _componentType): Component(_id, _name, _componentType){}
Subdivision::Subdivision(int _id): Component(_id, "Subdivision", SYS_SAGE_COMPONENT_SUBDIVISION){}
Subdivision::Subdivision():Subdivision(0){}
Numa::Numa(int _id, int _size):Subdivision(_id, "Numa", SYS_SAGE_COMPONENT_NUMA), size(_size){}
Numa::Numa(int _id):Numa(_id, 0){}
Numa::Numa():Numa(0){}
Core::Core(int _id):Component(_id, "Core", SYS_SAGE_COMPONENT_CORE){}
Core::Core():Core(0){}
Thread::Thread(int _id):Component(_id, "Thread", SYS_SAGE_COMPONENT_THREAD){}
Thread::Thread():Thread(0){}
| 32.667722 | 239 | 0.628403 | [
"vector"
] |
b3dd040cb3b99b20d42dd875e43eb512818ebf27 | 1,642 | cpp | C++ | dynamic_programming/edit_distance.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | null | null | null | dynamic_programming/edit_distance.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | 1 | 2022-01-02T14:58:03.000Z | 2022-01-02T14:58:03.000Z | dynamic_programming/edit_distance.cpp | rressi/exercises | b3d19f73361c3b1286d39d9f05d24cd1ebb3f034 | [
"MIT"
] | null | null | null |
#include "edit_distance.h"
#include <algorithm>
#include <vector>
namespace dp {
bool matchStringsWithMaxEditDistanceOfOne(StringView s, StringView t);
bool matchStrings(StringView s, StringView t, Distance maxDistance) {
switch (maxDistance) {
case 0:
return s == t;
case 1:
return matchStringsWithMaxEditDistanceOfOne(s, t);
default:
return calculateEditDistance(s, t) <= maxDistance;
}
}
auto getStringSuffix(StringView s, std::size_t pos) -> StringView {
if (pos < s.size()) {
return s.substr(pos);
} else {
return {};
}
}
bool matchStringsWithMaxEditDistanceOfOne(StringView s, StringView t) {
auto i = 0;
while (i < s.size() && i < t.size() && s[i] == t[i]) {
i++;
}
return (i == s.size() && i == t.size()) ||
getStringSuffix(s, i + 1) == getStringSuffix(t, i) ||
getStringSuffix(s, i) == getStringSuffix(t, i + 1) ||
getStringSuffix(s, i + 1) == getStringSuffix(t, i + 1);
}
auto calculateEditDistance(StringView s, StringView t) -> Distance {
auto matrix = std::vector<std::vector<int>>();
matrix.resize(s.size() + 1);
for (auto i = 0; i < matrix.size(); i++) {
matrix[i].resize(t.size() + 1);
matrix[i][0] = i;
}
auto &firstRow = matrix[0];
for (auto j = 1; j < firstRow.size(); j++) {
firstRow[j] = j;
}
for (auto i = 0; i < s.size(); i++) {
for (auto j = 0; j < t.size(); j++) {
matrix[i + 1][j + 1] =
std::min(std::min(matrix[i][j + 1] + 1, matrix[i + 1][j] + 1),
matrix[i][j] + int(s[i] != t[j]));
}
}
return matrix.back().back();
}
} // namespace dp | 23.797101 | 72 | 0.56821 | [
"vector"
] |
b3e5b0d49e6361ff586c04bf64402497299ea0f7 | 909 | cpp | C++ | Source/FactoryGame/FGProductionIndicatorInstanceManager.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGProductionIndicatorInstanceManager.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGProductionIndicatorInstanceManager.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | // This file has been automatically generated by the Unreal Header Implementation tool
#include "FGProductionIndicatorInstanceManager.h"
UFGProductionIndicatorInstanceManager::UFGProductionIndicatorInstanceManager(){ }
void UFGProductionIndicatorInstanceManager::OnUnregister(){ Super::OnUnregister(); }
void UFGProductionIndicatorInstanceManager::OnRegister(){ Super::OnRegister(); }
void UFGProductionIndicatorInstanceManager::ClearInstances(){ }
void UFGProductionIndicatorInstanceManager::AddInstance( const FTransform& transform, InstanceHandle& handle, EProductionStatus status){ }
void UFGProductionIndicatorInstanceManager::RemoveInstance( InstanceHandle& handle){ }
void UFGProductionIndicatorInstanceManager::MoveInstance( const FTransform& transform, InstanceHandle& handle, EProductionStatus moveTo){ }
void UFGProductionIndicatorInstanceManager::SetupInstanceLists( UStaticMesh* staticMesh){ }
| 69.923077 | 139 | 0.852585 | [
"transform"
] |
b3e81d4fe3c85b026458ba2d08c2f96bd7ae0dd8 | 578 | cpp | C++ | Frame.cpp | fchern/ttaos | 60fb785b866e2bbcaf5433a78a7cfad0934a3073 | [
"MIT"
] | null | null | null | Frame.cpp | fchern/ttaos | 60fb785b866e2bbcaf5433a78a7cfad0934a3073 | [
"MIT"
] | null | null | null | Frame.cpp | fchern/ttaos | 60fb785b866e2bbcaf5433a78a7cfad0934a3073 | [
"MIT"
] | null | null | null | /*
* Frame.cpp
*/
#include "Frame.h"
#include<vector>
#include<set>
#include<sstream>
#include<fstream>
#include<iostream>
#include<stdexcept>
#include "../structs/AccountEntryStruct.h"
#include <boost/lexical_cast.hpp>
#include "boost/format.hpp"
#include "TerranEnums.h"
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
using namespace ProjectNamespace;
template<typename T>
Frame<T>::Frame(const std::string &filename) {
}
template<typename T>
Frame<T>::~Frame() {
// TODO Auto-generated destructor stub
}
template
class Frame<AccountEntryStruct>;
| 15.621622 | 46 | 0.733564 | [
"vector"
] |
b3e82f07d5e8b006e211f5f25536fe4946b554bb | 3,029 | cc | C++ | components/service/ucloud/aliyuncvc/src/model/ListIsvStatisticsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/aliyuncvc/src/model/ListIsvStatisticsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/aliyuncvc/src/model/ListIsvStatisticsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/aliyuncvc/model/ListIsvStatisticsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Aliyuncvc;
using namespace AlibabaCloud::Aliyuncvc::Model;
ListIsvStatisticsResult::ListIsvStatisticsResult() :
ServiceResult()
{}
ListIsvStatisticsResult::ListIsvStatisticsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListIsvStatisticsResult::~ListIsvStatisticsResult()
{}
void ListIsvStatisticsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allStatisticsNode = dataNode["Statistics"]["Statistic"];
for (auto dataNodeStatisticsStatistic : allStatisticsNode)
{
Data::Statistic statisticObject;
if(!dataNodeStatisticsStatistic["MeetingNumber"].isNull())
statisticObject.meetingNumber = dataNodeStatisticsStatistic["MeetingNumber"].asString();
if(!dataNodeStatisticsStatistic["MeetingLength"].isNull())
statisticObject.meetingLength = dataNodeStatisticsStatistic["MeetingLength"].asString();
if(!dataNodeStatisticsStatistic["MemberNumber"].isNull())
statisticObject.memberNumber = dataNodeStatisticsStatistic["MemberNumber"].asString();
if(!dataNodeStatisticsStatistic["Day"].isNull())
statisticObject.day = dataNodeStatisticsStatistic["Day"].asString();
data_.statistics.push_back(statisticObject);
}
auto totalNode = dataNode["Total"];
if(!totalNode["MeetingNumber"].isNull())
data_.total.meetingNumber = std::stoi(totalNode["MeetingNumber"].asString());
if(!totalNode["MeetingLength"].isNull())
data_.total.meetingLength = std::stoi(totalNode["MeetingLength"].asString());
if(!totalNode["MemberNumber"].isNull())
data_.total.memberNumber = std::stoi(totalNode["MemberNumber"].asString());
if(!value["ErrorCode"].isNull())
errorCode_ = std::stoi(value["ErrorCode"].asString());
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
}
std::string ListIsvStatisticsResult::getMessage()const
{
return message_;
}
ListIsvStatisticsResult::Data ListIsvStatisticsResult::getData()const
{
return data_;
}
int ListIsvStatisticsResult::getErrorCode()const
{
return errorCode_;
}
bool ListIsvStatisticsResult::getSuccess()const
{
return success_;
}
| 32.569892 | 91 | 0.759327 | [
"model"
] |
b3f554fcd98f38fbf8bcdca6dec9a5f5a08c23cf | 3,605 | cpp | C++ | shore-sm-6.0.2/src/sthread/tests/thread4.cpp | glycerine/shore-mt | 39f1802ba9588bc9d32d34386ed0193477f7e8d1 | [
"Spencer-94",
"Spencer-86",
"Xnet",
"Linux-OpenIB",
"Spencer-99",
"X11",
"CECILL-B"
] | 3 | 2016-07-15T08:22:56.000Z | 2019-10-10T02:26:08.000Z | shore-sm-6.0.2/src/sthread/tests/thread4.cpp | glycerine/shore-mt | 39f1802ba9588bc9d32d34386ed0193477f7e8d1 | [
"Spencer-94",
"Spencer-86",
"Xnet",
"Linux-OpenIB",
"Spencer-99",
"X11",
"CECILL-B"
] | null | null | null | shore-sm-6.0.2/src/sthread/tests/thread4.cpp | glycerine/shore-mt | 39f1802ba9588bc9d32d34386ed0193477f7e8d1 | [
"Spencer-94",
"Spencer-86",
"Xnet",
"Linux-OpenIB",
"Spencer-99",
"X11",
"CECILL-B"
] | 2 | 2020-12-23T06:49:23.000Z | 2021-03-05T07:00:28.000Z | /*<std-header orig-src='shore'>
$Id: thread4.cpp,v 1.32 2010/06/08 22:27:54 nhall Exp $
SHORE -- Scalable Heterogeneous Object REpository
Copyright (c) 1994-99 Computer Sciences Department, University of
Wisconsin -- Madison
All Rights Reserved.
Permission to use, copy, modify and distribute this software and its
documentation is hereby granted, provided that both the copyright
notice and this permission notice appear in all copies of the
software, derivative works or modified versions, and any portions
thereof, and that both notices appear in supporting documentation.
THE AUTHORS AND THE COMPUTER SCIENCES DEPARTMENT OF THE UNIVERSITY
OF WISCONSIN - MADISON ALLOW FREE USE OF THIS SOFTWARE IN ITS
"AS IS" CONDITION, AND THEY DISCLAIM ANY LIABILITY OF ANY KIND
FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
This software was developed with support by the Advanced Research
Project Agency, ARPA order number 018 (formerly 8230), monitored by
the U.S. Army Research Laboratory under contract DAAB07-91-C-Q518.
Further funding for this work was provided by DARPA through
Rome Research Laboratory Contract No. F30602-97-2-0247.
*/
#include "w_defines.h"
/* -- do not edit anything above this line -- </std-header>*/
#include <cstdlib>
#include <ctime>
#include <w.h>
#include <sthread.h>
#include <iostream>
#include <sstream>
#include <w_strstream.h>
__thread stringstream *_safe_io(NULL);
void safe_io_init()
{
if (_safe_io==NULL) _safe_io = new stringstream;
}
void safe_io_fini()
{
if (_safe_io!=NULL) delete _safe_io; _safe_io=NULL;
}
#define SAFE_IO(XXXX) { safe_io_init(); \
*_safe_io << XXXX; \
fprintf(stdout, _safe_io->str().c_str()); }
class timer_thread_t : public sthread_t {
public:
timer_thread_t(unsigned ms);
protected:
virtual void run();
private:
unsigned _ms;
};
unsigned default_timeout[] = {
4000, 5000, 1000, 6000, 4500, 4400, 4300, 4200, 4100, 9000
};
bool verbose = false;
int main(int argc, char **argv)
{
int timeouts;
unsigned *timeout;
if (argc > 1 && strcmp(argv[1], "-v") == 0) {
verbose = true;
argc--;
argv++;
}
if (argc > 1) {
timeouts = argc - 1;
timeout = new unsigned[timeouts];
for (int i = 1; i < argc; i++)
timeout[i-1] = atoi(argv[i]);
}
else {
timeouts = sizeof(default_timeout) /sizeof(default_timeout[0]);
timeout = default_timeout;
}
timer_thread_t **timer_thread = new timer_thread_t *[timeouts];
int i;
for (i = 0; i < timeouts; i++) {
timer_thread[i] = new timer_thread_t(timeout[i]);
w_assert1(timer_thread[i]);
W_COERCE(timer_thread[i]->fork());
}
for (i = 0; i < timeouts; i++) {
W_COERCE( timer_thread[i]->join());
delete timer_thread[i];
}
delete [] timer_thread;
if (timeout != default_timeout)
delete [] timeout;
if (verbose)
sthread_t::dump_stats(cout);
delete _safe_io; _safe_io = NULL;
return 0;
}
timer_thread_t::timer_thread_t(unsigned ms)
: sthread_t(t_regular),
_ms(ms)
{
w_ostrstream_buf s(40); // XXX magic number
s << "timer_thread(" << ms << ')' << ends;
rename(s.c_str());
}
void timer_thread_t::run()
{
stime_t start, stop;
SAFE_IO( "[" << setw(2) << setfill('0') << id
<< "] going to sleep for " << _ms << "ms" << endl;)
if (verbose)
start = stime_t::now();
sthread_t::sleep(_ms);
if (verbose)
stop = stime_t::now();
SAFE_IO(
"[" << setw(2) << setfill('0') << id
<< "] woke up after " << _ms << "ms";
)
if (verbose) SAFE_IO(
"; measured " << (sinterval_t)(stop-start)
<< " seconds.";
cout << endl;
)
safe_io_fini();
}
| 22.53125 | 68 | 0.676006 | [
"object"
] |
b61673d9c592eaabbb0977aecd1bf45cd9ede167 | 96,170 | cc | C++ | src/pass/zero_elimination.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | null | null | null | src/pass/zero_elimination.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | null | null | null | src/pass/zero_elimination.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019-2021 Huawei Technologies Co., Ltd
*
* 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 <dmlc/base.h>
#include <dmlc/parameter.h>
#include <tvm/api_registry.h>
#include <tvm/ir_functor_ext.h>
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <ir_pass.h>
#include <tvm/ir_visitor.h>
#include <tvm/operation.h>
#include <tvm/arithmetic.h>
#include <arithmetic/const_fold.h>
#include <op/op_util.h>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <unordered_set>
#include <tuple>
#include "pass/utils.h"
#include "pass/zero_elimination.h"
#include "pass/autodiff_cce.h"
namespace akg {
namespace ir {
using air::IterVarType;
using air::arith::EvalSet;
using air::arith::IntSet;
using air::ir::HasSideEffect;
struct ExprLess {
bool operator()(const Expr &l, const Expr &r) const { return Compare(l, r) < 0; }
};
struct ExprEq {
bool operator()(const Expr &l, const Expr &r) const { return Compare(l, r) == 0; }
};
// Merge two maps, prefer the right one on conflict
template <class K, class V>
Map<K, V> Merge(Map<K, V> original, const Map<K, V> &update) {
for (const auto &p : update) {
original.Set(p.first, p.second);
}
return std::move(original);
}
// Concatenate two arrays
template <class T>
Array<T> Concat(Array<T> a, const Array<T> &b) {
for (const auto &x : b) {
a.push_back(x);
}
return std::move(a);
}
// Combine all expressions from the container using &&.
template <class container>
Expr All(const container &c) {
Expr res;
for (const auto &e : c) {
if (res.get()) {
res = res && e;
} else {
res = e;
}
}
if (res.get()) {
return res;
} else {
return const_true();
}
}
// Create a select statement of the form cond ? on_true : 0
Expr SelectElseZero(const Expr &cond, const Expr &on_true) {
return Select::make(cond, on_true, make_zero(on_true.type()));
}
// Simplify_cce the expression as thoroughly as possible by using all available simplifiers.
Expr SuperSimplify(Expr e, const Map<Var, Range> &vranges) {
// For some reason no simplifier can detect that there is only one value of the variable
std::unordered_map<const Variable *, Expr> vmap;
for (const auto &var_range : vranges) {
if (is_const_int(var_range.second->extent, 1)) {
vmap[var_range.first.get()] = var_range.second->min;
}
}
if (!vmap.empty()) {
e = Substitute(e, vmap);
}
e = SimplifyMad().Mutate(e);
return AutodiffSimplify().Mutate(CanonicalSimplify(Simplify_cce(CanonicalSimplify(e, vranges), vranges), vranges));
}
// Provability check that uses SuperSimplify
bool CanProve(const Expr &e, const Map<Var, Range> &vranges) { return is_one(SuperSimplify(e, vranges)); }
class ExprFreeVarsVisitor : public IRVisitor {
public:
std::vector<Var> free_array;
std::unordered_set<const Variable *> bound;
std::unordered_set<const Variable *> free;
void Visit(const NodeRef &node) override {
if (const auto v = node.as<Variable>()) {
if (!bound.count(v) && !free.count(v)) {
free.insert(v);
free_array.push_back(Downcast<Var>(node));
}
} else {
IRVisitor::Visit(node);
}
}
void Visit_(const Variable *op) override { CHECK(false) << "This case shouldn't happen"; }
void Visit_(const LetStmt *op) override {
bound.insert(op->var.get());
IRVisitor::Visit_(op);
}
void Visit_(const For *op) override {
bound.insert(op->loop_var.get());
IRVisitor::Visit_(op);
}
void Visit_(const Let *op) override {
bound.insert(op->var.get());
IRVisitor::Visit_(op);
}
void Visit_(const Reduce *op) override {
for (const auto &iv : op->axis) {
bound.insert(iv->var.get());
}
IRVisitor::Visit_(op);
}
void Visit_(const Store *op) override {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Allocate *op) override {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Free *op) override {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Load *op) override {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
};
// Get free variables of an expression
Array<Var> ExprFreeVars(const Expr &expr) {
ExprFreeVarsVisitor visitor;
visitor.Visit(expr);
return visitor.free_array;
}
DomainTransformation ComposeDomainTransformations(const DomainTransformation &first,
const DomainTransformation &second) {
CHECK(second->old_domain.same_as(first->new_domain));
Map<Var, Expr> new_to_old;
Map<Var, Expr> old_to_new;
for (auto p : second->new_to_old) {
new_to_old.Set(p.first, Substitute(p.second, first->new_to_old));
}
for (auto p : first->old_to_new) {
old_to_new.Set(p.first, Substitute(p.second, second->old_to_new));
}
return DomainTransformationNode::make(second->new_domain, first->old_domain, new_to_old, old_to_new);
}
DomainTransformation DomainTransformation::operator+=(const DomainTransformation &other) {
*this = ComposeDomainTransformations(*this, other);
return *this;
}
DomainTransformation EmptyDomainTransformation(const Domain &domain) {
Map<Var, Expr> new_to_old;
Map<Var, Expr> old_to_new;
for (const Var &v : domain->variables) {
old_to_new.Set(v, make_zero(v.type()));
}
Domain new_domain = DomainNode::make({}, {make_zero(Bool())}, {});
return DomainTransformationNode::make(new_domain, domain, new_to_old, old_to_new);
}
DomainTransformation IdDomainTransformation(const Domain &domain) {
Map<Var, Expr> new_to_old;
for (const Var &v : domain->variables) {
new_to_old.Set(v, v);
}
return DomainTransformationNode::make(domain, domain, new_to_old, new_to_old);
}
// Convert an array of itervars to an array of inequalities
Array<Expr> IterVarsToInequalities(const Array<IterVar> &itervars) {
Array<Expr> res;
for (const IterVar &v : itervars) {
res.push_back(GE::make(v->var, v->dom->min));
res.push_back(LT::make(v->var, v->dom->min + v->dom->extent));
}
return res;
}
// Convert an array of itervars to a map from vars to ranges
Map<Var, Range> IterVarsToMap(const Array<IterVar> &itervars) {
Map<Var, Range> res;
for (const IterVar &v : itervars) {
res.Set(v->var, v->dom);
}
return res;
}
// Convert an array of itervars to an array of vars
Array<Var> IterVarsToVars(const Array<IterVar> &itervars) {
Array<Var> res;
for (const IterVar &v : itervars) {
res.push_back(v->var);
}
return res;
}
// Given a map from vars to ranges create an array of itervars
Array<IterVar> IterVarsFromMap(const Array<Var> &vars, const Map<Var, Range> &vranges,
IterVarType iter_type = IterVarType::kDataPar, const std::string &thread_tag = "") {
Array<IterVar> res;
for (const Var &v : vars) {
CHECK(vranges.count(v)) << "A range for the variable " << v << " was not provided in map " << vranges;
res.push_back(IterVarNode::make(vranges[v], v, iter_type, thread_tag));
}
return res;
}
Expr SimplifyCombiner(const Expr &expr, bool prune_unused_components) {
const auto op = expr.as<Reduce>();
// First Simplify the results
Array<Expr> simplified_result;
for (const auto &res : op->combiner->result) {
simplified_result.push_back(SuperSimplify(res, IterVarsToMap(op->axis)));
}
// Which components to keep
std::vector<int> used(op->combiner->result.size(), false);
if (prune_unused_components) {
// This function recursively marks the used components starting from
// the index idx
std::function<void(int)> mark_used;
mark_used = [&used, &simplified_result, op, &mark_used](size_t idx) {
// if the idx-th component was mark as used before, do nothing
if (used[idx]) return;
used[idx] = true;
// check if the idx-th result expr uses some lhs or rhs variables
// and recursively mark the corresponding components
for (size_t i = 0; i < simplified_result.size(); ++i)
if (!used[i]) {
if (ExprUseVar(simplified_result[idx], op->combiner->lhs[i]) ||
ExprUseVar(simplified_result[idx], op->combiner->rhs[i]))
mark_used(static_cast<int>(i));
}
};
// mark all used components starting from the value_index
mark_used(op->value_index);
} else {
// if prunning was not requested, keep all components
used.assign(used.size(), true);
}
int new_value_index = op->value_index;
Array<Expr> new_result;
Array<Expr> new_identity;
Array<Var> new_lhs;
Array<Var> new_rhs;
Array<Expr> new_source;
// Create the new expressions based on the used ones.
for (size_t i = 0; i < used.size(); ++i) {
if (used[i]) {
// We Simplify_cce the result of the combiner and the identity element
new_result.push_back(simplified_result[i]);
new_identity.push_back(SuperSimplify(op->combiner->identity_element[i], IterVarsToMap(op->axis)));
new_lhs.push_back(op->combiner->lhs[i]);
new_rhs.push_back(op->combiner->rhs[i]);
new_source.push_back(op->source[i]);
} else if (static_cast<int>(i) < op->value_index) {
// value_index should also be adjusted
new_value_index--;
}
}
CommReducer new_combiner = CommReducerNode::make(new_lhs, new_rhs, new_result, new_identity);
return Reduce::make(new_combiner, new_source, op->axis, op->condition, new_value_index);
}
// Clone iter vars and return both the new vars and the substitution from old to new.
std::pair<Array<IterVar>, std::unordered_map<const Variable *, Expr>> CloneIterVars(const Array<IterVar> &vars) {
Array<IterVar> new_vars;
std::unordered_map<const Variable *, Expr> vmap;
for (const IterVar &iv : vars) {
IterVar new_v = IterVarNode::make(iv->dom, iv->var.copy_with_suffix(""), iv->iter_type, iv->thread_tag);
new_vars.push_back(new_v);
vmap[iv->var.get()] = new_v;
}
return std::make_pair(std::move(new_vars), std::move(vmap));
}
// Clone reduction by cloning the axis variables.
Expr CloneReduction(const Expr &expr) {
if (const auto red = expr.as<Reduce>()) {
Array<IterVar> new_axis;
std::unordered_map<const Variable *, Expr> vmap;
std::tie(new_axis, vmap) = CloneIterVars(red->axis);
Array<Expr> src_with_newaxis;
for (const auto &src : red->source) {
src_with_newaxis.push_back(Substitute(src, vmap));
}
return Reduce::make(red->combiner, src_with_newaxis, new_axis, Substitute(red->condition, vmap), red->value_index);
} else {
return expr;
}
}
// Return true if this combiner is just a sum.
bool IsSumCombiner(const CommReducer &combiner, const Map<Var, Range> &vranges) {
if (combiner->result.size() != 1) {
return false;
}
if (!is_const_value(SuperSimplify(combiner->identity_element[0], vranges), 0)) {
return false;
}
Expr should_be_zero = SuperSimplify(combiner->result[0] - (combiner->lhs[0] + combiner->rhs[0]), vranges);
return is_const_value(should_be_zero, 0);
}
// Return true if zero may be factored out of a reduction with this combiner.
bool CanFactorZeroFromCombiner(const CommReducer &combiner, int value_index, const Map<Var, Range> &vranges) {
if (!is_const_value(SuperSimplify(combiner->identity_element[value_index], vranges), 0)) {
return false;
}
Expr zero = make_zero(combiner->result[value_index].type());
Expr in =
Substitute(combiner->result[value_index], {{combiner->lhs[value_index], zero}, {combiner->rhs[value_index], zero}});
in = SuperSimplify(in, vranges);
return is_const_value(in, 0);
}
// If expr is a Call node, perform inlining, otherwise do nothing
Expr InlineThisCall(const Expr &expr) {
if (const auto op = expr.as<Call>()) {
if (op->call_type == Call::CallType::Halide) {
if (const auto op_comp = op->func.as<ComputeOpNode>()) {
Array<Var> tensor_axes;
for (const auto &var : op_comp->axis) {
tensor_axes.push_back(var->var);
}
Stmt inlined = Inline(Evaluate::make(expr), op->func, tensor_axes, op_comp->body[op->value_index]);
if (const auto ev = inlined.as<Evaluate>()) {
// If it is a reduction, clone it
return CloneReduction(ev->value);
}
}
}
}
return expr;
}
Tensor InlineTailCall(const Tensor &tensor) { return TransformBody(tensor, InlineThisCall); }
// Implements InlineTensors by trying to inline every Call of the given Expr
class InlineTensorsMutator : public IRMutator {
public:
explicit InlineTensorsMutator(const Array<Tensor> &inlineable, bool inline_reductions = false)
: inline_reductions_(inline_reductions) {
for (const Tensor &tensor : inlineable) {
inlineable_.emplace(tensor->op.operator->(), tensor->value_index);
}
}
~InlineTensorsMutator() override = default;
Expr Mutate_(const Call *op, const Expr &e) override {
if (op->call_type == Call::CallType::Halide) {
if (const auto op_comp = op->func.as<ComputeOpNode>()) {
// Inline only if the array of inlineable tensors is empty or contains this tensor
if (inlineable_.empty() || inlineable_.count({op_comp, op->value_index})) {
// Inline only compute nodes that are not reductions (unless inline reductions is allowed)
if (inline_reductions_ || !op_comp->body[0].as<Reduce>()) {
// Inline this call and then try to perform further inlining
return Mutate(InlineThisCall(e));
}
}
}
}
// If we cannot inline this call, we should try to do inlining in its arguments
return IRMutator::Mutate_(op, e);
}
private:
// Tensors which are allowed to be inlined, represented as pairs (op_node, value_index)
std::set<std::pair<const OperationNode *, int>> inlineable_;
bool inline_reductions_;
};
Expr InlineTensors(const Expr &expr, const Array<Tensor> &inlineable, bool inline_reductions) {
return InlineTensorsMutator(inlineable, inline_reductions).Mutate(expr);
}
Tensor InlineTensors(const Tensor &tensor, const Array<Tensor> &inlineable, bool inline_reductions) {
auto transformation = [inlineable, inline_reductions](const Expr &e) {
return InlineTensorsMutator(inlineable, inline_reductions).Mutate(e);
};
return TransformBody(tensor, transformation);
}
struct NonzeronessConditionResult {
Expr cond;
Expr value;
Expr to_expr() const { return SelectElseZero(cond, value); }
};
// The implementation of NonzeronessCondition
class NonzeronessConditionFunctor
: public air::ir::ExprFunctor<NonzeronessConditionResult(const Expr &, const Expr &)> {
public:
NonzeronessConditionResult NonzeronessCondition(const Expr &e) {
if (e.type().is_bool()) {
// Boolean expressions are non-zero whenever they are true themselves
return {e, const_true()};
} else {
return VisitExpr(e, e);
}
}
// Most of the cases are implemented using helpers below
result_type VisitExpr_(const Variable *, const Expr &e) final { return Default_(e); }
result_type VisitExpr_(const IntImm *op, const Expr &e) final { return Const_(op, e); }
result_type VisitExpr_(const UIntImm *op, const Expr &e) final { return Const_(op, e); }
result_type VisitExpr_(const FloatImm *op, const Expr &e) final { return Const_(op, e); }
result_type VisitExpr_(const StringImm *, const Expr &e) final { return Default_(e); }
result_type VisitExpr_(const Add *op, const Expr &e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Sub *op, const Expr &e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Mul *op, const Expr &e) final { return BinOpMulLike_(op, e); }
result_type VisitExpr_(const Div *op, const Expr &e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const FloorDiv *op, const Expr &e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const Mod *op, const Expr &e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const FloorMod *op, const Expr &e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const Min *op, const Expr &e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Max *op, const Expr &e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Cast *op, const Expr &e) final {
auto nz_a = NonzeronessCondition(op->value);
if (nz_a.value.same_as(op->value)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, Cast::make(op->type, nz_a.value)};
}
}
result_type VisitExpr_(const Select *op, const Expr &e) final {
Expr cond = op->condition, true_val = op->true_value, false_val = op->false_value;
auto nz_a = NonzeronessCondition(true_val);
auto nz_b = NonzeronessCondition(false_val);
// If the false part is zero, we can get rid of the select
if (is_const_value(nz_b.value, 0)) {
Expr new_cond = SuperSimplify(nz_a.cond && cond);
return {new_cond, nz_a.value};
}
// If the true part is zero, we can also get rid of the select
if (is_const_value(nz_a.value, 0)) {
Expr new_cond = SuperSimplify(nz_b.cond && !cond);
return {new_cond, nz_b.value};
}
// Otherwise we retain the select and combine the conditions into this
Expr new_cond = SuperSimplify((cond && nz_a.cond) || (!cond && nz_b.cond));
if (nz_a.value.same_as(true_val) && nz_b.value.same_as(false_val)) {
return {new_cond, e};
} else {
return {new_cond, Select::make(cond, nz_a.value, nz_b.value)};
}
}
result_type VisitExpr_(const Call *op, const Expr &e) final {
if (op->name == air::ir::intrinsic::tvm_if_then_else) {
Expr cond = op->args[0], true_val = op->args[1], false_val = op->args[2];
auto nz_a = NonzeronessCondition(true_val);
auto nz_b = NonzeronessCondition(false_val);
// We don't have as much freedom here as in the select case
// since the `if` must be preserved in any case
Expr new_cond = SuperSimplify((cond && nz_a.cond) || (!cond && nz_b.cond));
if (nz_a.value.same_as(true_val) && nz_b.value.same_as(false_val)) {
return {new_cond, e};
} else {
return {new_cond, if_then_else(cond, nz_a.value, nz_b.value)};
}
} else {
return Default_(e);
}
}
NonzeronessConditionResult Default_(const Expr &e) const {
// This is always correct, so it's the default
return {const_true(), e};
}
template <class TNode>
NonzeronessConditionResult Const_(const TNode *op, const Expr &e) {
if (op->value == 0) {
return {const_false(), e};
} else {
return {const_true(), e};
}
}
template <class TNode>
NonzeronessConditionResult BinOpAddLike_(const TNode *op, const Expr &e) {
auto nz_a = NonzeronessCondition(op->a);
auto nz_b = NonzeronessCondition(op->b);
// For addition and similar ops the result may be nonzero if either of the arguments is
// nonzero, so we combine the conditions with Or.
if (Equal(nz_a.cond, nz_b.cond)) {
// If the conditions are the same, we don't need Or
if (nz_a.value.same_as(op->a) && nz_b.value.same_as(op->b)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, TNode::make(nz_a.value, nz_b.value)};
}
} else {
// Otherwise use Or
Expr new_cond = SuperSimplify(nz_a.cond || nz_b.cond);
// A little optimization: if the combined condition is the same as one of the inner
// conditions, we don't need to guard the inner value with a select, otherwise
// we create a select in the `to_expr` call.
Expr new_a = Equal(nz_a.cond, new_cond) ? nz_a.value : nz_a.to_expr();
Expr new_b = Equal(nz_b.cond, new_cond) ? nz_b.value : nz_b.to_expr();
Expr new_expr = TNode::make(new_a, new_b);
return {new_cond, new_expr};
}
}
template <class TNode>
NonzeronessConditionResult BinOpMulLike_(const TNode *op, const Expr &e) {
auto nz_a = NonzeronessCondition(op->a);
auto nz_b = NonzeronessCondition(op->b);
// For multiplication and similar ops the result may be nonzero if
// both the arguments are nonzero, so we combine with And.
Expr new_cond = SuperSimplify(nz_a.cond && nz_b.cond);
if (nz_a.value.same_as(op->a) && nz_b.value.same_as(op->b)) {
return {new_cond, e};
} else {
return {new_cond, TNode::make(nz_a.value, nz_b.value)};
}
}
template <class TNode>
NonzeronessConditionResult BinOpDivLike_(const TNode *op, const Expr &e) {
auto nz_a = NonzeronessCondition(op->a);
// For Div we simply use the condition of the numerator.
if (nz_a.value.same_as(op->a)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, TNode::make(nz_a.value, op->b)};
}
}
};
// Transform expr into a pair (condition, new_expr) such that the old expr is equivalent to
// `select(condition, new_expr, 0)`. The pair is represented as a struct for clarity.
NonzeronessConditionResult NonzeronessCondition(const Expr &expr) {
return NonzeronessConditionFunctor().NonzeronessCondition(expr);
}
Expr LiftNonzeronessCondition(const Expr &expr) { return NonzeronessCondition(expr).to_expr(); }
class NormalizeComparisonsMutator : public IRMutator {
public:
Expr Mutate_(const EQ *op, const Expr &e) override { return Make<EQ>(op->a, op->b); }
Expr Mutate_(const NE *op, const Expr &e) override { return Make<NE>(op->a, op->b); }
Expr Mutate_(const LT *op, const Expr &e) override { return Make<LT>(op->a, op->b); }
Expr Mutate_(const LE *op, const Expr &e) override { return Make<LE>(op->a, op->b); }
Expr Mutate_(const GT *op, const Expr &e) override { return Make<LT>(op->b, op->a); }
Expr Mutate_(const GE *op, const Expr &e) override { return Make<LE>(op->b, op->a); }
private:
template <class TNode>
Expr Make(const Expr &a, const Expr &b) {
// rewrite LT to LE for ints
if (std::is_same<TNode, LT>::value && (a.type().is_int() || a.type().is_uint())) {
return LE::make(SuperSimplify(a - b + 1), make_zero(a.type()));
}
return TNode::make(SuperSimplify(a - b), make_zero(a.type()));
}
};
// Rewrite every comparison into the form a == 0, a != 0, a <= 0, and sometimes for floats a < 0
Expr NormalizeComparisons(const Expr &expr) { return NormalizeComparisonsMutator().Mutate(expr); }
struct FactorOutAtomicFormulasResult {
std::vector<Expr> atomic_formulas;
Expr rest;
Expr to_expr() const {
Expr res = rest;
for (const Expr &e : atomic_formulas) {
res = And::make(e, res);
}
return res;
}
Array<Expr> to_array() const {
Array<Expr> res = atomic_formulas;
res.push_back(rest);
return res;
}
};
// The implementation of FactorOutAtomicFormulas
class FactorOutAtomicFormulasFunctor
: public air::ir::ExprFunctor<FactorOutAtomicFormulasResult(const Expr &, const Expr &)> {
public:
result_type Atomic_(const Expr &e) {
// For atomic expressions the result is the expr itself with True as the residual
return {{e}, make_const(e.type(), 1)};
}
// This is basically the list of expression kinds that are considered atomic
result_type VisitExpr_(const Variable *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const Call *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const IntImm *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const UIntImm *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const EQ *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const NE *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const LE *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const LT *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const GE *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const GT *, const Expr &e) final { return Atomic_(e); }
result_type VisitExpr_(const And *op, const Expr &e) final {
auto res_a = VisitExpr(op->a, op->a);
auto res_b = VisitExpr(op->b, op->b);
// For the And case we return the union of the sets of atomic formulas
std::vector<Expr> res;
res.reserve(res_a.atomic_formulas.size() + res_b.atomic_formulas.size());
std::set_union(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(), res_b.atomic_formulas.begin(),
res_b.atomic_formulas.end(), std::back_inserter(res), ExprLess());
// And the residuals are combined with &&
return {res, res_a.rest && res_b.rest};
}
result_type VisitExpr_(const Mul *op, const Expr &e) final {
auto res_a = VisitExpr(op->a, op->a);
auto res_b = VisitExpr(op->b, op->b);
// For multiplication we do the same thing as for And
std::vector<Expr> res;
res.reserve(res_a.atomic_formulas.size() + res_b.atomic_formulas.size());
std::set_union(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(), res_b.atomic_formulas.begin(),
res_b.atomic_formulas.end(), std::back_inserter(res), ExprLess());
return {res, res_a.rest * res_b.rest};
}
result_type VisitExpr_(const Or *op, const Expr &e) final {
auto res_a = VisitExpr(op->a, op->a);
auto res_b = VisitExpr(op->b, op->b);
// For the Or case we intersect the sets of atomic formulas
std::vector<Expr> res;
res.reserve(std::min(res_a.atomic_formulas.size(), res_b.atomic_formulas.size()));
std::set_intersection(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(), res_b.atomic_formulas.begin(),
res_b.atomic_formulas.end(), std::back_inserter(res), ExprLess());
// Computing the residual is more complex: we have to compute the sets of atomic formulas
// which are left behind, and then combine them with the residuals into the new residual.
std::vector<Expr> new_cond_a;
new_cond_a.reserve(res_a.atomic_formulas.size() - res.size());
std::set_difference(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(), res.begin(), res.end(),
std::back_inserter(new_cond_a), ExprLess());
std::vector<Expr> new_cond_b;
new_cond_b.reserve(res_b.atomic_formulas.size() - res.size());
std::set_difference(res_b.atomic_formulas.begin(), res_b.atomic_formulas.end(), res.begin(), res.end(),
std::back_inserter(new_cond_b), ExprLess());
res_a.atomic_formulas = std::move(new_cond_a);
res_b.atomic_formulas = std::move(new_cond_b);
Expr new_rest = (res_a.to_expr() || res_b.to_expr());
return {res, new_rest};
}
};
// Transform the given formula into a conjunction of atomic formulas (represented as an array)
// and a non-atomic residual. Atomic formulas are consts, calls, variables and comparisons (a <= b,
// etc), i.e. formulas which are not logical operators (||, &&, !) on the top level.
FactorOutAtomicFormulasResult FactorOutAtomicFormulas(const Expr &e) {
return FactorOutAtomicFormulasFunctor().VisitExpr(e, e);
}
class RemoveRedundantInequalitiesMutator : public IRMutator {
public:
explicit RemoveRedundantInequalitiesMutator(Array<Expr> known) {
for (const Expr &cond : known) {
known_.push_back(SuperSimplify(cond));
}
}
~RemoveRedundantInequalitiesMutator() override = default;
Expr Mutate_(const Select *op, const Expr &e) override {
bool has_side_effect = HasSideEffect(e);
Expr new_cond = SuperSimplify(Mutate(op->condition));
if (is_one(new_cond) && !has_side_effect) {
return Mutate(op->true_value);
} else if (is_zero(new_cond) && !has_side_effect) {
return Mutate(op->false_value);
} else {
Array<Expr> new_known = known_;
for (const Expr &atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
// Note that we mutate only the true value with the new mutator
return Select::make(new_cond, new_mutator.Mutate(op->true_value), Mutate(op->false_value));
}
}
Expr Mutate_(const Call *op, const Expr &e) override {
if (op->name == air::ir::intrinsic::tvm_if_then_else) {
Expr new_cond = SuperSimplify(Mutate(op->args[0]));
if (is_one(new_cond)) {
return Mutate(op->args[1]);
} else if (is_zero(new_cond)) {
return Mutate(op->args[2]);
} else {
Array<Expr> new_known = known_;
for (const Expr &atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
// Note that we mutate only the true value with the new mutator
return if_then_else(new_cond, new_mutator.Mutate(op->args[1]), Mutate(op->args[2]));
}
} else {
return IRMutator::Mutate_(op, e);
}
}
Expr Mutate_(const Reduce *op, const Expr &e) override {
Array<Expr> known_with_axes = known_;
for (const Expr &axis_cond : IterVarsToInequalities(op->axis)) {
known_with_axes.push_back(axis_cond);
}
RemoveRedundantInequalitiesMutator mutator_with_axes(known_with_axes);
Expr new_cond = mutator_with_axes.Mutate(op->condition);
Array<Expr> new_known = known_with_axes;
for (const Expr &atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
Array<Expr> new_source;
for (const Expr &src : op->source) {
new_source.push_back(new_mutator.Mutate(src));
}
return Reduce::make(op->combiner, new_source, op->axis, new_cond, op->value_index);
}
Expr Mutate_(const EQ *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const NE *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const LT *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const LE *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const GT *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const GE *op, const Expr &e) override { return MutateAtomic_(e); }
Expr Mutate_(const And *op, const Expr &e) override { return (Mutate(op->a) && Mutate(op->b)); }
private:
Expr MutateAtomic_(const Expr &e) {
Expr simplified = SuperSimplify(e);
for (const Expr &other : known_) {
if (Equal(simplified, other)) {
return const_true();
}
}
return simplified;
}
Array<Expr> known_;
};
// Propagate information from conditions and remove redundant inequalities
Expr RemoveRedundantInequalities(const Expr &expr, const Array<Expr> &known) {
return RemoveRedundantInequalitiesMutator(known).Mutate(expr);
}
struct EliminateDivModResult {
Expr expr;
Map<Var, Expr> substitution;
Array<Var> new_variables;
Array<Expr> conditions;
Map<Var, Range> ranges;
};
class EliminateDivModMutator : public IRMutator {
public:
Map<Var, Expr> substitution;
Array<Var> new_variables;
Array<Expr> conditions;
Map<Var, Range> ranges;
explicit EliminateDivModMutator(const Map<Var, Range> &ranges) : ranges(ranges) {}
~EliminateDivModMutator() override = default;
Expr Mutate_(const Div *op, const Expr &e) override {
const auto imm = op->b.as<IntImm>();
if (imm && (imm->value > 0)) {
// Try to find the already existing variables for this expression
auto it = expr_to_vars_.find({op->a, imm->value});
if (it != expr_to_vars_.end()) {
return it->second.first;
}
// Otherwise recursively mutate the left hand side, and create new variables
Expr mutated_a = Mutate(op->a);
if (auto var_pair_opt = AddNewVarPair(op->a, mutated_a, imm->value)) {
return var_pair_opt.value().first;
} else {
return truncdiv(mutated_a, op->b);
}
}
return Mutate(op->a) / Mutate(op->b);
}
Expr Mutate_(const Mod *op, const Expr &e) override {
const auto imm = op->b.as<IntImm>();
if (imm && (imm->value > 0)) {
// Try to find the already existing variables for this expression
auto it = expr_to_vars_.find({op->a, imm->value});
if (it != expr_to_vars_.end()) {
return it->second.second;
}
// Otherwise recursively mutate the left hand side, and create new variables
Expr mutated_a = Mutate(op->a);
if (auto var_pair_opt = AddNewVarPair(op->a, mutated_a, imm->value)) {
return var_pair_opt.value().second;
} else {
return mutated_a % op->b;
}
}
return Mutate(op->a) % Mutate(op->b);
}
private:
dmlc::optional<std::pair<Var, Var>> AddNewVarPair(const Expr &e, const Expr &mut, int64_t val) {
using tresult = dmlc::optional<std::pair<Var, Var>>;
// Try to find the variables using the mutated expressions
if (!e.same_as(mut)) {
auto it = expr_to_vars_.find({mut, val});
if (it != expr_to_vars_.end()) {
return tresult(it->second);
}
}
Expr val_e = make_const(e.type(), val);
idx_ += 1;
// Convert `ranges` to IntSets
std::unordered_map<const Variable *, IntSet> var_intsets;
for (const auto &p : ranges) {
var_intsets[p.first.get()] = IntSet::range(p.second);
}
// Infer ranges for the expressions we want to replace with variables
Range div_range = EvalSet(mut / val_e, var_intsets).cover_range(Range());
Range mod_range = EvalSet(mut % val_e, var_intsets).cover_range(Range());
// We don't want to add unbounded variables
if (!div_range.get() || !mod_range.get()) {
LOG(WARNING) << "EliminateDivMod: won't eliminate div or mod of expr " << e
<< " because its bounds cannot be inferred";
return tresult();
}
// Create new variables for the expressions
auto div = Var("div" + std::to_string(idx_), e.type());
auto mod = Var("mod" + std::to_string(idx_), e.type());
new_variables.push_back(div);
new_variables.push_back(mod);
substitution.Set(div, mut / val_e);
substitution.Set(mod, mut % val_e);
ranges.Set(div, div_range);
ranges.Set(mod, mod_range);
// This additional condition works as a definition for the new variables
conditions.push_back(mut == div * val_e + mod);
if (!CanProve(mod_range->extent <= val_e)) {
// Since we use the C/C++ definition of mod, there may be multiple values of `mod`
// satisfying the added condition if the expr `e` may change its sign, so we
// have to add another condition.
LOG(WARNING) << "EliminateDivMod: cannot fully eliminate div or mod of expr " << e
<< " (probably it may change its sign)";
conditions.push_back(Select::make(e >= 0, mod >= 0, mod <= 0));
}
auto p = std::make_pair(div, mod);
expr_to_vars_[{e, val}] = p;
if (!e.same_as(mut)) {
expr_to_vars_[{mut, val}] = p;
}
return tresult(p);
}
// A custom comparison function for pairs of exprs and numbers. Compares exprs deeply.
struct Compare_ {
bool operator()(const std::pair<Expr, int64_t> &p1, const std::pair<Expr, int64_t> &p2) const {
if (p1.second < p2.second) {
return true;
} else if (p1.second == p2.second) {
return Compare(p1.first, p2.first) < 0;
} else {
return false;
}
}
};
// A counter for naming new variables
int idx_{0};
// A map from pairs of exprs and numbers (e, n) to pairs of new vars (div, mod)
// such that `div = e / n` and `mod = e % n`
std::map<std::pair<Expr, int64_t>, std::pair<Var, Var>, Compare_> expr_to_vars_;
};
// Replace every subexpr of the form e/const and e % const with a new variable.
// Syntactically equal expressions will be mapped to the same variable.
EliminateDivModResult EliminateDivMod(const Expr &expr, Map<Var, Range> ranges) {
EliminateDivModResult res;
EliminateDivModMutator mutator(std::move(ranges));
res.expr = mutator.Mutate(expr);
res.conditions = std::move(mutator.conditions);
res.new_variables = std::move(mutator.new_variables);
res.substitution = std::move(mutator.substitution);
res.ranges = std::move(mutator.ranges);
return res;
}
// run EliminateDivMod from the conditions of a domain
DomainTransformation EliminateDivModFromDomainConditions(const Domain &domain) {
auto elim_res = EliminateDivMod(All(domain->conditions), domain->ranges);
Map<Var, Range> new_vranges = elim_res.ranges;
Array<Var> new_axis = Concat(domain->variables, elim_res.new_variables);
Expr new_cond = elim_res.expr && All(elim_res.conditions);
Domain new_domain = DomainNode::make(new_axis, FactorOutAtomicFormulas(new_cond).to_array(), new_vranges);
Map<Var, Expr> old_to_new;
Map<Var, Expr> new_to_old = elim_res.substitution;
for (const Var &v : domain->variables) {
old_to_new.Set(v, v);
new_to_old.Set(v, v);
}
return DomainTransformationNode::make(new_domain, domain, new_to_old, old_to_new);
}
std::tuple<int64_t, int64_t, int64_t> xgcd(int64_t a, int64_t b) {
int64_t s = 0, old_s = 1;
int64_t t = 1, old_t = 0;
int64_t r = b, old_r = a;
while (r != 0) {
int64_t q = old_r / r;
std::swap(r, old_r);
r -= q * old_r;
std::swap(s, old_s);
s -= q * old_s;
std::swap(t, old_t);
t -= q * old_t;
}
CHECK_NE(old_r, 0);
CHECK_EQ(a % old_r, 0);
CHECK_EQ(b % old_r, 0);
CHECK(old_r == old_s * a + old_t * b);
return std::make_tuple(old_r, old_s, old_t);
}
DomainTransformation SolveSystemOfEquations(const Domain &domain) {
// Conditions we don't know what to do with
std::vector<Expr> rest;
// Matrix represented as a vector of rows, each row is an array of coefficients
std::vector<std::vector<int64_t>> matrix;
// A column of right hand sides
std::vector<Expr> rhs;
// A map from old vars to new vars represented as a matrix, each row of this matrix corresponds to
// an old variable (from domain->variables) and represents a vector of coefficients
std::vector<std::vector<int64_t>> old_to_new;
// A map from new vars to old vars represented directly as an array of expressions
std::vector<Expr> new_to_old;
size_t vars_size = domain->variables.size();
// Initialize the old_to_new matrix with the identity matrix
for (size_t i = 0; i < vars_size; ++i) {
old_to_new.emplace_back(vars_size);
old_to_new.back()[i] = 1;
new_to_old.push_back(domain->variables[i]);
}
// Transform formulas into rows of the matrix
for (const Expr &formula : domain->conditions) {
if (const auto eq = formula.as<EQ>()) {
Array<Expr> coefs =
air::arith::DetectLinearEquation(SuperSimplify(eq->a - eq->b, domain->ranges), domain->variables);
if (!coefs.empty()) {
std::vector<int64_t> row;
for (size_t j = 0; j < coefs.size() - 1; ++j) {
Expr c = coefs[j];
if (const auto intimm = c.as<IntImm>()) {
row.push_back(intimm->value);
} else {
row.clear();
break;
}
}
if (!row.empty()) {
matrix.push_back(row);
rhs.push_back(-coefs[coefs.size() - 1]);
continue;
}
}
}
// otherwise
rest.push_back(formula);
}
// Diagonalize the matrix
for (size_t index = 0; index < std::min(matrix.size(), vars_size); ++index) {
// Here the matrix is partially diagonalized, that is matrix[i, j] is zero for all i, j
// such that (i < index) or (j < index), unless (i == j).
// That is, now we are diagonalizing the submatrix with i >= index and j >= index
// Find a row with a nonzero element in the index-th column
// (We also prefer rows where this element has minimal abs value)
size_t best_i = index;
for (auto i = best_i; i < matrix.size(); ++i) {
int64_t m_old = matrix[best_i][index];
int64_t m_new = matrix[i][index];
if (m_new != 0) {
if ((m_old == 0) || (std::abs(m_new) < std::abs(m_old))) {
best_i = i;
}
}
}
// Move the row we found to the index-th position
std::swap(matrix[index], matrix[best_i]);
std::swap(rhs[index], rhs[best_i]);
// If the index-th diagonal element is still zero, try to find a column with nonzero index-th
// element and move it to the index-th position
if (matrix[index][index] == 0) {
for (size_t j = index + 1; j < vars_size; ++j) {
if (matrix[index][j] != 0) {
for (size_t i = index; i < matrix.size(); ++i) {
std::swap(matrix[i][index], matrix[i][j]);
}
// swapping columns corresponds to swapping the corresponding new variables
std::swap(new_to_old[index], new_to_old[j]);
for (size_t i = 0; i < old_to_new.size(); ++i) {
std::swap(old_to_new[i][index], old_to_new[i][j]);
}
break;
}
}
}
// If the index-th diagonal element is still zero, then both the index-th row and the index-th
// column are completely zero, and we don't need to do anything; just go to the next index
if (matrix[index][index] == 0) {
continue;
}
// Now the index-th diagonal element is non-zero and we can zero all the index-th column
// below it by subtracting rows from each other
for (auto i = index + 1; i < matrix.size(); ++i) {
if (matrix[i][index] != 0) {
int64_t g, a, b;
// g = a*matrix[index][index] + b*matrix[i][index]
CHECK_NE(matrix[index][index], 0);
if (matrix[i][index] % matrix[index][index] != 0) {
std::tie(g, a, b) = xgcd(matrix[index][index], matrix[i][index]);
} else {
// Explicitly avoid changing the index-th row. This is important to avoid infinite
// loop.
g = matrix[index][index];
a = 1;
b = 0;
}
// Let m = matrix[index][index], n = matrix[i][index], then the following is true:
//
// [ a n/g ][ m/g n/g ] = [ 1 0 ]
// [ b -m/g ][ b -a ] = [ 0 1 ]
//
// Note that the two matrices are integer (since g = gcd(m, n)).
// We will essentially multiply our matrix on the left by a dilated and transposed version
// of the first of these two matrices. The second matrix is not needed here, however we will
// use it while zeroing the index-th row.
CHECK_NE(g, 0);
int64_t m_g = matrix[index][index] / g;
int64_t n_g = matrix[i][index] / g;
// Note that j is the index of the column, not the row
for (size_t j = index; j < matrix[i].size(); ++j) {
// Multiply index-th row by a and add the i-th row multiplied by b
// This will make the index-th diagonal element equal to the gcd
int64_t new_index_j = a * matrix[index][j] + b * matrix[i][j];
// This transformation performs zeroing of matrix[i][index]
int64_t new_i_j = n_g * matrix[index][j] - m_g * matrix[i][j];
matrix[index][j] = new_index_j;
matrix[i][j] = new_i_j;
}
// We have to do the same with rhs
Expr ea = make_const(rhs[index].type(), a);
Expr eb = make_const(rhs[i].type(), b);
Expr e_m_g = make_const(rhs[i].type(), m_g);
Expr e_n_g = make_const(rhs[index].type(), n_g);
Expr new_index_rhs = ea * rhs[index] + eb * rhs[i];
Expr new_i_rhs = e_n_g * rhs[index] - e_m_g * rhs[i];
rhs[index] = new_index_rhs;
rhs[i] = new_i_rhs;
}
}
bool changed = false;
// Now we have to zero the elements of the index-th row by manipulating columns.
// This is more difficult because column manipulation corresponds to variable manipulation,
// but the algorithm is essentially the same as before.
for (size_t j = index + 1; j < vars_size; ++j) {
if (matrix[index][j] != 0) {
int64_t g, a, b;
// g = a*matrix[index][index] + b*matrix[index][j]
CHECK_NE(matrix[index][index], 0);
if (matrix[index][j] % matrix[index][index] != 0) {
std::tie(g, a, b) = xgcd(matrix[index][index], matrix[index][j]);
// During this phase we may disrupt the zeroness of the index-th column, so we will
// have to take some action if this might have happened.
changed = true;
} else {
// Explicitly avoid changing the index-th column. This is important to avoid infinite
// loop. Note that here we don't have to set `changed` to true since we don't change the
// index-th column.
g = matrix[index][index];
a = 1;
b = 0;
}
// Let m = matrix[index][index], n = matrix[index][j], then the following is true:
//
// [ a n/g ][ m/g n/g ] = [ 1 0 ]
// [ b -m/g ][ b -a ] = [ 0 1 ]
//
// Now we are going to multiply our matrix on the right (to manipulate columns instead of
// rows), we will also transform the old_to_new matrix the same way, and we will use the
// second matrix to transform new_to_old.
CHECK_NE(g, 0);
int64_t m_g = matrix[index][index] / g;
int64_t n_g = matrix[index][j] / g;
for (size_t i = index; i < matrix.size(); ++i) {
int64_t new_i_index = a * matrix[i][index] + b * matrix[i][j];
int64_t new_i_j = n_g * matrix[i][index] - m_g * matrix[i][j];
matrix[i][index] = new_i_index;
matrix[i][j] = new_i_j;
}
// We do exactly the same transformations with old_to_new
for (size_t i = 0; i < old_to_new.size(); ++i) {
int64_t new_i_index = a * old_to_new[i][index] + b * old_to_new[i][j];
int64_t new_i_j = n_g * old_to_new[i][index] - m_g * old_to_new[i][j];
old_to_new[i][index] = new_i_index;
old_to_new[i][j] = new_i_j;
}
// And apply reverse transformations to new_to_old.
Expr ea = make_const(new_to_old[j].type(), a);
Expr eb = make_const(new_to_old[index].type(), b);
Expr e_m_g = make_const(new_to_old[index].type(), m_g);
Expr e_n_g = make_const(new_to_old[j].type(), n_g);
Expr new_index = e_m_g * new_to_old[index] + e_n_g * new_to_old[j];
Expr new_j = eb * new_to_old[index] - ea * new_to_old[j];
new_to_old[index] = new_index;
new_to_old[j] = new_j;
}
}
if (changed) {
// We might have changed the first column, so we have to zero it once more (or at least check
// if it's zero), so just perform this iteration once more.
index -= 1;
}
}
// Set the signs for new variables to have positive sign on 1st dependent input variable
for (size_t ii = 0; ii < new_to_old.size(); ii++) {
Array<Expr> coefs =
air::arith::DetectLinearEquation(SuperSimplify(new_to_old[ii], domain->ranges), domain->variables);
if (!coefs.empty()) {
for (size_t jj = 0; jj < coefs.size() - 1; ++jj) {
Expr c = coefs[jj];
if (const auto intimm = c.as<IntImm>()) {
if (intimm->value == 0) continue;
if (intimm->value < 0) {
new_to_old[ii] = Simplify_cce(-new_to_old[ii], domain->ranges);
for (size_t kk = 0; kk < old_to_new.size(); kk++) {
old_to_new[kk][ii] = -old_to_new[kk][ii];
}
} else {
break;
}
}
}
}
}
Array<Var> new_vars;
Map<Var, Expr> new_to_old_map;
std::vector<Expr> solution;
Array<Expr> conditions;
// Simplify_cce right hand sides
for (Expr &r : rhs) {
r = SuperSimplify(r, domain->ranges);
}
// Create the conditions of the existence of a solution
for (size_t j = 0; j < matrix.size(); ++j) {
Expr new_cond;
if ((j >= vars_size) || (matrix[j][j] == 0)) {
// The row of matrix is zero. A solution exists only if the rhs[j] is also zero
new_cond = (rhs[j] == 0);
} else {
// The diagonal element is non-zero. A solution exists only if the diagonal element
// is a divisor of the rhs[j]
new_cond = (truncmod(rhs[j], static_cast<int>(std::abs(matrix[j][j]))) == 0);
}
new_cond = SuperSimplify(new_cond, domain->ranges);
if (is_const_int(new_cond, 0)) {
return EmptyDomainTransformation(domain);
} else if (!is_const_int(new_cond, 1)) {
conditions.push_back(new_cond);
}
}
// Now create new variables or directly solve the equations
for (size_t j = 0; j < vars_size; ++j) {
if ((j >= matrix.size()) || (matrix[j][j] == 0)) {
// The j-th variable can take any integer value, create a tvm variable for it
Expr to_old = SuperSimplify(new_to_old[j], domain->ranges);
std::string name_hint = "n" + std::to_string(new_vars.size());
if (const auto v_old = to_old.as<Variable>()) {
name_hint += "_" + v_old->name_hint;
}
Var v = Var(name_hint, new_to_old[j].type());
solution.push_back(v);
new_vars.push_back(v);
new_to_old_map.Set(v, to_old);
} else {
// The j-th variable is just a single value, don't create a tvm variable
if (matrix[j][j] >= 0) {
Expr a = make_const(rhs[j].type(), matrix[j][j]);
solution.push_back(SuperSimplify(rhs[j] / a, domain->ranges));
} else {
// This is required because some simplifiers have problems with dividing by negative numbers
Expr a = make_const(rhs[j].type(), -matrix[j][j]);
solution.push_back(SuperSimplify((-rhs[j]) / a, domain->ranges));
}
}
}
// Convert the old_to_new matrix to map
Map<Var, Expr> old_to_new_map;
for (size_t i = 0; i < vars_size; ++i) {
Expr e = make_zero(domain->variables[i].type());
for (size_t j = 0; j < vars_size; ++j) {
e = e + make_const(e.type(), old_to_new[i][j]) * solution[j];
}
e = SuperSimplify(e);
old_to_new_map.Set(domain->variables[i], e);
}
// The resulting ranges
Map<Var, Range> ranges;
// First of all, fill the new ranges with outer variable ranges
std::unordered_set<const Variable *> vset;
for (const Var &v : domain->variables) {
vset.insert(v.get());
}
for (const auto &p : domain->ranges) {
if (!vset.count(p.first.get())) {
ranges.Set(p.first, p.second);
}
}
// Convert original ranges to IntSets
std::unordered_map<const Variable *, IntSet> var_intsets;
for (const auto &p : domain->ranges) {
var_intsets[p.first.get()] = IntSet::range(p.second);
}
// Infer ranges for the new variables and add them to the resulting ranges
for (const auto &p : new_to_old_map) {
Range range = EvalSet(p.second, var_intsets).cover_range(Range());
if (range.defined()) {
ranges.Set(p.first, range);
}
}
// We have to transform ranges of the old variables into conditions over new variables because new
// ranges are not enough usually.
for (const auto &p : domain->ranges) {
if (old_to_new_map.count(p.first)) {
Expr in_terms_of_new = old_to_new_map[p.first];
Expr lower_cond = SuperSimplify(p.second->min <= in_terms_of_new, ranges);
Expr upper_cond = SuperSimplify(in_terms_of_new < p.second->min + p.second->extent, ranges);
if (!is_const_int(lower_cond, 1)) {
conditions.push_back(lower_cond);
}
if (!is_const_int(upper_cond, 1)) {
conditions.push_back(upper_cond);
}
}
}
// Add the rest conditions
for (const Expr &cond : rest) {
conditions.push_back(Substitute(cond, old_to_new_map));
}
Domain new_domain = DomainNode::make(new_vars, conditions, ranges);
return DomainTransformationNode::make(new_domain, domain, new_to_old_map, old_to_new_map);
}
VarBounds VarBounds::substitute(const Map<Var, Expr> &subst) const {
auto apply_fun = [&subst](const Expr &e) { return Substitute(e, subst); };
return {Substitute(coef, subst), air::ir::UpdateArray(lower, apply_fun), air::ir::UpdateArray(equal, apply_fun),
air::ir::UpdateArray(upper, apply_fun)};
}
Array<Expr> SolveSystemOfInequalitiesResult::as_conditions() const {
Array<Expr> res;
for (const Var &v : variables) {
auto it = bounds.find(v.get());
CHECK(it != bounds.end());
const VarBounds &bnds = it->second;
Expr lhs = bnds.coef * v;
for (const Expr &rhs : bnds.equal) {
res.push_back(EQ::make(lhs, rhs));
}
for (const Expr &rhs : bnds.lower) {
res.push_back(GE::make(lhs, rhs));
}
for (const Expr &rhs : bnds.upper) {
res.push_back(LE::make(lhs, rhs));
}
}
for (const Expr &e : other_conditions) {
res.push_back(e);
}
return res;
}
Expr SimplifyRemainder(const Expr &expr) {
// Simplifying condition of the form: (((0 - var) % value) == 0)
if (const EQ *op = expr.as<EQ>()) {
if (const Mod *mod = op->a.as<Mod>()) {
if (const Sub *subA = mod->a.as<Sub>()) {
if (is_zero(subA->a)) {
return EQ::make(Mod::make(subA->b, mod->b), op->b);
}
}
}
}
return expr;
}
// Rewrite the system of inequalities using Fourier-Motzkin elimination
// Note that variable ranges help a lot, so this parameter is even non-optional
SolveSystemOfInequalitiesResult SolveSystemOfInequalities(const Array<Expr> &inequalities, const Array<Var> &variables,
const Map<Var, Range> &vranges) {
SolveSystemOfInequalitiesResult res;
res.variables = variables;
// The algorithm consists in doing the following things for each variable v
// - Take formulas from `current` and classify them according to polarity wrt v
// - Combine each formula of positive polarity (wrt v) with each formula of negative polarity
// - Put the resulting combinations into `new_current` along with unclassifiable formulas
// - Replace `current` with `new_current` and move to the next variable
// current and new_current are sorted to enable some heuristics
std::set<Expr, ExprLess> current;
std::set<Expr, ExprLess> new_current;
// A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
std::vector<std::pair<int64_t, Expr>> coef_pos;
// A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
std::vector<std::pair<int64_t, Expr>> coef_neg;
// formulas we don't know what to do with
std::vector<Expr> rest;
// A helper that adds an inequality to new_current if it's not obviously redundant
auto add_to_new_current = [&new_current, &vranges](const Expr &new_ineq) {
if (CanProve(new_ineq, vranges)) {
// redundant: follows from the vranges
return;
}
if (const LE *new_le = new_ineq.as<LE>()) {
// A heuristic: check if the new inequality is a consequence of one
// of its future neighbors (in this case don't add it) or if a future neighbor is
// a consequence of the new ineq (in which case remove the neighbor)
auto it_neighbor = new_current.lower_bound(new_ineq);
if (it_neighbor != new_current.begin()) {
const LE *le = std::prev(it_neighbor)->as<LE>();
if (le && CanProve(new_le->a - le->a <= 0, vranges)) {
return;
} else if (le && CanProve(le->a - new_le->a <= 0, vranges)) {
new_current.erase(std::prev(it_neighbor));
}
}
// Check the other neighbor
if (it_neighbor != new_current.end()) {
const LE *le = it_neighbor->as<LE>();
if (le && CanProve(new_le->a - le->a <= 0, vranges)) {
return;
} else if (le && CanProve(le->a - new_le->a <= 0, vranges)) {
it_neighbor = new_current.erase(it_neighbor);
}
}
new_current.insert(it_neighbor, new_ineq);
} else {
new_current.insert(new_ineq);
}
};
// Simplify_cce each inequality into the form `expr <= 0` and add to new_current formulas
for (const Expr &ineq : inequalities) {
add_to_new_current(NormalizeComparisons(SuperSimplify(ineq, vranges)));
}
std::swap(current, new_current);
for (const Var &v : variables) {
CHECK(!res.bounds.count(v.get())) << "Variable " << v
<< " appears several times in the `variables` which might be a bug";
new_current.clear();
coef_pos.clear();
coef_neg.clear();
// Add bounds from vranges
if (vranges.count(v)) {
const Range &range = vranges[v];
Expr range_lbound = SuperSimplify(range->min, vranges);
Expr range_ubound = SuperSimplify(range->min + range->extent - 1, vranges);
coef_neg.emplace_back(std::pair<int64_t, Expr>{-1, range_lbound});
coef_pos.emplace_back(std::pair<int64_t, Expr>{1, -range_ubound});
}
// Take formulas from `current` and classify them according to polarity wrt v
for (const Expr &ineq : current) {
if (const LE *le = ineq.as<LE>()) {
Array<Expr> coef = air::arith::DetectLinearEquation(le->a, {v});
if (!coef.empty() && is_const(coef[0])) {
CHECK(as_const_int(coef[0]));
int64_t coef0 = *as_const_int(coef[0]);
if (coef0 == 0) {
// zero polarity, straight to new_current
add_to_new_current(ineq);
} else if (coef0 > 0) {
coef_pos.emplace_back(std::pair<int64_t, Expr>{coef0, coef[1]});
} else {
coef_neg.emplace_back(std::pair<int64_t, Expr>{coef0, coef[1]});
}
continue;
}
} else if (const EQ *eq = ineq.as<EQ>()) {
Array<Expr> coef = air::arith::DetectLinearEquation(eq->a, {v});
if (!coef.empty() && is_const(coef[0])) {
CHECK(as_const_int(coef[0]));
int64_t coef0 = *as_const_int(coef[0]);
if (coef0 == 0) {
// zero polarity, straight to new_current
add_to_new_current(ineq);
} else if (coef0 > 0) {
// Equalities may be considered as pairs of two inequalities
coef_pos.emplace_back(std::pair<int64_t, Expr>{coef0, coef[1]});
coef_neg.emplace_back(std::pair<int64_t, Expr>{-coef0, -coef[1]});
} else {
coef_pos.emplace_back(std::pair<int64_t, Expr>{-coef0, -coef[1]});
coef_neg.emplace_back(std::pair<int64_t, Expr>{coef0, coef[1]});
}
continue;
}
}
// if nothing worked, put it in rest
rest.push_back(ineq);
}
// Combine each positive inequality with each negative one (by adding them together)
for (const auto &pos : coef_pos) {
for (const auto &neg : coef_neg) {
auto first_gcd = air::ir::gcd(static_cast<int>(pos.first), static_cast<int>(-neg.first));
CHECK_NE(first_gcd, 0);
Expr c_pos = make_const(v.type(), neg.first / first_gcd);
Expr c_neg = make_const(v.type(), pos.first / first_gcd);
Expr new_lhs = c_neg * neg.second - c_pos * pos.second;
Expr new_ineq = LE::make(new_lhs, make_zero(pos.second.type()));
new_ineq = NormalizeComparisons(SuperSimplify(new_ineq, vranges));
add_to_new_current(new_ineq);
}
}
// Now we have to generate resulting (in)equalities for the variable v
// Find the common denominator in a sense
// We will generate formulas of the form coef_lcm*v <= bound
int64_t coef_lcm = 1;
for (const auto &pos : coef_pos) {
coef_lcm = air::ir::lcm(coef_lcm, pos.first);
}
for (const auto &neg : coef_neg) {
coef_lcm = air::ir::lcm(coef_lcm, -neg.first);
}
// The resulting lower and upper bounds stored in sorted vectors
std::vector<Expr> upper_bounds;
std::vector<Expr> lower_bounds;
upper_bounds.reserve(coef_pos.size());
lower_bounds.reserve(coef_neg.size());
for (const auto &pos : coef_pos) {
CHECK_NE(pos.first, 0);
Expr bound = make_const(v.type(), -coef_lcm / pos.first) * pos.second;
bound = SuperSimplify(bound, vranges);
// Don't add if any of the existing bounds is better
if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
[&bound, &vranges](const Expr &o) { return CanProve(o - bound <= 0, vranges); })) {
continue;
}
// Erase all worse bounds
upper_bounds.erase(
std::remove_if(upper_bounds.begin(), upper_bounds.end(),
[&bound, &vranges](const Expr &o) { return CanProve(o - bound >= 0, vranges); }),
upper_bounds.end());
// Add
upper_bounds.push_back(bound);
}
for (const auto &neg : coef_neg) {
CHECK_NE(neg.first, 0);
Expr bound = make_const(v.type(), -coef_lcm / neg.first) * neg.second;
bound = SuperSimplify(bound, vranges);
// Don't add if any of the existing bounds is better
if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
[&bound, &vranges](const Expr &o) { return CanProve(o - bound >= 0, vranges); })) {
continue;
}
// Erase all worse bounds
lower_bounds.erase(
std::remove_if(lower_bounds.begin(), lower_bounds.end(),
[&bound, &vranges](const Expr &o) { return CanProve(o - bound <= 0, vranges); }),
lower_bounds.end());
// Add
lower_bounds.push_back(bound);
}
// Sort the vectors and remove duplicates
for (std::vector<Expr> *bounds : {&upper_bounds, &lower_bounds}) {
std::sort(bounds->begin(), bounds->end(), ExprLess());
bounds->erase(std::unique(bounds->begin(), bounds->end(), ExprEq()), bounds->end());
}
// Bounds which are both lower and upper should go to equal...
std::vector<Expr> equal;
equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
std::set_intersection(upper_bounds.begin(), upper_bounds.end(), lower_bounds.begin(), lower_bounds.end(),
std::back_inserter(equal), ExprLess());
// ...and be removed from upper bounds...
std::vector<Expr> new_upper;
new_upper.reserve(upper_bounds.size() - equal.size());
std::set_difference(upper_bounds.begin(), upper_bounds.end(), equal.begin(), equal.end(),
std::back_inserter(new_upper), ExprLess());
// ...and from lower bounds.
std::vector<Expr> new_lower;
new_lower.reserve(lower_bounds.size() - equal.size());
std::set_difference(lower_bounds.begin(), lower_bounds.end(), equal.begin(), equal.end(),
std::back_inserter(new_lower), ExprLess());
// Write it to the result.
auto &bnds = res.bounds[v.get()];
bnds.coef = make_const(v.type(), coef_lcm);
bnds.equal = equal;
bnds.lower = new_lower;
bnds.upper = new_upper;
std::swap(current, new_current);
}
// Everything that is left goes to res.other_conditions
for (const Expr &e : current) {
Expr e_simp = SuperSimplify(e, vranges);
if (is_const_int(e_simp, 0)) {
// contradiction detected
res.other_conditions = {const_false()};
return res;
} else if (is_const_int(e_simp, 1)) {
continue;
} else {
res.other_conditions.push_back(e_simp);
}
}
for (const Expr &e : rest) res.other_conditions.push_back(e);
return res;
}
// Deskew the given domain
DomainTransformation DeskewDomain(const Domain &domain) {
// Resulting ranges will contain ranges for the new variables and for the variables that are
// not in the domain->variables but are in domain->ranges
Map<Var, Range> res_ranges;
// vars are variables from domain's variables followed by all the other variables from its ranges
Array<Var> vars = domain->variables;
for (const auto &pair : domain->ranges) {
bool already = false;
for (const Var &v : vars) {
already = already || v.same_as(pair.first);
}
if (!already) {
vars.push_back(pair.first);
// Also populate the resulting ranges with ranges of outer variables
res_ranges.Set(pair.first, pair.second);
}
}
auto solved_system = SolveSystemOfInequalities(domain->conditions, vars, domain->ranges);
Map<Var, Expr> res_old_to_new;
Map<Var, Expr> res_new_to_old;
Array<Var> res_variables;
Array<Expr> res_conditions;
std::unordered_map<const Variable *, IntSet> new_var_intsets;
Map<Var, Range> vranges = domain->ranges;
// Initialize new_var_intsets with the old var intsets
for (const auto &pair : domain->ranges) {
new_var_intsets[pair.first.get()] = IntSet::range(pair.second);
}
// We process variables in the reverse direction to start with the most independent one.
// This order is needed to compute new ranges.
for (auto it = domain->variables.rbegin(); it != domain->variables.rend(); ++it) {
const Var &var = *it;
auto &bnd = solved_system.bounds[var.get()];
// Note that we replace old vars with new ones
bnd = bnd.substitute(res_old_to_new);
if (is_one(bnd.coef) && !bnd.equal.empty()) {
// There is an equation of the form `v == expr`, so this variable can be completely removed.
// Note that we use the 0-th expression because they are ordered by complexity, so it must be
// the simplest one.
res_old_to_new.Set(var, bnd.equal[0]);
} else {
Array<Expr> lowers = Concat(bnd.equal, bnd.lower);
Array<Expr> uppers = Concat(bnd.equal, bnd.upper);
// Here we will try all pairs of lower and upper bounds and find the best pair, that is, the
// pair with the minimal difference between the upper and the lower.
// Note that the bounds are for v*coef, not for v (because we don't want complex expressions
// involving division).
// The lower bound of the best pair so far
Expr best_lower = vranges[var]->min * bnd.coef;
// The difference between the upper and the lower of the best pair so far
Expr best_diff = (vranges[var]->extent - 1) * bnd.coef;
// The overapproximation of the best difference
Expr best_diff_over = best_diff;
for (const Expr &low : lowers) {
for (const Expr &upp : uppers) {
Expr diff = SuperSimplify(upp - low, vranges);
// Since diff may depend on some other variables, we compute its overapproximation
Expr diff_over = EvalSet(diff, new_var_intsets).max();
if (air::arith::is_pos_inf(diff_over)) {
continue;
}
// If it is provable that the new one is strictly better than the current best one,
// then replace it. Note that we are biased towards earlier pairs which should be simpler.
if (CanProve(diff_over - best_diff_over < 0, vranges)) {
best_lower = low;
best_diff = diff;
best_diff_over = diff_over;
}
}
}
if (is_const_int(best_diff, 0)) {
// In this case coef*iv = best_lower
// Don't create an itervar, just replace it everywhere with its min
res_old_to_new.Set(var, SuperSimplify(best_lower / bnd.coef, vranges));
// To assure correctness, we have to add a condition that best_lower can be divided by coef
res_conditions.push_back(SuperSimplify(best_lower % bnd.coef == 0, vranges));
} else {
std::string suffix = Equal(best_lower, vranges[var]->min * bnd.coef) ? "" : "_shifted";
Var new_var = var.copy_with_suffix(suffix);
// We will replace our iv with new_var + shift.
// We use rounding-up division to compute shift. Since we want to use a single formula
// without selects in as many cases as possible, we try to prove conditions manually.
Expr shift;
if (CanProve(best_lower <= 0, vranges)) {
shift = best_lower / bnd.coef;
} else if (CanProve(best_lower > -bnd.coef, vranges)) {
shift = (best_lower + bnd.coef - 1) / bnd.coef;
} else {
shift = Select::make(best_lower <= -bnd.coef, best_lower / bnd.coef, (best_lower + bnd.coef - 1) / bnd.coef);
}
shift = SuperSimplify(shift, vranges);
Expr diff = SuperSimplify(best_diff_over / bnd.coef, vranges);
if (is_const_int(diff, 0)) {
// Don't create an itervar, just replace it everywhere with its min
res_old_to_new.Set(var, shift);
} else {
res_old_to_new.Set(var, new_var + shift);
// Note that we are substituting old with new, so best_lower contains new var,
// that is we have to substitute new with old in best_lower here
res_new_to_old.Set(new_var, SuperSimplify(var - Substitute(shift, res_new_to_old), vranges));
new_var_intsets[new_var.get()] = IntSet::interval(make_zero(new_var.type()), diff);
// Add the new var to the resulting axis
auto range = Range(make_zero(new_var.type()), SuperSimplify(diff + 1, vranges));
res_variables.push_back(new_var);
res_ranges.Set(new_var, range);
vranges.Set(new_var, range);
}
}
}
}
for (const Expr &old_cond : solved_system.as_conditions()) {
auto simpleOldCond = SuperSimplify(Substitute(old_cond, res_old_to_new), vranges);
simpleOldCond = SimplifyRemainder(simpleOldCond);
bool exists = false;
for (const Expr &check_cond : res_conditions) {
if (CanProve(check_cond == simpleOldCond)) {
exists = true;
break;
}
}
if (!exists) {
res_conditions.push_back(simpleOldCond);
}
}
// Reverse the axis so that it matches the order of the original variables
res_variables = Array<Var>(res_variables.rbegin(), res_variables.rend());
Domain new_domain = DomainNode::make(res_variables, res_conditions, res_ranges);
return DomainTransformationNode::make(new_domain, domain, res_new_to_old, res_old_to_new);
}
// Simplify_cce an iteration domain.
DomainTransformation SimplifyDomain(const Domain &domain, bool eliminate_div_mod, bool keep_dims) {
DomainTransformation transf = IdDomainTransformation(domain);
if (eliminate_div_mod) {
transf += EliminateDivModFromDomainConditions(transf->new_domain);
}
// Repeating the following steps has a positive effect.
for (size_t i = 0; i < N_REPEAT_TRANSFORM; ++i) {
DomainTransformation tr;
tr = SolveSystemOfEquations(transf->new_domain);
// SolveSystemOfEquations might lead to unexpected iterator variables
// such as the case of roi_align_ad. To pass this case while making most of the optimization
// in zero elimination, we check whether all the var in new domain are included in the range.
// If not, we will not update the domain transformation.
DomainTransformation old_tf = transf;
transf += tr;
Map<Var, Range> vranges = transf->new_domain->ranges;
bool unexpect_var = false;
for (auto it = transf->new_domain->variables.begin(); it != transf->new_domain->variables.end(); ++it) {
const Var &var = *it;
if (vranges.find(var) == vranges.end()) {
unexpect_var = true;
break;
}
}
if (!unexpect_var) {
tr = DeskewDomain(transf->new_domain);
transf += tr;
} else {
transf = old_tf;
}
}
return transf;
}
// Use the condition of a reduction op to Simplify_cce its domain (axis)
Expr SimplifyReductionDomain(const Expr &expr, const Map<Var, Range> &outer_vranges) {
if (const auto red = expr.as<Reduce>()) {
Domain domain = DomainNode::make(IterVarsToVars(red->axis), FactorOutAtomicFormulas(red->condition).to_array(),
Merge(outer_vranges, IterVarsToMap(red->axis)));
auto res = SimplifyDomain(domain);
Array<Expr> new_source;
for (const Expr &src : red->source) {
new_source.push_back(Substitute(src, res->old_to_new));
}
Array<IterVar> new_axis =
IterVarsFromMap(res->new_domain->variables, res->new_domain->ranges, IterVarType::kCommReduce);
// Perform simplification mainly to remove a possibly empty reduction.
return Simplify_cce(
Reduce::make(red->combiner, new_source, new_axis, All(res->new_domain->conditions), red->value_index));
} else {
return expr;
}
}
// Restore the reduced dims from the expr
class RestoreDimsTensor : public IRMutator {
public:
RestoreDimsTensor(const Map<Var, Range> vranges, const Array<Var> &used_res_variables,
const Map<Var, Expr> new_to_old)
: new_vranges(vranges), used_res_variables_(used_res_variables), new_to_old_(new_to_old) {}
~RestoreDimsTensor() override = default;
Expr Mutate_(const Call *op, const Expr &e) override {
Expr expr = IRMutator::Mutate_(op, e);
const Call *n = expr.as<Call>();
CHECK(n);
if (n->call_type == Call::Halide) {
size_t counter_int = 0, counter_var = 0;
bool previous_exist = (new_var_exprs.size() > 0);
bool supported = true;
for (size_t i = 0; i < n->args.size(); i++) {
if ((n->args[i]->GetTypeKey() == "IntImm") && (n->args[i].as<IntImm>()->value == 0)) {
std::string new_name = "kd_" + std::to_string(counter_int++);
if (previous_exist) {
if (new_vars[i].get()->name_hint != new_name) {
supported = false;
break;
}
} else {
auto new_v = Var(new_name);
new_var_exprs.push_back(new_v);
new_vars.push_back(new_v);
new_vranges.Set(new_v, Range::make_by_min_extent(0, 1));
new_call_exprs.push_back(Expr(0));
}
} else {
if (previous_exist) {
if (!new_var_exprs[i].same_as(used_res_variables_[counter_var])) {
supported = false;
break;
}
counter_var++;
} else {
new_var_exprs.push_back(used_res_variables_[counter_var]);
new_vars.push_back(used_res_variables_[counter_var]);
new_call_exprs.push_back(new_to_old_[used_res_variables_[counter_var]]);
counter_var++;
}
}
}
if (!supported) {
return e;
}
auto new_expr = Call::make(n->type, n->name, new_var_exprs, n->call_type, n->func, n->value_index);
return new_expr;
}
return expr;
}
public:
Array<Expr> new_var_exprs;
Array<Expr> new_call_exprs;
Array<Var> new_vars;
Map<Var, Range> new_vranges;
private:
Array<Var> used_res_variables_;
Map<Var, Expr> new_to_old_;
};
void ExtractUsedVariables(const Expr &e, const Expr &cond, const Array<Var> &outer_axis, const Map<Var, Range> &vranges,
DomainTransformation &simplified_domain, Expr &new_expr, Array<Var> &used_res_variables) {
Domain domain = DomainNode::make(outer_axis, FactorOutAtomicFormulas(cond).to_array(), vranges);
simplified_domain = SimplifyDomain(domain);
new_expr = SuperSimplify(Substitute(e, simplified_domain->old_to_new), simplified_domain->new_domain->ranges);
// This is mostly done to Simplify_cce if_then_else which is not known by the Halide simplifier
new_expr = RemoveRedundantInequalities(new_expr, simplified_domain->new_domain->conditions);
// Keep only those variables of the new vars which are used in the new_expr
for (const Var &var : simplified_domain->new_domain->variables) {
if (ExprUseVar(new_expr, var)) {
used_res_variables.push_back(var);
}
}
}
bool CheckIfVolumeIncreased(const Array<Var> &outer_axis, const Map<Var, Range> &vranges,
const Array<Var> &used_res_variables, const DomainTransformation &simplified_domain) {
// Compute volumes before and after
Expr old_volume = make_const(Int(64), 1);
for (const Var &var : outer_axis) {
old_volume = old_volume * vranges[var]->extent;
}
Expr new_volume = make_const(Int(64), 1);
for (const Var &var : used_res_variables) {
new_volume = new_volume * simplified_domain->new_domain->ranges[var]->extent;
}
// if we can prove that the old volume is not greater than the new volume then
// prefer the old expression.
if (CanProve(old_volume <= new_volume, vranges)) {
return true;
} else {
return false;
}
}
void CheckReduceExpr(const DomainTransformation &simplified_domain, Expr &new_expr) {
if (auto isRed = new_expr.as<Reduce>()) {
Array<Expr> newSource;
bool changed = false;
for (size_t i = 0; i < isRed->source.size(); i++) {
if (auto isSelect = isRed->source[i].as<Select>()) {
auto simplerCond =
Simplify_cce(isSelect->condition, Merge(simplified_domain->new_domain->ranges, IterVarsToMap(isRed->axis)));
if (!simplerCond.same_as(isSelect->condition)) {
changed = true;
}
newSource.push_back(Select::make(simplerCond, isSelect->true_value, isSelect->false_value));
} else {
newSource.push_back(isRed->source[i]);
}
}
if (changed) {
new_expr = Reduce::make(isRed->combiner, newSource, isRed->axis, isRed->condition, isRed->value_index);
}
}
return;
}
// Extract the given expr under the given condition as a separate tensor if the volume of the
// extracted tensor will be less than the volume of the outer_axis
Expr ExtractAsTensorMaybe(const Expr &e, const Expr &cond, const Array<Var> &outer_axis, const Map<Var, Range> &vranges,
bool keep_dims) {
DomainTransformation res;
Expr new_expr;
Array<Var> used_res_variables;
ExtractUsedVariables(e, cond, outer_axis, vranges, res, new_expr, used_res_variables);
// If the expression does not use vars then it is probably better to keep it inlined
if (used_res_variables.empty()) {
// We can return the new_expr here instead of the old e because it doesn't use variables
// otherwise we would need to replace the new vars or create a let-expression
return new_expr;
}
// If it's already a call to a tensor then extracting it will probably be useless
if (const Call *call = new_expr.as<Call>()) {
if (call->call_type == Call::CallType::Halide) {
return e;
}
}
if (CheckIfVolumeIncreased(outer_axis, vranges, used_res_variables, res)) {
return e;
}
CheckReduceExpr(res, new_expr);
static int new_tensor_counter = 0;
std::string new_tensor_name("extracted_tensor_" + std::to_string(new_tensor_counter));
new_tensor_counter++;
if (keep_dims) {
RestoreDimsTensor restore_dims(res->new_domain->ranges, used_res_variables, res->new_to_old);
Expr new_expr_keep_dims = restore_dims.Mutate(new_expr);
if (!new_expr_keep_dims.same_as(new_expr)) {
Tensor new_tensor = TensorFromExpr(
new_expr_keep_dims, IterVarsFromMap(restore_dims.new_vars, restore_dims.new_vranges), new_tensor_name);
return Call::make(e.type(), new_tensor->op->name, restore_dims.new_call_exprs, Call::CallType::Halide,
new_tensor->op, new_tensor->value_index);
}
}
Tensor tensor =
TensorFromExpr(new_expr, IterVarsFromMap(used_res_variables, res->new_domain->ranges), new_tensor_name);
Array<Expr> args;
for (const Var &var : used_res_variables) {
args.push_back(res->new_to_old[var]);
}
return Call::make(e.type(), tensor->op->name, args, Call::CallType::Halide, tensor->op, tensor->value_index);
}
// Extract from cond an implication of cond not containing vars
std::pair<Expr, Expr> ImplicationNotContainingVars(const Expr &cond, const std::unordered_set<const Variable *> &vars) {
CHECK(cond.type().is_bool()) << "The type of cond must be bool";
if (const And *and_op = cond.as<And>()) {
auto pair_a = ImplicationNotContainingVars(and_op->a, vars);
auto pair_b = ImplicationNotContainingVars(and_op->b, vars);
return {pair_a.first && pair_b.first, pair_a.second && pair_b.second};
} else if (const Or *or_op = cond.as<Or>()) {
auto pair_a = ImplicationNotContainingVars(or_op->a, vars);
auto pair_b = ImplicationNotContainingVars(or_op->b, vars);
return {(pair_a.first || pair_b.first),
(pair_a.first || pair_b.second) && (pair_b.first || pair_a.second) && (pair_a.second || pair_b.second)};
} else if (!ExprUseVar(cond, vars)) {
return {cond, const_true()};
} else {
return {const_true(), cond};
}
}
// Factor conditions out of a reduction by applying Fourier-Motzkin elimination and moving out
// (in)equalities which do not depend on the reduction variables.
std::pair<Expr, Expr> LiftConditionsThroughReduction(const Expr &cond, const Array<IterVar> &red_axis,
const Array<IterVar> &outer_axis) {
// Factor out atomics so that we can consider this as a system of inequalities
auto factoratomic_res = FactorOutAtomicFormulas(cond);
Array<Expr> atomics = factoratomic_res.atomic_formulas;
const Expr &rest = factoratomic_res.rest;
Array<Var> allvars;
for (const IterVar &v : red_axis) {
allvars.push_back(v->var);
}
for (const IterVar &v : outer_axis) {
allvars.push_back(v->var);
}
auto vranges = Merge(IterVarsToMap(red_axis), IterVarsToMap(outer_axis));
// start from reduction vars, so that input vars don't depend on them
atomics = SolveSystemOfInequalities(atomics, allvars, vranges).as_conditions();
// Append the rest part
Expr rewritten_cond = (All(atomics) && rest);
std::unordered_set<const Variable *> vset;
for (const IterVar &v : red_axis) {
vset.insert(v->var.get());
}
// The outer (first) condition does not contain reduction vars,
// the inner (second) condition is everything else
return ImplicationNotContainingVars(rewritten_cond, vset);
}
class ExtractReductionsMutator : public IRMutator {
public:
ExtractReductionsMutator(const Array<Var> &outer_axis, Map<Var, Range> vranges,
std::string name = "extracted_reduction")
: outer_axis_(outer_axis), vranges_(std::move(vranges)), name_(std::move(name)) {}
~ExtractReductionsMutator() override = default;
Expr Mutate_(const Reduce *op, const Expr &e) override {
ExtractReductionsMutator new_mutator(Concat(IterVarsToVars(op->axis), outer_axis_),
Merge(vranges_, IterVarsToMap(op->axis)), name_);
Array<Expr> new_source;
for (const Expr &src : op->source) {
new_source.push_back(new_mutator.Mutate(src));
}
auto simplerCond = Simplify_cce(op->condition, Merge(vranges_, IterVarsToMap(op->axis)));
Expr new_reduce = Reduce::make(op->combiner, new_source, op->axis, simplerCond, op->value_index);
ExprFreeVarsVisitor fv_visitor;
fv_visitor.Visit(new_reduce);
// Vars of the tensor we are going to create for this reduction
Array<Var> vars;
for (const Var &v : outer_axis_) {
// We take variables from the outer_axis_ which are also present in the new reduction
if (fv_visitor.free.count(v.get())) {
vars.push_back(v);
}
}
auto newaxis_vmap_pair = CloneIterVars(IterVarsFromMap(vars, vranges_));
Array<IterVar> new_axis = newaxis_vmap_pair.first;
new_reduce = SuperSimplify(Substitute(new_reduce, newaxis_vmap_pair.second), IterVarsToMap(new_axis));
Tensor tensor = TensorFromExpr(new_reduce, new_axis, name_, tag_, attrs_);
Array<Expr> args;
for (const Var &v : vars) {
args.push_back(v);
}
return Call::make(e.type(), tensor->op->name, args, Call::CallType::Halide, tensor->op, tensor->value_index);
}
private:
Array<Var> outer_axis_;
Map<Var, Range> vranges_;
std::string name_;
std::string tag_;
Map<std::string, NodeRef> attrs_;
};
// Extract reductions as separate tensors.
Expr ExtractReductions(const Expr &expr, const Array<Var> &outer_axis, const Map<Var, Range> &vranges) {
return ExtractReductionsMutator(outer_axis, vranges).Mutate(expr);
}
Expr ExtractNonTopReductions(const Expr &expr, const Array<Var> &outer_axis, const Map<Var, Range> &vranges) {
if (const auto red = expr.as<Reduce>()) {
Array<Var> new_outer_axis = Concat(IterVarsToVars(red->axis), outer_axis);
Map<Var, Range> new_vranges = Merge(vranges, IterVarsToMap(red->axis));
Array<Expr> new_source;
for (const Expr &src : red->source) {
new_source.push_back(ExtractReductions(src, new_outer_axis, new_vranges));
}
Expr new_condition = ExtractReductions(red->condition, new_outer_axis, new_vranges);
return Reduce::make(red->combiner, new_source, red->axis, new_condition, red->value_index);
} else {
return ExtractReductions(expr, outer_axis, vranges);
}
}
Expr OptimizeAndLiftNonzeronessConditionsImpl(const Expr &expr, const Array<IterVar> &axis,
const Map<Var, Range> &vranges, bool keep_dims = false) {
Expr result;
Map<Var, Range> combined_vranges = Merge(vranges, IterVarsToMap(axis));
if (const auto *red = expr.as<Reduce>()) {
bool is_sum = IsSumCombiner(red->combiner, vranges);
if (is_sum || CanFactorZeroFromCombiner(red->combiner, red->value_index, vranges)) {
Expr new_red = expr;
// Here we Simplify_cce the reduction
{
Expr cond = red->condition;
Array<Expr> source = red->source;
// If it is a summation then we can lift nonzeroness conditions from the source
// and add them to the reduction conditions
if (is_sum) {
auto nz = NonzeronessCondition(red->source[red->value_index]);
cond = nz.cond && cond;
source.Set(0, nz.value);
}
new_red = Reduce::make(red->combiner, source, red->axis, cond, red->value_index);
new_red = SimplifyReductionDomain(new_red, combined_vranges);
red = new_red.as<Reduce>();
// If the reduction disappears completely then transform the result as a non-reduction
if (!red) {
// For reduction, the keep_dims should be False
return OptimizeAndLiftNonzeronessConditionsImpl(new_red, axis, vranges);
}
}
Expr new_outer_cond, new_reduce_cond;
Array<Expr> new_source = red->source;
// Partially lift conditions from the reduce condition
std::tie(new_outer_cond, new_reduce_cond) = LiftConditionsThroughReduction(red->condition, red->axis, axis);
// If it's not sum then we haven't yet lifted nonzeroness cond from the source
if (!is_sum) {
Expr outer_nz_cond, nz_cond, nz_source;
auto nz = NonzeronessCondition(red->source[red->value_index]);
// Append conditions from the reduction
nz_cond = new_reduce_cond && nz.cond;
nz_source = nz.value;
std::tie(outer_nz_cond, nz_cond) = LiftConditionsThroughReduction(nz_cond, red->axis, axis);
new_outer_cond = new_outer_cond && outer_nz_cond;
new_source.Set(static_cast<size_t>(static_cast<uint>(red->value_index)), SelectElseZero(nz_cond, nz_source));
}
Expr new_reduce = Reduce::make(red->combiner, new_source, red->axis, new_reduce_cond, red->value_index);
new_reduce = ExtractAsTensorMaybe(new_reduce, new_outer_cond, IterVarsToVars(axis), combined_vranges, keep_dims);
result = SelectElseZero(new_outer_cond, new_reduce);
} else {
return SimplifyReductionDomain(expr, combined_vranges);
}
} else {
auto nz = NonzeronessCondition(expr);
Expr new_expr = ExtractAsTensorMaybe(nz.value, nz.cond, IterVarsToVars(axis), combined_vranges, keep_dims);
result = SelectElseZero(nz.cond, new_expr);
}
// Note that RemoveRedundantInequalities can sometimes propagate equalities which
// other simplifiers cannot, like (i % 3) == 0.
Array<Expr> axis_conds = IterVarsToInequalities(axis);
result = RemoveRedundantInequalities(result, axis_conds);
// Sometimes ExtractAsTensorMaybe doesn't perform extraction, so there may be some non-top
// reductions left, take care of them
auto candidate = SuperSimplify(ExtractReductions(result, IterVarsToVars(axis), combined_vranges), combined_vranges);
if (auto select = candidate.as<Select>()) {
auto simplerCond = Simplify_cce(select->condition, IterVarsToMap(axis));
if (!simplerCond.same_as(select->condition)) {
candidate = Select::make(simplerCond, select->true_value, select->false_value);
}
}
return candidate;
}
Tensor OptimizeAndLiftNonzeronessConditions(const Tensor &tensor, bool keep_dims, const Map<Var, Range> &vranges) {
auto transform_func = [&vranges, &keep_dims](const Expr &expr, const Array<IterVar> &axis) {
return OptimizeAndLiftNonzeronessConditionsImpl(expr, axis, vranges, keep_dims);
};
return TransformBody(tensor, transform_func);
}
Domain DomainNode::make(Array<Var> variables, Array<Expr> conditions, Map<Var, Range> ranges) {
auto n = make_node<DomainNode>();
n->variables = std::move(variables);
n->conditions = std::move(conditions);
n->ranges = std::move(ranges);
return Domain(n);
}
TVM_STATIC_IR_FUNCTOR(IRPrinter, vtable).set_dispatch<DomainNode>([](const ObjectRef &node, IRPrinter *p) {
auto *d = static_cast<const DomainNode *>(node.get());
p->stream << "Domain(variables=" << d->variables << ", conditions=" << d->conditions << ", ranges=" << d->ranges
<< ')';
});
TVM_REGISTER_NODE_TYPE(DomainNode);
DomainTransformation DomainTransformationNode::make(Domain new_domain, Domain old_domain, Map<Var, Expr> new_to_old,
Map<Var, Expr> old_to_new) {
auto n = make_node<DomainTransformationNode>();
n->new_domain = std::move(new_domain);
n->old_domain = std::move(old_domain);
n->new_to_old = std::move(new_to_old);
n->old_to_new = std::move(old_to_new);
return DomainTransformation(n);
}
TVM_STATIC_IR_FUNCTOR(IRPrinter, vtable)
.set_dispatch<DomainTransformationNode>([](const ObjectRef &node, IRPrinter *p) {
auto *d = static_cast<const DomainTransformationNode *>(node.get());
p->stream << "DomainTransformation(new_domain=" << d->new_domain << ", old_domain=" << d->old_domain
<< ", new_to_old=" << d->new_to_old << ", old_to_new=" << d->old_to_new << ')';
});
TVM_REGISTER_NODE_TYPE(DomainTransformationNode);
TVM_REGISTER_API("arith._make_Domain").set_body([](const TVMArgs args, TVMRetValue *ret) {
if (args[1].IsObjectRef<Expr>()) {
*ret = DomainNode::make(args[0], FactorOutAtomicFormulas(args[1]).to_array(), args[2]);
} else {
*ret = DomainNode::make(args[0], args[1], args[2]);
}
});
TVM_REGISTER_API("ir_pass.ComposeDomainTransformations").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = ComposeDomainTransformations(args[0], args[1]);
});
TVM_REGISTER_API("ir_pass.EmptyDomainTransformation").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = EmptyDomainTransformation(args[0]);
});
TVM_REGISTER_API("ir_pass.IdDomainTransformation").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = IdDomainTransformation(args[0]);
});
TVM_REGISTER_API("ir_pass.SolveSystemOfEquations").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = SolveSystemOfEquations(args[0]);
});
TVM_REGISTER_API("ir_pass.IsSumCombiner").set_body([](const TVMArgs args, TVMRetValue *ret) {
if (args.size() >= 2) {
*ret = IsSumCombiner(args[0], args[1]);
} else {
*ret = IsSumCombiner(args[0]);
}
});
TVM_REGISTER_API("ir_pass.CanFactorZeroFromCombiner").set_body([](const TVMArgs args, TVMRetValue *ret) {
if (args.size() >= 3) {
*ret = CanFactorZeroFromCombiner(args[0], args[1], args[2]);
} else {
*ret = CanFactorZeroFromCombiner(args[0], args[1]);
}
});
TVM_REGISTER_API("ir_pass.LiftNonzeronessCondition").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = LiftNonzeronessCondition(args[0]);
});
TVM_REGISTER_API("ir_pass.InlineTailCall").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = InlineTailCall(args[0]);
});
TVM_REGISTER_API("ir_pass.InlineTensors").set_body([](const TVMArgs args, TVMRetValue *ret) {
if (args[0].IsObjectRef<Expr>()) {
Expr e = args[0];
if (args.size() == 1) {
*ret = InlineTensors(e);
} else if (args.size() == 2) {
*ret = InlineTensors(e, args[1]);
} else if (args.size() >= 3) {
*ret = InlineTensors(e, args[1], args[2]);
}
} else if (args[0].IsObjectRef<Tensor>()) {
Tensor t = args[0];
if (args.size() == 1) {
*ret = InlineTensors(t);
} else if (args.size() == 2) {
*ret = InlineTensors(t, args[1]);
} else if (args.size() >= 3) {
*ret = InlineTensors(t, args[1], args[2]);
}
}
});
TVM_REGISTER_API("ir_pass.SolveSystemOfInequalities").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = SolveSystemOfInequalities(args[0], args[1], args[2]).as_conditions();
});
TVM_REGISTER_API("ir_pass.SimplifyDomain").set_body([](const TVMArgs args, TVMRetValue *ret) {
if (args.size() == 1) {
*ret = SimplifyDomain(args[0]);
} else {
*ret = SimplifyDomain(args[0], args[1]);
}
});
TVM_REGISTER_API("ir_pass.SimplifyReductionDomain").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = SimplifyReductionDomain(args[0], args[1]);
});
TVM_REGISTER_API("ir_pass.ExtractAsTensorMaybe").set_body([](const TVMArgs args, TVMRetValue *ret) {
CHECK(args.size() >= 4) << "Not enough args.";
if (args.size() == 4) {
*ret = ExtractAsTensorMaybe(args[0], args[1], args[2], args[3]);
} else {
*ret = ExtractAsTensorMaybe(args[0], args[1], args[2], args[3], args[4]);
}
});
TVM_REGISTER_API("ir_pass.ExtractReductions").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = ExtractReductions(args[0], args[1], args[2]);
});
TVM_REGISTER_API("ir_pass.ExtractNonTopReductions").set_body([](const TVMArgs args, TVMRetValue *ret) {
*ret = ExtractNonTopReductions(args[0], args[1], args[2]);
});
TVM_REGISTER_API("ir_pass.OptimizeAndLiftNonzeronessConditions").set_body([](const TVMArgs args, TVMRetValue *ret) {
CHECK(args.size()) << "No given args.";
if (args.size() >= 3) {
*ret = OptimizeAndLiftNonzeronessConditions(args[0], args[1], args[2]);
} else {
if (args.size() >= 2) {
*ret = OptimizeAndLiftNonzeronessConditions(args[0], args[1]);
} else {
*ret = OptimizeAndLiftNonzeronessConditions(args[0]);
}
}
});
Tensor TensorFromExpr(const Expr &expr, const Array<IterVar> &axis, const std::string &name, const std::string &tag,
const Map<std::string, NodeRef> &attrs) {
Array<Expr> new_bodies;
int new_value_index = 0;
// If this is a reduction then we have to clone its body
if (const auto red = expr.as<Reduce>()) {
new_value_index = red->value_index;
for (size_t i = 0; i < red->source.size(); ++i) {
Expr ith_red = Reduce::make(red->combiner, red->source, red->axis, red->condition, static_cast<int>(i));
new_bodies.push_back(ith_red);
}
} else {
new_value_index = 0;
new_bodies.push_back(expr);
}
return ComputeOpNode::make(name, tag, attrs, axis, new_bodies)
.output(static_cast<size_t>(static_cast<uint>(new_value_index)));
}
Tensor TransformBody(const Tensor &tensor, const std::function<Expr(const Expr &, const Array<IterVar> &)> &func) {
if (const auto op = tensor->op.as<ComputeOpNode>()) {
// Transform only one body
Expr new_body = func(op->body[tensor->value_index], op->axis);
// If the body didn't change then we can return the same tensor
if (new_body.same_as(op->body[tensor->value_index])) return tensor;
return TensorFromExpr(new_body, op->axis, op->name, op->tag, op->attrs);
} else {
return tensor;
}
}
Tensor TransformBody(const Tensor &tensor, const std::function<Expr(const Expr &)> &func) {
return TransformBody(tensor, [func](const Expr &e, const Array<IterVar> &) { return func(e); });
}
} // namespace ir
} // namespace akg
| 37.713725 | 120 | 0.653645 | [
"vector",
"transform"
] |
b62b710852dc22ad250778d599e38d03b0556fde | 5,952 | cpp | C++ | apps/KinectV2OSC/addons/ofxImGui/example-helpers/src/ofApp.cpp | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 52 | 2015-01-13T05:17:23.000Z | 2021-05-09T14:09:39.000Z | apps/KinectV2OSC/addons/ofxImGui/example-helpers/src/ofApp.cpp | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 7 | 2015-01-12T10:25:14.000Z | 2018-09-18T12:34:15.000Z | apps/KinectV2OSC/addons/ofxImGui/example-helpers/src/ofApp.cpp | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 31 | 2015-01-12T06:39:15.000Z | 2020-04-06T07:05:08.000Z | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_NOTICE);
ofDisableArbTex();
ofSetBackgroundAuto(false);
ofSetVerticalSync(true);
ofSetFrameRate(60);
this->stepper = 0.0f;
// Gui
this->gui.setup();
this->guiVisible = true;
}
//--------------------------------------------------------------
void ofApp::update()
{
this->stepper += this->speed;
cubeSize = ofMap(sinf(this->stepper), -1.0f, 1.0f, this->sizeMin, this->sizeMax);
}
//--------------------------------------------------------------
void ofApp::draw()
{
// We have to use ofParameter::get() since this we are using an ofFloatColor.
ofClear(this->background.get());
this->camera.begin();
{
ofEnableDepthTest();
ofSetColor(ofColor::white);
if (this->enabled)
{
ofPushStyle();
{
// We have to use ofParameter::get() since this we are using an ofFloatColor.
ofSetColor(this->foreground.get());
auto fillRender = static_cast<RenderMode>(this->fillMode.get());
if (fillRender != RenderMode::None)
{
ofFill();
if (fillRender == RenderMode::Texture && this->texture.isAllocated())
{
this->texture.bind();
}
ofDrawBox(this->cubeSize);
if (fillRender == RenderMode::Texture && this->texture.isAllocated())
{
this->texture.unbind();
}
}
auto strokeRender = static_cast<RenderMode>(this->strokeMode.get());
if (strokeRender != RenderMode::None)
{
ofNoFill();
if (strokeRender == RenderMode::Texture && this->texture.isAllocated())
{
this->texture.bind();
}
ofDrawBox(this->cubeSize);
if (strokeRender == RenderMode::Texture && this->texture.isAllocated())
{
this->texture.unbind();
}
}
}
ofPopStyle();
}
ofDisableDepthTest();
}
this->camera.end();
// Gui
this->mouseOverGui = false;
if (this->guiVisible)
{
this->mouseOverGui = this->imGui();
}
if (this->mouseOverGui)
{
this->camera.disableMouseInput();
}
else
{
this->camera.enableMouseInput();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
//--------------------------------------------------------------
bool ofApp::loadImage(const string & filePath)
{
ofImage image;
image.setUseTexture(false);
if (!image.load(filePath))
{
ofLogError(__FUNCTION__) << "No image found at " << filePath;
return false;
}
ofTextureData texData;
texData.width = image.getWidth();
texData.height = image.getHeight();
texData.textureTarget = GL_TEXTURE_2D;
texData.bFlipTexture = true;
this->texture.allocate(texData);
this->texture.loadData(image.getPixels());
this->imagePath = ofFilePath::makeRelative(ofToDataPath(""), filePath);
return true;
}
//--------------------------------------------------------------
bool ofApp::imGui()
{
auto mainSettings = ofxImGui::Settings();
this->gui.begin();
{
if (ofxImGui::BeginWindow("Helpers", mainSettings, false))
{
ImGui::Text("%.1f FPS (%.3f ms/frame)", ofGetFrameRate(), 1000.0f / ImGui::GetIO().Framerate);
if (ofxImGui::BeginTree(this->colors, mainSettings))
{
ofxImGui::AddParameter(this->background, false);
ofxImGui::AddParameter(this->foreground);
ofxImGui::EndTree(mainSettings);
}
if (ofxImGui::BeginTree(this->mesh, mainSettings))
{
ofxImGui::AddParameter(this->enabled);
ofxImGui::AddRange("Size Range", this->sizeMin, this->sizeMax, 1.0f);
ofxImGui::AddParameter(this->speed);
ImGui::Text("Size: %.2f", this->cubeSize);
ofxImGui::EndTree(mainSettings);
}
if (ofxImGui::BeginTree(this->render, mainSettings))
{
if (ImGui::Button("Load Image..."))
{
auto dialogResult = ofSystemLoadDialog("Load Image", false, ofToDataPath(""));
if (dialogResult.bSuccess)
{
this->loadImage(dialogResult.filePath);
}
}
static const vector<string> labels = { "None", "Color", "Texture" };
ofxImGui::AddRadio(this->fillMode, labels, 3);
ofxImGui::AddRadio(this->strokeMode, labels, 3);
if (this->texture.isAllocated())
{
ofxImGui::AddParameter(this->preview);
}
ofxImGui::EndTree(mainSettings);
}
}
ofxImGui::EndWindow(mainSettings);
if (this->preview)
{
static const float kPreviewSize = 256.0f;
auto previewSettings = ofxImGui::Settings();
previewSettings.windowPos = ofVec2f(ofGetWidth() - kPreviewSize - kImGuiMargin * 3, kImGuiMargin);
previewSettings.windowSize = ofVec2f(kPreviewSize, kPreviewSize);
if (ofxImGui::BeginWindow(this->preview, previewSettings, false))
{
ofxImGui::AddImage(this->texture, previewSettings.windowSize);
}
ofxImGui::EndWindow(previewSettings);
}
}
this->gui.end();
return mainSettings.mouseOverGui;
}
| 23.903614 | 101 | 0.544859 | [
"mesh",
"render",
"vector"
] |
b62ee3f3dddd853646b673d5e7840719466072eb | 5,017 | cpp | C++ | examples/either.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | examples/either.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | examples/either.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/either/apply.hpp>
#include <fcppt/either/bind.hpp>
#include <fcppt/either/error.hpp>
#include <fcppt/either/error_from_optional.hpp>
#include <fcppt/either/map.hpp>
#include <fcppt/either/match.hpp>
#include <fcppt/either/no_error.hpp>
#include <fcppt/either/object.hpp>
#include <fcppt/either/to_exception.hpp>
#include <fcppt/optional/make.hpp>
#include <fcppt/optional/object_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <iostream>
#include <istream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace
{
//! [either_read_raw]
typedef
std::pair<
int,
std::string
>
int_string_pair;
int_string_pair
read_stream_raw(
std::istream &_stream
)
{
int result_int;
if(
!(_stream >> result_int)
)
throw
std::runtime_error{
"Failed reading the int"
};
std::string result_string;
if(
!(_stream >> result_string)
)
throw
std::runtime_error{
"Failed reading the string"
};
return
int_string_pair{
result_int,
result_string
};
}
//! [either_read_raw]
//! [either_read]
template<
typename Type
>
fcppt::either::object<
std::runtime_error,
Type
>
read(
std::istream &_stream,
std::string const &_error
)
{
Type result;
typedef
fcppt::either::object<
std::runtime_error,
Type
>
result_type;
return
_stream >> result
?
result_type{
result
}
:
result_type{
std::runtime_error{
_error
}
}
;
}
//! [either_read]
//! [either_read_apply]
fcppt::either::object<
std::runtime_error,
int_string_pair
>
read_stream_either(
std::istream &_stream
)
{
fcppt::either::object<
std::runtime_error,
int
> const either_int(
read<
int
>(
_stream,
"read int"
)
);
fcppt::either::object<
std::runtime_error,
std::string
> const either_string(
read<
std::string
>(
_stream,
"read string"
)
);
return
fcppt::either::apply(
[](
int const _i,
std::string const &_s
)
{
return
int_string_pair(
_i,
_s
);
},
either_int,
either_string
);
}
//! [either_read_apply]
//! [either_read_bind]
fcppt::either::object<
std::runtime_error,
int_string_pair
>
read_stream_either_bind(
std::istream &_stream
)
{
return
fcppt::either::bind(
read<
int
>(
_stream,
"read int"
),
[
&_stream
](
int const _int_value
)
{
return
fcppt::either::map(
read<
std::string
>(
_stream,
"read string"
),
[
_int_value
](
std::string const &_string_value
)
{
return
std::make_pair(
_int_value,
_string_value
);
}
);
}
);
}
//! [either_read_bind]
//! [either_match]
void
either_match(
std::istream &_stream
)
{
fcppt::either::match(
read_stream_either(
_stream
),
[](
std::runtime_error const &_error
)
{
std::cerr
<< "Reading failed "
<< _error.what()
<< '\n';
},
[](
int_string_pair const &_result
)
{
std::cout
<< "The result is "
<< _result.first
<< ", "
<< _result.second
<< '\n';
}
);
}
//! [either_match]
//! [either_to_exception]
void
either_to_exception(
std::istream &_stream
)
{
int_string_pair const result(
fcppt::either::to_exception(
read_stream_either(
_stream
),
[](
std::runtime_error const &_error
)
{
return
_error;
}
)
);
std::cout
<< "The result is "
<< result.first
<< ", "
<< result.second
<< '\n';
}
//! [either_to_exception]
int
do_something()
{
return
42;
}
enum class error_code
{
failure1
};
//! [either_error]
auto
either_error(
fcppt::optional::object<
error_code
> const _error
)
{
fcppt::either::error<
error_code
> const either_error{
fcppt::either::error_from_optional(
_error
)
};
return
fcppt::either::map(
either_error,
[](
fcppt::either::no_error
)
{
// Do something in case of no error.
return
do_something();
}
);
}
//! [either_error]
}
int
main()
{
{
std::istringstream stream(
"42 test"
);
std::cout
<<
read_stream_raw(
stream
).first
<<
'\n';
}
{
std::istringstream stream(
"42 test"
);
std::cout
<<
read_stream_either(
stream
).has_success()
<<
'\n';
}
{
std::istringstream stream(
"42 test"
);
std::cout
<<
read_stream_either_bind(
stream
).has_success()
<<
'\n';
}
{
std::istringstream stream(
"42 test"
);
either_match(
stream
);
}
{
std::istringstream stream(
"42 test"
);
either_to_exception(
stream
);
}
either_error(
fcppt::optional::make(
error_code::failure1
)
);
}
| 12.831202 | 61 | 0.601953 | [
"object"
] |
b630cd3cb4962b4678c845592b9651c15dfe7874 | 11,302 | cpp | C++ | cognitics/src/sfa/SegmentIntersector.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/src/sfa/SegmentIntersector.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/src/sfa/SegmentIntersector.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | /*************************************************************************
Copyright (c) 2019 Cognitics, Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "sfa/SegmentIntersector.h"
namespace sfa {
//private
bool SegmentIntersector::handleParallel(const Point* p1, const Point* p2, const Point* p3, const Point* p4, Geometry*& result)
{
if (!Collinear(p1,p2,p3)) return false;
//parallel and non collinear case
//between flags
bool Bp1 = Between(p3,p4,p1);
bool Bp3 = Between(p1,p2,p3);
bool Bp2 = Between(p3,p4,p2);
bool Bp4 = Between(p1,p2,p4);
//if none of the points are between each other, there is no intersection
if(!(Bp1 || Bp2 || Bp3 || Bp4)) return false;
//flags for if any of the points are equal to the other end points
bool p1p3 = p1->equals(p3);
bool p1p4 = p1->equals(p4);
bool p2p3 = p2->equals(p3);
bool p2p4 = p2->equals(p4);
//result might be a point, if they intersect at the end points, but only one endpoint
if ( !Bp2 && ((p1p3 && !Bp4) || (p1p4 && !Bp3)) )
{
result = new Point(p1);
return true;
}
else if ( !Bp1 && ((p2p3 && !Bp4) || (p2p4 && !Bp3)) )
{
result = new Point(p2);
return true;
}
std::vector<const Point*> points;
if (Bp1) points.push_back(p1);
if (Bp3 && !p1p3) points.push_back(p3);
if (Bp2 && !p2p3) points.push_back(p2);
if (Bp4) points.push_back(p4);
if (points.size() == 0)
{
return false;
}
else if (points.size() == 1)
{
result = new Point(points.at(0));
return true;
}
//result is a segment
result = new LineString;
static_cast<LineString*>(result)->addPoint(new Point(points[0]));
static_cast<LineString*>(result)->getPointN(0)->clearZ();
static_cast<LineString*>(result)->addPoint(new Point(points[1]));
static_cast<LineString*>(result)->getPointN(1)->clearZ();
return true;
}
bool SegmentIntersector::handleParallel3D(const Point* p1, const Point* p2, const Point* p3, const Point* p4, Geometry* &result)
{
if (!Collinear3D(p1,p2,p3)) return false;
//parallel and non collinear case
//between flags
bool Bp1 = Between3D(p3,p4,p1);
bool Bp3 = Between3D(p1,p2,p3);
bool Bp2 = Between3D(p3,p4,p2);
bool Bp4 = Between3D(p1,p2,p4);
//if none of the points are between each other, there is no intersection
if(!(Bp1 || Bp2 || Bp3 || Bp4)) return false;
//flags for if any of the points are equal to the other end points
bool p1p3 = p1->equals3D(p3);
bool p1p4 = p1->equals3D(p4);
bool p2p3 = p2->equals3D(p3);
bool p2p4 = p2->equals3D(p4);
//result might be a point, if they intersect at the end points, but only one endpoint
if ( !Bp2 && ((p1p3 && !Bp4) || (p1p4 && !Bp3)) )
{
result = new Point(p1);
return true;
}
else if ( !Bp1 && ((p2p3 && !Bp4) || (p2p4 && !Bp3)) )
{
result = new Point(p2);
return true;
}
//result is a segment
result = new LineString;
std::vector<const Point*> points;
if (Bp1) points.push_back(p1);
if (Bp3 && !p1p3) points.push_back(p3);
if (Bp2 && !p2p3) points.push_back(p2);
if (Bp4) points.push_back(p4);
static_cast<LineString*>(result)->addPoint(new Point(points[0]));
static_cast<LineString*>(result)->addPoint(new Point(points[1]));
return true;
}
//public
bool SegmentIntersector::Intersects(const Point* p1, const Point* p2, const Point* p3, const Point* p4)
{
Point u = *p2 - *p1;
Point v = *p4 - *p3;
Point w = *p1 - *p3;
double denom = v.X()*u.Y() - v.Y()*u.X();
if (abs(denom) < SFA_EPSILON)
{
Geometry* temp = NULL;
bool result = handleParallel(p1,p2,p3,p4,temp);
if (temp) delete temp;
return result;
}
double s = (v.Y()*w.X() - v.X()*w.Y())/denom;
if (s < -SFA_EPSILON || s > 1+SFA_EPSILON) return false;
double t = (u.Y()*w.X() - u.X()*w.Y())/denom;
if (t < -SFA_EPSILON || t > 1+SFA_EPSILON) return false;
return true;
}
bool SegmentIntersector::Intersects3D(const Point* p1, const Point* p2, const Point* p3, const Point* p4)
{
//check if the lines are parallel
double dx1 = p2->X() - p1->X();
double dy1 = p2->Y() - p1->Y();
double dz1 = p2->Z() - p1->Z();
double dx2 = p4->X() - p3->X();
double dy2 = p4->Y() - p3->Y();
double dz2 = p4->Z() - p3->Z();
//if (dx1,dy1,dz1) is a multiple of (dx2,dy2,dz2) then they are parallel
if ( (dx1 == dx2 && dy1 == dy2 && dz1 == dz2)
||
( (dx1 != 0) && (dy1*(dx2/dx1) == dy2 && dz1*(dx2/dx1) == dz2) )
||
( (dy1 != 0) && (dx1*(dy2/dy1) == dx2 && dz1*(dy2/dy1) == dz2) )
||
(dx1*(dz2/dz1) == dx2 && dy1*(dz2/dz1) == dy2) )
{
if (!Collinear3D(p1,p2,p3)) return false;
//parallel and non collinear case
//between flags
bool Bp1 = Between3D(p3,p4,p1);
bool Bp3 = Between3D(p1,p2,p3);
bool Bp2 = Between3D(p3,p4,p2);
bool Bp4 = Between3D(p1,p2,p4);
//if none of the points are between each other, there is no intersection
if(!(Bp1 || Bp2 || Bp3 || Bp4)) return false;
return true;
}
double denom;
double t1;
denom = dy1*dx2 - dx1*dy2;
if (denom == 0.0)
{
//test which axis to use to resolve for denom and t1
if ((dx1+dx2) == 0) //use yz plane
{
denom = dz1*dy2 - dy1*dz2;
t1 = ((p3->Z() - p1->Z())*dy2 - (p3->Y() - p1->Y())*dz2)/denom;
}
else //use zx plane
{
denom = dx1*dz2 - dz1*dx2;
t1 = ((p3->X() - p1->X())*dz2 - (p3->Z() - p1->Z())*dx2)/denom;
}
}
else
{
t1 = ((p3->Y() - p1->Y())*dx2 - (p3->X() - p1->X())*dy2)/denom;
}
double x = p1->X() + dx1*t1;
double y = p1->Y() + dy1*t1;
//test Z
double z1 = p1->Z() + dz1*t1;
//find t2
double t2;
if (dx2 != 0) t2 = (x - p3->X())/dx2;
else if (dy2 != 0) t2 = (y - p3->Y())/dy2;
else t2 = (z1 - p3->Z())/dz2;
double z2 = p3->Z() + (p4->Z() - p3->Z())*t2;
if (z1 != z2) return false;
Point test(x,y,z1);
if (Between3D(p1,p2,&test) && Between3D(p3,p4,&test))
return true;
else return false;
}
//public
bool SegmentIntersector::Intersection(const Point* p1, const Point* p2, const Point* p3, const Point* p4, Geometry*& result)
{
Point u = *p2 - *p1;
Point v = *p4 - *p3;
Point w = *p1 - *p3;
double denom = v.X()*u.Y() - v.Y()*u.X();
if (abs(denom) < SFA_EPSILON)
return handleParallel(p1,p2,p3,p4,result);
double s = (v.Y()*w.X() - v.X()*w.Y())/denom;
if (s < -SFA_EPSILON || s > 1+SFA_EPSILON) return false;
double t = (u.Y()*w.X() - u.X()*w.Y())/denom;
if (t < -SFA_EPSILON || t > 1+SFA_EPSILON) return false;
result = new Point( *p1 + u*s );
return true;
}
bool SegmentIntersector::Intersection3D(const Point* p1, const Point* p2, const Point* p3, const Point* p4, Geometry*& result)
{
//check if the lines are parallel
double dx1 = p2->X() - p1->X();
double dy1 = p2->Y() - p1->Y();
double dz1 = p2->Z() - p1->Z();
double dx2 = p4->X() - p3->X();
double dy2 = p4->Y() - p3->Y();
double dz2 = p4->Z() - p3->Z();
//if (dx1,dy1,dz1) is a multiple of (dx2,dy2,dz2) then they are parallel
if (dx1 == dx2 && dy1 == dy2 && dz1 == dz2)
{
return handleParallel(p1,p2,p3,p4,result);
}
else if (dx1 != 0)
{
if (dy1*(dx2/dx1) == dy2 && dz1*(dx2/dx1) == dz2) return handleParallel(p1,p2,p3,p4,result);
}
else if (dy1 != 0)
{
if (dx1*(dy2/dy1) == dx2 && dz1*(dy2/dy1) == dz2) return handleParallel(p1,p2,p3,p4,result);
}
else
{
if (dx1*(dz2/dz1) == dx2 && dy1*(dz2/dz1) == dy2) return handleParallel(p1,p2,p3,p4,result);
}
double denom;
double t1;
denom = dy1*dx2 - dx1*dy2;
if (denom == 0.0)
{
//test which axis to use to resolve for denom and t1
if ((dx1+dx2) == 0) //use yz plane
{
denom = dz1*dy2 - dy1*dz2;
t1 = ((p3->Z() - p1->Z())*dy2 - (p3->Y() - p1->Y())*dz2)/denom;
}
else //use zx plane
{
denom = dx1*dz2 - dz1*dx2;
t1 = ((p3->X() - p1->X())*dz2 - (p3->Z() - p1->Z())*dx2)/denom;
}
}
else
{
t1 = ((p3->Y() - p1->Y())*dx2 - (p3->X() - p1->X())*dy2)/denom;
}
double x = p1->X() + dx1*t1;
double y = p1->Y() + dy1*t1;
//test Z
double z1 = p1->Z() + dz1*t1;
//find t2
double t2;
if (dx2 != 0) t2 = (x - p3->X())/dx2;
else if (dy2 != 0) t2 = (y - p3->Y())/dy2;
else t2 = (z1 - p3->Z())/dz2;
double z2 = p3->Z() + (p4->Z() - p3->Z())*t2;
if (z1 != z2) return false;
Point* test = new Point(x,y,z1);
if (z1 == 0) test->clearZ();
if (Between3D(p1,p2,test) && Between3D(p3,p4,test))
{
result = test;
return true;
}
delete test;
return false;
}
} | 33.93994 | 132 | 0.496726 | [
"geometry",
"vector"
] |
ac0750e8e211334f3ab43a6524bcbe1dfa6a467c | 4,204 | cpp | C++ | frontend/dcwMain.cpp | WeDPR-Team/libPSI | 9c506b7be66e99363eb20878a8e146534a47bb78 | [
"Unlicense"
] | 91 | 2016-06-19T15:01:08.000Z | 2022-03-26T21:05:00.000Z | frontend/dcwMain.cpp | WeDPR-Team/libPSI | 9c506b7be66e99363eb20878a8e146534a47bb78 | [
"Unlicense"
] | 30 | 2019-03-04T11:49:37.000Z | 2022-03-10T07:45:59.000Z | frontend/dcwMain.cpp | WeDPR-Team/libPSI | 9c506b7be66e99363eb20878a8e146534a47bb78 | [
"Unlicense"
] | 31 | 2017-09-25T03:05:25.000Z | 2022-01-19T09:25:38.000Z |
#include "dcwMain.h"
#include "cryptoTools/Network/Endpoint.h"
#include "libPSI/PSI/Dcw/DcwRBfPsiReceiver.h"
#include "libPSI/PSI/Dcw/DcwRBfPsiSender.h"
#include "cryptoTools/Common/Defines.h"
#include "libOTe/TwoChooseOne/IknpOtExtReceiver.h"
#include "libOTe/TwoChooseOne/IknpOtExtSender.h"
#include "libOTe/TwoChooseOne/SilentOtExtReceiver.h"
#include "libOTe/TwoChooseOne/SilentOtExtSender.h"
#include "cryptoTools/Common/Log.h"
#include "cryptoTools/Common/Timer.h"
#include "cryptoTools/Crypto/PRNG.h"
#include <fstream>
#include <algorithm>
#include "boost/format.hpp"
extern u8 dummy[];
using namespace osuCrypto;
void DcwRSend(
LaunchParams& params)
{
#ifdef ENABLE_DCW_PSI
PRNG prng(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
for (auto setSize : params.mNumItems)
{
for (auto tt : params.mNumThreads)
{
if (tt != 1)
{
continue;
}
auto chls = params.getChannels(tt);
for (u64 jj = 0; jj < params.mTrials; jj++)
{
std::vector<block> set(setSize);
for (u64 i = 0; i < setSize; ++i)
set[i] = prng.get<block>();
SilentOtExtReceiver sRecv;
SilentOtExtSender sSend;
IknpOtExtReceiver iRecv;
IknpOtExtSender iSend;
bool silent = params.mCmd->isSet("silent");
//OtExtReceiver& otRecv = silent ? (OtExtReceiver&)sRecv : iRecv;
OtExtSender& otSend = silent ? (OtExtSender&)sSend : iSend;
DcwRBfPsiSender sendPSIs;
gTimer.reset();
sendPSIs.init(setSize, params.mStatSecParam, otSend, chls, prng.get<block>());
chls[0].asyncSend(dummy, 1);
sendPSIs.sendInput(set, chls);
}
}
}
#else
std::cout << Color::Red << "DCW PSI is not enabled" << std::endl << Color::Default;
#endif
}
void DcwRRecv(
LaunchParams& params)
{
#ifdef ENABLE_DCW_PSI
PRNG prng(_mm_set_epi32(4253465, 3434565, 234435, 23987045));
for (auto setSize : params.mNumItems)
{
for (u64 numThreads : params.mNumThreads)
{
if (numThreads != 1)
{
std::cout << "dcwr n = " << setSize << " t = " << numThreads << " skipped, t > 1 (multi-thread) not implemented." << std::endl;
continue;
}
auto chls = params.getChannels(numThreads);
for (u64 jj = 0; jj < params.mTrials; jj++)
{
std::vector<block> set(setSize);
for (u64 i = 0; i < setSize; ++i)
set[i] =prng.get<block>();
SilentOtExtReceiver sRecv;
SilentOtExtSender sSend;
IknpOtExtReceiver iRecv;
IknpOtExtSender iSend;
bool silent = params.mCmd->isSet("silent");
OtExtReceiver& otRecv = silent ? (OtExtReceiver&)sRecv : iRecv;
//OtExtSender& otSend = silent ? (OtExtSender&)sSend : iSend;
DcwRBfPsiReceiver recvPSIs;
gTimer.reset();
Timer timer;
auto start = timer.setTimePoint("start");
recvPSIs.init(setSize, params.mStatSecParam, otRecv, chls, sysRandomSeed());
chls[0].recv(dummy, 1);
auto mid = timer.setTimePoint("init");
recvPSIs.sendInput(set, chls);
auto end = timer.setTimePoint("done");
auto offlineTime = std::chrono::duration_cast<std::chrono::milliseconds>(mid - start).count();
auto onlineTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - mid).count();
//std::cout << setSize << " " << offlineTime << " " << online << std::endl;
std::string tag("DCWR");
printTimings(tag, chls, offlineTime, onlineTime, params, setSize, numThreads);
}
}
}
#else
std::cout << Color::Red << "DCW PSI is not enabled" << std::endl << Color::Default;
#endif
}
| 29.605634 | 143 | 0.550904 | [
"vector"
] |
ac0b5432dedb38592e07a29bbea750558f74031d | 2,365 | hpp | C++ | include/ghex/buffer_info.hpp | GridTools/GHEX | 1adce924c02cf0553d2ceed69f7dc37e39c7013d | [
"BSD-3-Clause"
] | 9 | 2020-01-30T08:12:40.000Z | 2022-01-17T11:18:07.000Z | include/ghex/buffer_info.hpp | ghex-org/GHEX | 6eb91410d5c01d36a70f0eb106c1f065df3cee9f | [
"BSD-3-Clause"
] | 50 | 2019-12-19T13:25:56.000Z | 2021-09-16T13:57:36.000Z | include/ghex/buffer_info.hpp | ghex-org/GHEX | 6eb91410d5c01d36a70f0eb106c1f065df3cee9f | [
"BSD-3-Clause"
] | 10 | 2019-12-10T15:31:36.000Z | 2021-07-04T19:31:28.000Z | /*
* GridTools
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#pragma once
#include <ghex/arch_traits.hpp>
#include <vector>
namespace ghex
{
// forward declaration
template<typename GridType, typename DomainIdType>
class pattern;
template<typename GridType, typename DomainIdType>
class pattern_container;
// forward declaration
template<typename Pattern, typename Arch, typename Field>
struct buffer_info;
/** @brief ties together field, pattern and device
* @tparam GridType grid tag type
* @tparam DomainIdType domain id type
* @tparam Arch device type
* @tparam Field field descriptor type */
template<typename GridType, typename DomainIdType, typename Arch, typename Field>
struct buffer_info<pattern<GridType, DomainIdType>, Arch, Field>
{
public: // member types
using pattern_type = pattern<GridType, DomainIdType>;
using pattern_container_type = pattern_container<GridType, DomainIdType>;
using arch_type = Arch;
using field_type = Field;
using device_id_type = typename arch_traits<arch_type>::device_id_type;
using value_type = typename field_type::value_type;
private: // friend class
friend class pattern<GridType, DomainIdType>;
private: // private ctor
buffer_info(const pattern_type& p, field_type& field, device_id_type id) noexcept
: m_p{&p}
, m_field{&field}
, m_id{id}
{
}
public: // copy and move ctors
buffer_info(const buffer_info&) noexcept = default;
buffer_info(buffer_info&&) noexcept = default;
public: // member functions
device_id_type device_id() const noexcept { return m_id; }
const pattern_type& get_pattern() const noexcept { return *m_p; }
const pattern_container_type& get_pattern_container() const noexcept
{
return m_p->container();
}
field_type& get_field() noexcept { return *m_field; }
private: // members
const pattern_type* m_p;
field_type* m_field;
device_id_type m_id;
};
template<typename T>
struct is_buffer_info : public std::false_type
{
};
template<typename Pattern, typename Arch, typename Field>
struct is_buffer_info<buffer_info<Pattern, Arch, Field>> : public std::true_type
{
};
} // namespace ghex
| 27.823529 | 85 | 0.717548 | [
"vector"
] |
ac0e1e417f7be43be55a04f44fb8ea0beb54ee31 | 17,333 | cc | C++ | hand-gesture-recognition/hand-gesture-recognition-calculator.cc | Amankumar1456/IC464_Sixth_Sense | 08ba64f0d94b2a7acb6b79eb2159cbdf493d1a65 | [
"Apache-2.0"
] | 1 | 2020-09-30T08:14:46.000Z | 2020-09-30T08:14:46.000Z | hand-gesture-recognition/hand-gesture-recognition-calculator.cc | Amankumar1456/IC464_Sixth_Sense | 08ba64f0d94b2a7acb6b79eb2159cbdf493d1a65 | [
"Apache-2.0"
] | null | null | null | hand-gesture-recognition/hand-gesture-recognition-calculator.cc | Amankumar1456/IC464_Sixth_Sense | 08ba64f0d94b2a7acb6b79eb2159cbdf493d1a65 | [
"Apache-2.0"
] | 1 | 2020-08-04T12:36:14.000Z | 2020-08-04T12:36:14.000Z | #include <cmath>
#include <stdlib.h>
<<<<<<< HEAD
#include <iostream>
#include <cstring>
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/landmark.pb.h"
#include "mediapipe/framework/formats/rect.pb.h"
namespace mediapipe
{
<<<<<<< HEAD
std::string text = "";
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
namespace
{
constexpr char normRectTag[] = "NORM_RECT";
constexpr char normalizedLandmarkListTag[] = "NORM_LANDMARKS";
<<<<<<< HEAD
constexpr char recognizedHandGestureTag[] = "RECOGNIZED_HAND_GESTURE";
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
}
/*
// Graph config:
//
// node {
// calculator: "HandGestureRecognitionCalculator"
// input_stream: "NORM_LANDMARKS:scaled_landmarks"
// input_stream: "NORM_RECT:hand_rect_for_next_frame"
// }
*/
class HandGestureRecognitionCalculator : public CalculatorBase
{
public:
static ::mediapipe::Status GetContract(CalculatorContract *cc);
::mediapipe::Status Open(CalculatorContext *cc) override;
::mediapipe::Status Process(CalculatorContext *cc) override;
private:
<<<<<<< HEAD
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
float get_Euclidean_DistanceAB(float a_x, float a_y, float b_x, float b_y)
{
float dist = std::pow(a_x - b_x, 2) + pow(a_y - b_y, 2);
return std::sqrt(dist);
}
};
REGISTER_CALCULATOR(HandGestureRecognitionCalculator);
::mediapipe::Status HandGestureRecognitionCalculator::GetContract(
CalculatorContract *cc)
{
RET_CHECK(cc->Inputs().HasTag(normalizedLandmarkListTag));
cc->Inputs().Tag(normalizedLandmarkListTag).Set<mediapipe::NormalizedLandmarkList>();
RET_CHECK(cc->Inputs().HasTag(normRectTag));
cc->Inputs().Tag(normRectTag).Set<NormalizedRect>();
<<<<<<< HEAD
RET_CHECK(cc->Outputs().HasTag(recognizedHandGestureTag));
cc->Outputs().Tag(recognizedHandGestureTag).Set<std::string>();
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
return ::mediapipe::OkStatus();
}
::mediapipe::Status HandGestureRecognitionCalculator::Open(
CalculatorContext *cc)
{
cc->SetOffset(TimestampDiff(0));
return ::mediapipe::OkStatus();
}
::mediapipe::Status HandGestureRecognitionCalculator::Process(
CalculatorContext *cc)
{
<<<<<<< HEAD
std::string *recognized_hand_gesture;
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
// hand closed (red) rectangle
const auto rect = &(cc->Inputs().Tag(normRectTag).Get<NormalizedRect>());
float width = rect->width();
float height = rect->height();
float rot = rect->rotation();
<<<<<<< HEAD
char cur = '\u0000';
if (width < 0.01 || height < 0.01)
{
LOG(INFO) << "No Hand Detected";
recognized_hand_gesture = new std::string("");
cc->Outputs()
.Tag(recognizedHandGestureTag)
.Add(recognized_hand_gesture, cc->InputTimestamp());
return ::mediapipe::OkStatus();
}
/*recognized_hand_gesture = new std::string("Please call me ");
cc->Outputs()
.Tag(recognizedHandGestureTag)
.Add(recognized_hand_gesture, cc->InputTimestamp());
return ::mediapipe::OkStatus();*/
=======
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
const auto &landmarkList = cc->Inputs()
.Tag(normalizedLandmarkListTag)
.Get<mediapipe::NormalizedLandmarkList>();
RET_CHECK_GT(landmarkList.landmark_size(), 0) << "Input landmark vector is empty.";
float l0x= landmarkList.landmark(0).x();
float l0y= landmarkList.landmark(0).y();
float l0z= landmarkList.landmark(0).z();
float l1x= landmarkList.landmark(1).x();
float l1y= landmarkList.landmark(1).y();
float l1z= landmarkList.landmark(1).z();
float l2x= landmarkList.landmark(2).x();
float l2y= landmarkList.landmark(2).y();
float l2z= landmarkList.landmark(2).z();
float l3x= landmarkList.landmark(3).x();
float l3y= landmarkList.landmark(3).y();
float l3z= landmarkList.landmark(3).z();
float l4x= landmarkList.landmark(4).x();
float l4y= landmarkList.landmark(4).y();
float l4z= landmarkList.landmark(4).z();
float l5x= landmarkList.landmark(5).x();
float l5y= landmarkList.landmark(5).y();
float l5z= landmarkList.landmark(5).z();
float l6x= landmarkList.landmark(6).x();
float l6y= landmarkList.landmark(6).y();
float l6z= landmarkList.landmark(6).z();
float l7x= landmarkList.landmark(7).x();
float l7y= landmarkList.landmark(7).y();
float l7z= landmarkList.landmark(7).z();
float l8x= landmarkList.landmark(8).x();
float l8y= landmarkList.landmark(8).y();
float l8z= landmarkList.landmark(8).z();
float l9x= landmarkList.landmark(9).x();
float l9y= landmarkList.landmark(9).y();
float l9z= landmarkList.landmark(9).z();
float l10x= landmarkList.landmark(10).x();
float l10y= landmarkList.landmark(10).y();
float l10z= landmarkList.landmark(10).z();
float l11x= landmarkList.landmark(11).x();
float l11y= landmarkList.landmark(11).y();
float l11z= landmarkList.landmark(11).z();
float l12x= landmarkList.landmark(12).x();
float l12y= landmarkList.landmark(12).y();
float l12z= landmarkList.landmark(12).z();
float l13x= landmarkList.landmark(13).x();
float l13y= landmarkList.landmark(13).y();
float l13z= landmarkList.landmark(13).z();
float l14x= landmarkList.landmark(14).x();
float l14y= landmarkList.landmark(14).y();
float l14z= landmarkList.landmark(14).z();
float l15x= landmarkList.landmark(15).x();
float l15y= landmarkList.landmark(15).y();
float l15z= landmarkList.landmark(15).z();
float l16x= landmarkList.landmark(16).x();
float l16y= landmarkList.landmark(16).y();
float l16z= landmarkList.landmark(16).z();
float l17x= landmarkList.landmark(17).x();
float l17y= landmarkList.landmark(17).y();
float l17z= landmarkList.landmark(17).z();
float l18x= landmarkList.landmark(18).x();
float l18y= landmarkList.landmark(18).y();
float l18z= landmarkList.landmark(18).z();
float l19x= landmarkList.landmark(19).x();
float l19y= landmarkList.landmark(19).y();
float l19z= landmarkList.landmark(19).z();
float l20x= landmarkList.landmark(20).x();
float l20y= landmarkList.landmark(20).y();
float l20z= landmarkList.landmark(20).z();
/*
LOG(INFO) << "\n\n";
LOG(INFO) << "Landmark 0 coordinates : " << l0x <<"\t"<<l0y<<"\t"<<l0z;
LOG(INFO) << "Landmark 1 coordinates : " << l1x <<"\t"<<l1y<<"\t"<<l1z;
LOG(INFO) << "Landmark 2 coordinates : " << l2x <<"\t"<<l2y<<"\t"<<l2z;
LOG(INFO) << "Landmark 3 coordinates : " << l3x <<"\t"<<l3y<<"\t"<<l3z;
LOG(INFO) << "Landmark 4 coordinates : " << l4x <<"\t"<<l4y<<"\t"<<l4z;
LOG(INFO) << "Landmark 5 coordinates : " << l5x <<"\t"<<l5y<<"\t"<<l5z;
LOG(INFO) << "Landmark 6 coordinates : " << l6x <<"\t"<<l6y<<"\t"<<l6z;
LOG(INFO) << "Landmark 7 coordinates : " << l7x <<"\t"<<l7y<<"\t"<<l7z;
LOG(INFO) << "Landmark 8 coordinates : " << l8x <<"\t"<<l8y<<"\t"<<l8z;
LOG(INFO) << "Landmark 9 coordinates : " << l9x <<"\t"<<l9y<<"\t"<<l9z;
LOG(INFO) << "Landmark 10 coordinates : " << l10x <<"\t"<<l10y<<"\t"<<l10z;
LOG(INFO) << "Landmark 11 coordinates : " << l11x <<"\t"<<l11y<<"\t"<<l11z;
LOG(INFO) << "Landmark 12 coordinates : " << l12x <<"\t"<<l12y<<"\t"<<l12z;
LOG(INFO) << "Landmark 13 coordinates : " << l13x <<"\t"<<l13y<<"\t"<<l13z;
LOG(INFO) << "Landmark 14 coordinates : " << l14x <<"\t"<<l14y<<"\t"<<l14z;
LOG(INFO) << "Landmark 15 coordinates : " << l15x <<"\t"<<l15y<<"\t"<<l15z;
LOG(INFO) << "Landmark 16 coordinates : " << l16x <<"\t"<<l16y<<"\t"<<l16z;
LOG(INFO) << "Landmark 17 coordinates : " << l17x <<"\t"<<l17y<<"\t"<<l17z;
LOG(INFO) << "Landmark 18 coordinates : " << l18x <<"\t"<<l18y<<"\t"<<l18z;
LOG(INFO) << "Landmark 19 coordinates : " << l19x <<"\t"<<l19y<<"\t"<<l19z;
LOG(INFO) << "Landmark 20 coordinates : " << l20x <<"\t"<<l20y<<"\t"<<l20z;
<<<<<<< HEAD
LOG(INFO) << "\n\n";*/
//LOG(INFO) << rot;
char orientation = 'n';
if(rot<0.5 && rot>-0.5)
orientation = 'u';
else if(rot<-0.5 && rot>-1.5)
orientation = 'l';
else if(rot<-1.5)
orientation = 'd';
if(orientation == 'n') {
return ::mediapipe::OkStatus();
}
//LOG(INFO) << orientation;
if(orientation=='u' && l4y<l3y && l8y<l7y && l12y<l11y && l16y<l15y && l20y<l19y) {
recognized_hand_gesture = new std::string(" ");
cur = ' ';
}
if(orientation=='u' && l6y<l7y&&l6y<l8y&&l10y<l11y&&l10y<l12y&&l14y<l15y&&l14y<l16y&&l18y<l19y&&l18y<l20y) {
if(l4y>l8y||l4y>l12y||l4y>l16y||l4y>l20y) {
recognized_hand_gesture = new std::string("E");
cur = 'E';
LOG(INFO) << "E";
//return ::mediapipe::OkStatus();
}
else {
if(l4x<l6x) {
recognized_hand_gesture = new std::string("A");
cur = 'A';
LOG(INFO) << "A";
//return ::mediapipe::OkStatus();
}
else if(l4z<l7z || l4z<l11z || l4z<l15z) {
recognized_hand_gesture = new std::string("S");
cur = 'S';
LOG(INFO) << "S";
//return ::mediapipe::OkStatus();
}
else if((l4y<l10y && l4y<l6y) && (l4x<l10x)) {
recognized_hand_gesture = new std::string("T");
cur = 'T';
LOG(INFO) << "T";
//return ::mediapipe::OkStatus();
}
}
}
else if(orientation=='u' && l2x<l4x && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l8y<l7y && l8y<l6y && l12y<l11y && l12y<l10y) {
float d812 = get_Euclidean_DistanceAB(l8x, l8y, l12x, l12y);
float d711 = get_Euclidean_DistanceAB(l7x, l7y, l11x, l11y);
if(d812 > 0.1) {
recognized_hand_gesture = new std::string("V");
cur = 'V';
LOG(INFO) << "V";
//return ::mediapipe::OkStatus();
}
else if(l7z<l11z) {
recognized_hand_gesture = new std::string("R");
cur = 'R';
LOG(INFO) << "R";
//return ::mediapipe::OkStatus();
}
else if(d711 < 0.1) {
recognized_hand_gesture = new std::string("U");
cur = 'U';
LOG(INFO) << "U";
//return ::mediapipe::OkStatus();
}
}
else if(orientation=='u' && get_Euclidean_DistanceAB(l4x, l4y, l12x, l12y)<0.1 && get_Euclidean_DistanceAB(l4x, l4y, l16x, l16y)<0.1 && get_Euclidean_DistanceAB(l4x, l4y, l20x, l20y)<0.1 && l8y<l7y && l8y<l6y) {
recognized_hand_gesture = new std::string("D");
cur = 'D';
LOG(INFO) << "D";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l12y>l11y && l12y>l10y && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l4x>l5x) {
if(l8y<l7y && l8y<l6y && abs(l8z-l7z)>5) {
recognized_hand_gesture = new std::string("X");
cur = 'X';
LOG(INFO) << "X";
//return ::mediapipe::OkStatus();
}
else if(l8y<l7y && l8y<l6y) {
recognized_hand_gesture = new std::string("Z");
cur = 'Z';
LOG(INFO) << "Z";
//return ::mediapipe::OkStatus();
}
}
else if(orientation=='u' && l20y<l19y && l20y<l18y && l16y<l15y && l16y<l14y && l12y<l11y && l12y<l10y && l8y>l7y && l8y>l6y && l4x>l5x) {
recognized_hand_gesture = new std::string("F");
cur = 'F';
LOG(INFO) << "F";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l20y<l19y && l20y<l18y && l16y<l15y && l16y<l14y && l12y<l11y && l12y<l10y && l8y<l7y && l8y<l6y && l4x>l5x) {
recognized_hand_gesture = new std::string("B");
cur = 'B';
LOG(INFO) << "B";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l20y<l19y && l20y<l18y && l16y>l15y && l16y>l14y && l12y>l11y && l12y>l10y && l8y>l7y && l8y>l6y && l4x>l5x) {
recognized_hand_gesture = new std::string("I");
cur = 'I';
LOG(INFO) << "I";
//return ::mediapipe::OkStatus();
}
else if(orientation=='l' && l20x<l19x && l20x<l18x && l16x>l15x && l16x>l14x && l12x>l11x && l12x>l10x && l8x>l7x && l8x>l6x && l4y>l5y) {
recognized_hand_gesture = new std::string("J");
cur = 'J';
LOG(INFO) << "J";
//return ::mediapipe::OkStatus();
}
else if(orientation=='l' && l20x>l19x && l20x>l18x && l16x>l15x && l16x>l14x && l12x>l11x && l12x>l10x && l8x<l7x && l8x<l6x && l4x<l5x) {
recognized_hand_gesture = new std::string("G");
cur = 'G';
LOG(INFO) << "G";
//return ::mediapipe::OkStatus();
}
else if(orientation=='l' && l20x>l19x && l20x>l18x && l16x>l15x && l16x>l14x && l12x<l11x && l12x<l10x && l8x<l7x && l8x<l6x && l4x<l5x) {
recognized_hand_gesture = new std::string("H");
cur = 'H';
LOG(INFO) << "H";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l4x>l5x && l8y<l7y && l8y<l6y && l12y<l11y && l12y<l10y && l16y<l15y && l16y<l14y && l20y>l19y && l20y>l18y) {
recognized_hand_gesture = new std::string("W");
cur = 'W';
LOG(INFO) << "W";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l4x<l5x && l8y>l7y && l8y>l6y && l12y>l11y && l12y>l10y && l16y>l15y && l16y>l14y && l20y<l19y && l20y<l18y) {
recognized_hand_gesture = new std::string("Y");
cur = 'Y';
LOG(INFO) << "Y";
//return ::mediapipe::OkStatus();
}
else if(orientation=='l' && l20x<l17x && l16x<l13x && l12x<l9x && l8x<l5x && l4x<l2x) {
float d48 = get_Euclidean_DistanceAB(l4x, l4y, l8x, l8y);
if(d48<0.2) {
recognized_hand_gesture = new std::string("O");
cur = 'O';
LOG(INFO) << "O";
//return ::mediapipe::OkStatus();
}
else {
recognized_hand_gesture = new std::string("C");
cur = 'C';
LOG(INFO) << "C";
//return ::mediapipe::OkStatus();
}
}
else if(orientation=='u' && l4x<l5x && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l8y<l7y && l8y<l6y && l12y<l11y && l12y<l10y) {
recognized_hand_gesture = new std::string("K");
cur = 'K';
LOG(INFO) << "K";
//return ::mediapipe::OkStatus();
}
else if(orientation=='u' && l4x<l5x && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l8y<l7y && l8y<l6y && l12y>l11y && l12y>l10y) {
recognized_hand_gesture = new std::string("L");
cur = 'L';
LOG(INFO) << "L";
//return ::mediapipe::OkStatus();
}
else if(orientation=='d') {
recognized_hand_gesture = new std::string("");
cur = '\u0000';
LOG(INFO) << "Downward Gesture";
}
if(text.size()>0) {
char prev = text[text.size()-1];
if(prev!=cur) {
text.push_back(cur);
}
}
else {
text.push_back(cur);
}
recognized_hand_gesture = new std::string(text);
LOG(INFO) << text;
cc->Outputs()
.Tag(recognizedHandGestureTag)
.Add(recognized_hand_gesture, cc->InputTimestamp());
=======
LOG(INFO) << "\n\n";
*/
if (width < 0.01 || height < 0.01)
{
LOG(INFO) << "No Hand Detected";
return ::mediapipe::OkStatus();
}
if(l6y<l7y&&l6y<l8y&&l10y<l11y&&l10y<l12y&&l14y<l15y&&l14y<l16y&&l18y<l19y&&l18y<l20y) {
if(l4y>l8y||l4y>l12y||l4y>l16y||l4y>l20y) {
LOG(INFO) << "E";
return ::mediapipe::OkStatus();
}
else {
if(l4x<l6x) {
LOG(INFO) << "A";
return ::mediapipe::OkStatus();
}
else if(l4z<l7z || l4z<l11z || l4z<l15z) {
LOG(INFO) << "S";
return ::mediapipe::OkStatus();
}
else if((l4y<l10y && l4y<l6y) && (l4x<l10x)) {
LOG(INFO) << "T";
return ::mediapipe::OkStatus();
}
}
}
else if(l2x<l4x && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l8y<l7y && l8y<l6y && l12y<l11y && l12y<l10y) {
float d812 = get_Euclidean_DistanceAB(l8x, l8y, l12x, l12y);
float d711 = get_Euclidean_DistanceAB(l7x, l7y, l11x, l11y);
if(d812 > 0.1) {
LOG(INFO) << "V";
return ::mediapipe::OkStatus();
}
else if(l7z<l11z) {
LOG(INFO) << "R";
return ::mediapipe::OkStatus();
}
else if(d711 < 0.1) {
LOG(INFO) << "U";
return ::mediapipe::OkStatus();
}
}
else if(get_Euclidean_DistanceAB(l4x, l4y, l12x, l12y)<0.1 && get_Euclidean_DistanceAB(l4x, l4y, l16x, l16y)<0.1 && get_Euclidean_DistanceAB(l4x, l4y, l20x, l20y)<0.1 && l8y<l7y && l8y<l6y) {
LOG(INFO) << "D";
return ::mediapipe::OkStatus();
}
else if(l12y>l11y && l12y>l10y && l16y>l15y && l16y>l14y && l20y>l19y && l20y>l18y && l4x>l5x) {
if(l8y<l7y && l8y<l6y && abs(l8z-l7z)>5) {
LOG(INFO) << "X";
return ::mediapipe::OkStatus();
}
else if(l8y<l7y && l8y<l6y) {
LOG(INFO) << "Z";
return ::mediapipe::OkStatus();
}
}
else if(l20y<l19y && l20y<l18y && l16y<l15y && l16y<l14y && l12y<l11y && l12y<l10y && l8y>l7y && l8y>l6y && l4x>l5x) {
LOG(INFO) << "F";
return ::mediapipe::OkStatus();
}
else if(l20y<l19y && l20y<l18y && l16y<l15y && l16y<l14y && l12y<l11y && l12y<l10y && l8y<l7y && l8y<l6y && l4x>l5x) {
LOG(INFO) << "B";
return ::mediapipe::OkStatus();
}
else if(l20y<l19y && l20y<l18y && l16y>l15y && l16y>l14y && l12y>l11y && l12y>l10y && l8y>l7y && l8y>l6y && l4x>l5x) {
LOG(INFO) << "I";
return ::mediapipe::OkStatus();
}
else if(l20x<l19x && l20x<l18x && l16x>l15x && l16x>l14x && l12x>l11x && l12x>l10x && l8x>l7x && l8x>l6x && l4y>l5y) {
LOG(INFO) << "J";
return ::mediapipe::OkStatus();
}
else if(l20x>l19x && l20x>l18x && l16x>l15x && l16x>l14x && l12x>l11x && l12x>l10x && l8x<l7x && l8x<l6x && l4x<l5x) {
LOG(INFO) << "G";
return ::mediapipe::OkStatus();
}
else if(l20x>l19x && l16x>l15x && l12x<l11x && l8x<l7x && l4x>l5x) {
LOG(INFO) << "H";
return ::mediapipe::OkStatus();
}
else if(l20x<l17x && l16x<l13x && l12x<l9x && l8x<l5x && l4x<l2x) {
float d48 = get_Euclidean_DistanceAB(l4x, l4y, l8x, l8y);
if(d48<0.1) {
LOG(INFO) << "O";
return ::mediapipe::OkStatus();
}
else {
LOG(INFO) << "C";
return ::mediapipe::OkStatus();
}
}
>>>>>>> 3a7d6a46c987f0ce67fc909c3c407a9997a71478
return ::mediapipe::OkStatus();
}
} | 33.078244 | 212 | 0.618647 | [
"vector"
] |
ac16d7dcd7801943536afbd5b555f7022c86dd7b | 17,119 | cc | C++ | smbprovider/smbprovider_test_helper.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | smbprovider/smbprovider_test_helper.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | smbprovider/smbprovider_test_helper.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "smbprovider/smbprovider_test_helper.h"
#include <algorithm>
#include <gtest/gtest.h>
#include "smbprovider/mount_config.h"
#include "smbprovider/netbios_packet_parser.h"
#include "smbprovider/proto_bindings/directory_entry.pb.h"
#include "smbprovider/temp_file_manager.h"
namespace smbprovider {
namespace {
template <typename ProtoType>
ProtoBlob SerializeProtoToBlobAndCheck(const ProtoType& proto) {
ProtoBlob proto_blob;
EXPECT_EQ(ERROR_OK, SerializeProtoToBlob(proto, &proto_blob));
return proto_blob;
}
} // namespace
MountOptionsProto CreateMountOptionsProto(const std::string& path,
const std::string& workgroup,
const std::string& username) {
MountOptionsProto mount_options;
mount_options.set_path(path);
mount_options.set_workgroup(workgroup);
mount_options.set_username(username);
// Default to enable NTLM authentication.
std::unique_ptr<MountConfigProto> config =
CreateMountConfigProto(true /* enable_ntlm */);
mount_options.set_allocated_mount_config(config.release());
return mount_options;
}
MountOptionsProto CreateMountOptionsProto(const std::string& path,
const std::string& workgroup,
const std::string& username,
const MountConfig& mount_config) {
MountOptionsProto mount_options =
CreateMountOptionsProto(path, workgroup, username);
std::unique_ptr<MountConfigProto> config =
CreateMountConfigProto(mount_config.enable_ntlm);
mount_options.set_allocated_mount_config(config.release());
return mount_options;
}
UnmountOptionsProto CreateUnmountOptionsProto(int32_t mount_id) {
UnmountOptionsProto unmount_options;
unmount_options.set_mount_id(mount_id);
return unmount_options;
}
ReadDirectoryOptionsProto CreateReadDirectoryOptionsProto(
int32_t mount_id, const std::string& directory_path) {
ReadDirectoryOptionsProto read_directory_options;
read_directory_options.set_mount_id(mount_id);
read_directory_options.set_directory_path(directory_path);
return read_directory_options;
}
GetMetadataEntryOptionsProto CreateGetMetadataOptionsProto(
int32_t mount_id, const std::string& entry_path) {
GetMetadataEntryOptionsProto get_metadata_options;
get_metadata_options.set_mount_id(mount_id);
get_metadata_options.set_entry_path(entry_path);
return get_metadata_options;
}
OpenFileOptionsProto CreateOpenFileOptionsProto(int32_t mount_id,
const std::string& file_path,
bool writeable) {
OpenFileOptionsProto open_file_options;
open_file_options.set_mount_id(mount_id);
open_file_options.set_file_path(file_path);
open_file_options.set_writeable(writeable);
return open_file_options;
}
CloseFileOptionsProto CreateCloseFileOptionsProto(int32_t mount_id,
int32_t file_id) {
CloseFileOptionsProto close_file_options;
close_file_options.set_mount_id(mount_id);
close_file_options.set_file_id(file_id);
return close_file_options;
}
DeleteEntryOptionsProto CreateDeleteEntryOptionsProto(
int32_t mount_id, const std::string& entry_path, bool recursive) {
DeleteEntryOptionsProto delete_entry_options;
delete_entry_options.set_mount_id(mount_id);
delete_entry_options.set_entry_path(entry_path);
delete_entry_options.set_recursive(recursive);
return delete_entry_options;
}
ReadFileOptionsProto CreateReadFileOptionsProto(int32_t mount_id,
int32_t file_id,
int64_t offset,
int32_t length) {
ReadFileOptionsProto options;
options.set_mount_id(mount_id);
options.set_file_id(file_id);
options.set_offset(offset);
options.set_length(length);
return options;
}
CreateFileOptionsProto CreateCreateFileOptionsProto(
int32_t mount_id, const std::string& file_path) {
CreateFileOptionsProto options;
options.set_mount_id(mount_id);
options.set_file_path(file_path);
return options;
}
TruncateOptionsProto CreateTruncateOptionsProto(int32_t mount_id,
const std::string& file_path,
int64_t length) {
TruncateOptionsProto options;
options.set_mount_id(mount_id);
options.set_file_path(file_path);
options.set_length(length);
return options;
}
WriteFileOptionsProto CreateWriteFileOptionsProto(int32_t mount_id,
int32_t file_id,
int64_t offset,
int32_t length) {
WriteFileOptionsProto options;
options.set_mount_id(mount_id);
options.set_file_id(file_id);
options.set_offset(offset);
options.set_length(length);
return options;
}
CreateDirectoryOptionsProto CreateCreateDirectoryOptionsProto(
int32_t mount_id, const std::string& directory_path, bool recursive) {
CreateDirectoryOptionsProto options;
options.set_mount_id(mount_id);
options.set_directory_path(directory_path);
options.set_recursive(recursive);
return options;
}
MoveEntryOptionsProto CreateMoveEntryOptionsProto(
int32_t mount_id,
const std::string& source_path,
const std::string& target_path) {
MoveEntryOptionsProto options;
options.set_mount_id(mount_id);
options.set_source_path(source_path);
options.set_target_path(target_path);
return options;
}
CopyEntryOptionsProto CreateCopyEntryOptionsProto(
int32_t mount_id,
const std::string& source_path,
const std::string& target_path) {
CopyEntryOptionsProto options;
options.set_mount_id(mount_id);
options.set_source_path(source_path);
options.set_target_path(target_path);
return options;
}
GetDeleteListOptionsProto CreateGetDeleteListOptionsProto(
int32_t mount_id, const std::string& entry_path) {
GetDeleteListOptionsProto options;
options.set_mount_id(mount_id);
options.set_entry_path(entry_path);
return options;
}
GetSharesOptionsProto CreateGetSharesOptionsProto(
const std::string& server_url) {
GetSharesOptionsProto options;
options.set_server_url(server_url);
return options;
}
RemountOptionsProto CreateRemountOptionsProto(const std::string& path,
int32_t mount_id) {
RemountOptionsProto options;
options.set_path(path);
options.set_mount_id(mount_id);
return options;
}
RemountOptionsProto CreateRemountOptionsProto(const std::string& path,
int32_t mount_id,
const MountConfig& mount_config) {
RemountOptionsProto remount_options;
remount_options.set_path(path);
remount_options.set_mount_id(mount_id);
// set_allocated_mount_config() transfers ownership of |mount_config| to
// |mount_options| so |mount_config| needs to be created in the heap.
auto config = std::make_unique<MountConfigProto>();
config->set_enable_ntlm(mount_config.enable_ntlm);
remount_options.set_allocated_mount_config(config.release());
return remount_options;
}
authpolicy::KerberosFiles CreateKerberosFilesProto(
const std::string& krb5cc, const std::string& krb5conf) {
authpolicy::KerberosFiles kerberos_files;
kerberos_files.set_krb5cc(krb5cc);
kerberos_files.set_krb5conf(krb5conf);
return kerberos_files;
}
ProtoBlob CreateMountOptionsBlob(const std::string& path) {
return SerializeProtoToBlobAndCheck(
CreateMountOptionsProto(path, "" /* workgroup */, "" /* username */,
MountConfig(true /* enable_ntlm */)));
}
ProtoBlob CreateMountOptionsBlob(const std::string& path,
const MountConfig& mount_config) {
return SerializeProtoToBlobAndCheck(CreateMountOptionsProto(
path, "" /* workgroup */, "" /* username */, mount_config));
}
ProtoBlob CreateMountOptionsBlob(const std::string& path,
const std::string& workgroup,
const std::string& username,
const MountConfig mount_config) {
return SerializeProtoToBlobAndCheck(
CreateMountOptionsProto(path, workgroup, username, mount_config));
}
ProtoBlob CreateUnmountOptionsBlob(int32_t mount_id) {
return SerializeProtoToBlobAndCheck(CreateUnmountOptionsProto(mount_id));
}
ProtoBlob CreateReadDirectoryOptionsBlob(int32_t mount_id,
const std::string& directory_path) {
return SerializeProtoToBlobAndCheck(
CreateReadDirectoryOptionsProto(mount_id, directory_path));
}
ProtoBlob CreateGetMetadataOptionsBlob(int32_t mount_id,
const std::string& entry_path) {
ProtoBlob proto_blob;
return SerializeProtoToBlobAndCheck(
CreateGetMetadataOptionsProto(mount_id, entry_path));
}
ProtoBlob CreateOpenFileOptionsBlob(int32_t mount_id,
const std::string& file_path,
bool writeable) {
return SerializeProtoToBlobAndCheck(
CreateOpenFileOptionsProto(mount_id, file_path, writeable));
}
ProtoBlob CreateCloseFileOptionsBlob(int32_t mount_id, int32_t file_id) {
return SerializeProtoToBlobAndCheck(
CreateCloseFileOptionsProto(mount_id, file_id));
}
ProtoBlob CreateDeleteEntryOptionsBlob(int32_t mount_id,
const std::string& entry_path,
bool recursive) {
return SerializeProtoToBlobAndCheck(
CreateDeleteEntryOptionsProto(mount_id, entry_path, recursive));
}
ProtoBlob CreateReadFileOptionsBlob(int32_t mount_id,
int32_t file_id,
int64_t offset,
int32_t length) {
return SerializeProtoToBlobAndCheck(
CreateReadFileOptionsProto(mount_id, file_id, offset, length));
}
ProtoBlob CreateCreateFileOptionsBlob(int32_t mount_id,
const std::string& file_path) {
return SerializeProtoToBlobAndCheck(
CreateCreateFileOptionsProto(mount_id, file_path));
}
ProtoBlob CreateTruncateOptionsBlob(int32_t mount_id,
const std::string& file_path,
int64_t length) {
return SerializeProtoToBlobAndCheck(
CreateTruncateOptionsProto(mount_id, file_path, length));
}
ProtoBlob CreateWriteFileOptionsBlob(int32_t mount_id,
int32_t file_id,
int64_t offset,
int32_t length) {
return SerializeProtoToBlobAndCheck(
CreateWriteFileOptionsProto(mount_id, file_id, offset, length));
}
ProtoBlob CreateCreateDirectoryOptionsBlob(int32_t mount_id,
const std::string& directory_path,
bool recursive) {
return SerializeProtoToBlobAndCheck(
CreateCreateDirectoryOptionsProto(mount_id, directory_path, recursive));
}
ProtoBlob CreateMoveEntryOptionsBlob(int32_t mount_id,
const std::string& source_path,
const std::string& target_path) {
return SerializeProtoToBlobAndCheck(
CreateMoveEntryOptionsProto(mount_id, source_path, target_path));
}
ProtoBlob CreateCopyEntryOptionsBlob(int32_t mount_id,
const std::string& source_path,
const std::string& target_path) {
return SerializeProtoToBlobAndCheck(
CreateCopyEntryOptionsProto(mount_id, source_path, target_path));
}
ProtoBlob CreateGetDeleteListOptionsBlob(int32_t mount_id,
const std::string& entry_path) {
return SerializeProtoToBlobAndCheck(
CreateGetDeleteListOptionsProto(mount_id, entry_path));
}
ProtoBlob CreateGetSharesOptionsBlob(const std::string& server_url) {
return SerializeProtoToBlobAndCheck(CreateGetSharesOptionsProto(server_url));
}
ProtoBlob CreateRemountOptionsBlob(const std::string& path, int32_t mount_id) {
return CreateRemountOptionsBlob(path, mount_id,
MountConfig(true /* enable_ntlm */));
}
ProtoBlob CreateRemountOptionsBlob(const std::string& path,
int32_t mount_id,
MountConfig mount_config) {
return SerializeProtoToBlobAndCheck(
CreateRemountOptionsProto(path, mount_id, mount_config));
}
base::ScopedFD WritePasswordToFile(TempFileManager* temp_manager,
const std::string& password) {
const size_t password_size = password.size();
std::vector<uint8_t> password_data(sizeof(password_size) + password.size());
// Write the password length in the first sizeof(size_t) bytes of the buffer.
std::memcpy(password_data.data(), &password_size, sizeof(password_size));
// Append |password| starting at the end of password_size.
std::memcpy(password_data.data() + sizeof(password_size), password.c_str(),
password.size());
return temp_manager->CreateTempFile(password_data);
}
std::string CreateKrb5ConfPath(const base::FilePath& temp_dir) {
return temp_dir.Append(kTestKrb5ConfName).value();
}
std::string CreateKrb5CCachePath(const base::FilePath& temp_dir) {
return temp_dir.Append(kTestCCacheName).value();
}
void ExpectFileEqual(const std::string& path,
const std::string expected_contents) {
const base::FilePath file_path(path);
std::string actual_contents;
EXPECT_TRUE(ReadFileToString(file_path, &actual_contents));
EXPECT_EQ(expected_contents, actual_contents);
}
void ExpectFileNotEqual(const std::string& path,
const std::string expected_contents) {
const base::FilePath file_path(path);
std::string actual_contents;
EXPECT_TRUE(ReadFileToString(file_path, &actual_contents));
EXPECT_NE(expected_contents, actual_contents);
}
std::vector<uint8_t> CreateNetBiosResponsePacket(
const std::vector<std::vector<uint8_t>>& hostnames,
uint8_t name_length,
std::vector<uint8_t> name,
uint16_t transaction_id,
uint8_t response_type) {
// Build the prefix of the packet.
std::vector<uint8_t> packet = {0xAA, 0xAA, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// Set Transaction ID in Big Endian representation.
packet[0] = transaction_id >> 8;
packet[1] = transaction_id & 0xFF;
// Add the name section.
packet.push_back(name_length);
packet.insert(packet.end(), name.begin(), name.end());
// Add the next section
std::vector<uint8_t> middle_section = {0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00};
// Set the response_type.
middle_section[2] = response_type;
packet.insert(packet.end(), middle_section.begin(), middle_section.end());
// Set number of address list entries.
packet.push_back(hostnames.size());
// Add the address list entries.
for (const auto& hostname : hostnames) {
packet.insert(packet.end(), hostname.begin(), hostname.end());
}
return packet;
}
std::vector<uint8_t> CreateNetBiosResponsePacket(
const std::vector<std::vector<uint8_t>>& hostnames,
std::vector<uint8_t> name,
uint16_t transaction_id,
uint8_t response_type) {
return CreateNetBiosResponsePacket(hostnames, name.size(), name,
transaction_id, response_type);
}
std::vector<uint8_t> CreateValidNetBiosHostname(const std::string& hostname,
uint8_t type) {
DCHECK_LE(hostname.size(), netbios::kServerNameLength);
std::vector<uint8_t> hostname_bytes(netbios::kServerEntrySize);
std::copy(hostname.begin(), hostname.end(), hostname_bytes.begin());
// Fill the rest of the name with spaces.
std::fill(hostname_bytes.begin() + hostname.size(),
hostname_bytes.begin() + netbios::kServerNameLength, 0x20);
// Set the type.
hostname_bytes[15] = type;
// Set two nulls for the flags.
hostname_bytes[16] = 0x00;
hostname_bytes[17] = 0x00;
return hostname_bytes;
}
std::unique_ptr<MountConfigProto> CreateMountConfigProto(bool enable_ntlm) {
// set_allocated_mount_config() transfers ownership of |mount_config| to
// |mount_options| so |mount_config| needs to be created in the heap.
auto mount_config = std::make_unique<MountConfigProto>();
mount_config->set_enable_ntlm(enable_ntlm);
return mount_config;
}
} // namespace smbprovider
| 35.964286 | 80 | 0.687482 | [
"vector"
] |
ac1d8cd77737515ec2765ae433ffc026bb5e6bd5 | 17,812 | hpp | C++ | deps/boost/include/boost/numeric/ublas/tensor/functions.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 995 | 2018-06-22T10:39:18.000Z | 2022-03-25T01:22:14.000Z | deps/boost/include/boost/numeric/ublas/tensor/functions.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 32 | 2018-06-23T14:19:37.000Z | 2022-03-29T10:20:37.000Z | deps/boost/include/boost/numeric/ublas/tensor/functions.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 172 | 2018-06-22T11:12:00.000Z | 2022-03-29T07:44:33.000Z | //
// Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// The authors gratefully acknowledge the support of
// Fraunhofer IOSB, Ettlingen, Germany
//
#ifndef BOOST_UBLAS_TENSOR_FUNCTIONS_HPP
#define BOOST_UBLAS_TENSOR_FUNCTIONS_HPP
#include <stdexcept>
#include <vector>
#include <algorithm>
#include <numeric>
#include "multiplication.hpp"
#include "algorithms.hpp"
#include "expression.hpp"
#include "expression_evaluation.hpp"
#include "storage_traits.hpp"
namespace boost {
namespace numeric {
namespace ublas {
template<class Value, class Format, class Allocator>
class tensor;
template<class Value, class Format, class Allocator>
class matrix;
template<class Value, class Allocator>
class vector;
/** @brief Computes the m-mode tensor-times-vector product
*
* Implements C[i1,...,im-1,im+1,...,ip] = A[i1,i2,...,ip] * b[im]
*
* @note calls ublas::ttv
*
* @param[in] m contraction dimension with 1 <= m <= p
* @param[in] a tensor object A with order p
* @param[in] b vector object B
*
* @returns tensor object C with order p-1, the same storage format and allocator type as A
*/
template<class V, class F, class A1, class A2>
auto prod(tensor<V,F,A1> const& a, vector<V,A2> const& b, const std::size_t m)
{
using tensor_type = tensor<V,F,A1>;
using extents_type = typename tensor_type::extents_type;
using ebase_type = typename extents_type::base_type;
using value_type = typename tensor_type::value_type;
using size_type = typename extents_type::value_type;
auto const p = std::size_t(a.rank());
if( m == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttv): contraction mode must be greater than zero.");
if( p < m )
throw std::length_error("error in boost::numeric::ublas::prod(ttv): rank of tensor must be greater than or equal to the modus.");
if( p == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttv): rank of tensor must be greater than zero.");
if( a.empty() )
throw std::length_error("error in boost::numeric::ublas::prod(ttv): first argument tensor should not be empty.");
if( b.size() == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttv): second argument vector should not be empty.");
auto nc = ebase_type(std::max(p-1, size_type(2)) , size_type(1));
auto nb = ebase_type{b.size(),1};
for(auto i = 0u, j = 0u; i < p; ++i)
if(i != m-1)
nc[j++] = a.extents().at(i);
auto c = tensor_type(extents_type(nc),value_type{});
auto bb = &(b(0));
ttv(m, p,
c.data(), c.extents().data(), c.strides().data(),
a.data(), a.extents().data(), a.strides().data(),
bb, nb.data(), nb.data());
return c;
}
/** @brief Computes the m-mode tensor-times-matrix product
*
* Implements C[i1,...,im-1,j,im+1,...,ip] = A[i1,i2,...,ip] * B[j,im]
*
* @note calls ublas::ttm
*
* @param[in] a tensor object A with order p
* @param[in] b vector object B
* @param[in] m contraction dimension with 1 <= m <= p
*
* @returns tensor object C with order p, the same storage format and allocator type as A
*/
template<class V, class F, class A1, class A2>
auto prod(tensor<V,F,A1> const& a, matrix<V,F,A2> const& b, const std::size_t m)
{
using tensor_type = tensor<V,F,A1>;
using extents_type = typename tensor_type::extents_type;
using strides_type = typename tensor_type::strides_type;
using value_type = typename tensor_type::value_type;
auto const p = a.rank();
if( m == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttm): contraction mode must be greater than zero.");
if( p < m || m > a.extents().size())
throw std::length_error("error in boost::numeric::ublas::prod(ttm): rank of the tensor must be greater equal the modus.");
if( p == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttm): rank of the tensor must be greater than zero.");
if( a.empty() )
throw std::length_error("error in boost::numeric::ublas::prod(ttm): first argument tensor should not be empty.");
if( b.size1()*b.size2() == 0)
throw std::length_error("error in boost::numeric::ublas::prod(ttm): second argument matrix should not be empty.");
auto nc = a.extents().base();
auto nb = extents_type {b.size1(),b.size2()};
auto wb = strides_type (nb);
nc[m-1] = nb[0];
auto c = tensor_type(extents_type(nc),value_type{});
auto bb = &(b(0,0));
ttm(m, p,
c.data(), c.extents().data(), c.strides().data(),
a.data(), a.extents().data(), a.strides().data(),
bb, nb.data(), wb.data());
return c;
}
/** @brief Computes the q-mode tensor-times-tensor product
*
* Implements C[i1,...,ir,j1,...,js] = sum( A[i1,...,ir+q] * B[j1,...,js+q] )
*
* @note calls ublas::ttt
*
* na[phia[x]] = nb[phib[x]] for 1 <= x <= q
*
* @param[in] phia one-based permutation tuple of length q for the first input tensor a
* @param[in] phib one-based permutation tuple of length q for the second input tensor b
* @param[in] a left-hand side tensor with order r+q
* @param[in] b right-hand side tensor with order s+q
* @result tensor with order r+s
*/
template<class V, class F, class A1, class A2>
auto prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b,
std::vector<std::size_t> const& phia, std::vector<std::size_t> const& phib)
{
using tensor_type = tensor<V,F,A1>;
using extents_type = typename tensor_type::extents_type;
using value_type = typename tensor_type::value_type;
using size_type = typename extents_type::value_type;
auto const pa = a.rank();
auto const pb = b.rank();
auto const q = size_type(phia.size());
if(pa == 0ul)
throw std::runtime_error("error in ublas::prod: order of left-hand side tensor must be greater than 0.");
if(pb == 0ul)
throw std::runtime_error("error in ublas::prod: order of right-hand side tensor must be greater than 0.");
if(pa < q)
throw std::runtime_error("error in ublas::prod: number of contraction dimensions cannot be greater than the order of the left-hand side tensor.");
if(pb < q)
throw std::runtime_error("error in ublas::prod: number of contraction dimensions cannot be greater than the order of the right-hand side tensor.");
if(q != phib.size())
throw std::runtime_error("error in ublas::prod: permutation tuples must have the same length.");
if(pa < phia.size())
throw std::runtime_error("error in ublas::prod: permutation tuple for the left-hand side tensor cannot be greater than the corresponding order.");
if(pb < phib.size())
throw std::runtime_error("error in ublas::prod: permutation tuple for the right-hand side tensor cannot be greater than the corresponding order.");
auto const& na = a.extents();
auto const& nb = b.extents();
for(auto i = 0ul; i < q; ++i)
if( na.at(phia.at(i)-1) != nb.at(phib.at(i)-1))
throw std::runtime_error("error in ublas::prod: permutations of the extents are not correct.");
auto const r = pa - q;
auto const s = pb - q;
std::vector<std::size_t> phia1(pa), phib1(pb);
std::iota(phia1.begin(), phia1.end(), 1ul);
std::iota(phib1.begin(), phib1.end(), 1ul);
std::vector<std::size_t> nc( std::max ( r+s , size_type(2) ), size_type(1) );
for(auto i = 0ul; i < phia.size(); ++i)
* std::remove(phia1.begin(), phia1.end(), phia.at(i)) = phia.at(i);
//phia1.erase( std::remove(phia1.begin(), phia1.end(), phia.at(i)), phia1.end() ) ;
assert(phia1.size() == pa);
for(auto i = 0ul; i < r; ++i)
nc[ i ] = na[ phia1[ i ] - 1 ];
for(auto i = 0ul; i < phib.size(); ++i)
* std::remove(phib1.begin(), phib1.end(), phib.at(i)) = phib.at(i) ;
//phib1.erase( std::remove(phib1.begin(), phib1.end(), phia.at(i)), phib1.end() ) ;
assert(phib1.size() == pb);
for(auto i = 0ul; i < s; ++i)
nc[ r + i ] = nb[ phib1[ i ] - 1 ];
// std::copy( phib.begin(), phib.end(), phib1.end() );
assert( phia1.size() == pa );
assert( phib1.size() == pb );
auto c = tensor_type(extents_type(nc), value_type{});
ttt(pa, pb, q,
phia1.data(), phib1.data(),
c.data(), c.extents().data(), c.strides().data(),
a.data(), a.extents().data(), a.strides().data(),
b.data(), b.extents().data(), b.strides().data());
return c;
}
//template<class V, class F, class A1, class A2, std::size_t N, std::size_t M>
//auto operator*( tensor_index<V,F,A1,N> const& lhs, tensor_index<V,F,A2,M> const& rhs)
/** @brief Computes the q-mode tensor-times-tensor product
*
* Implements C[i1,...,ir,j1,...,js] = sum( A[i1,...,ir+q] * B[j1,...,js+q] )
*
* @note calls ublas::ttt
*
* na[phi[x]] = nb[phi[x]] for 1 <= x <= q
*
* @param[in] phi one-based permutation tuple of length q for bot input tensors
* @param[in] a left-hand side tensor with order r+q
* @param[in] b right-hand side tensor with order s+q
* @result tensor with order r+s
*/
template<class V, class F, class A1, class A2>
auto prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b,
std::vector<std::size_t> const& phi)
{
return prod(a, b, phi, phi);
}
/** @brief Computes the inner product of two tensors
*
* Implements c = sum(A[i1,i2,...,ip] * B[i1,i2,...,jp])
*
* @note calls inner function
*
* @param[in] a tensor object A
* @param[in] b tensor object B
*
* @returns a value type.
*/
template<class V, class F, class A1, class A2>
auto inner_prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b)
{
using value_type = typename tensor<V,F,A1>::value_type;
if( a.rank() != b.rank() )
throw std::length_error("error in boost::numeric::ublas::inner_prod: Rank of both tensors must be the same.");
if( a.empty() || b.empty())
throw std::length_error("error in boost::numeric::ublas::inner_prod: Tensors should not be empty.");
if( a.extents() != b.extents())
throw std::length_error("error in boost::numeric::ublas::inner_prod: Tensor extents should be the same.");
return inner(a.rank(), a.extents().data(),
a.data(), a.strides().data(),
b.data(), b.strides().data(), value_type{0});
}
/** @brief Computes the outer product of two tensors
*
* Implements C[i1,...,ip,j1,...,jq] = A[i1,i2,...,ip] * B[j1,j2,...,jq]
*
* @note calls outer function
*
* @param[in] a tensor object A
* @param[in] b tensor object B
*
* @returns tensor object C with the same storage format F and allocator type A1
*/
template<class V, class F, class A1, class A2>
auto outer_prod(tensor<V,F,A1> const& a, tensor<V,F,A2> const& b)
{
using tensor_type = tensor<V,F,A1>;
using extents_type = typename tensor_type::extents_type;
if( a.empty() || b.empty() )
throw std::runtime_error("error in boost::numeric::ublas::outer_prod: tensors should not be empty.");
auto nc = typename extents_type::base_type(a.rank() + b.rank());
for(auto i = 0u; i < a.rank(); ++i)
nc.at(i) = a.extents().at(i);
for(auto i = 0u; i < b.rank(); ++i)
nc.at(a.rank()+i) = b.extents().at(i);
auto c = tensor_type(extents_type(nc));
outer(c.data(), c.rank(), c.extents().data(), c.strides().data(),
a.data(), a.rank(), a.extents().data(), a.strides().data(),
b.data(), b.rank(), b.extents().data(), b.strides().data());
return c;
}
/** @brief Transposes a tensor according to a permutation tuple
*
* Implements C[tau[i1],tau[i2]...,tau[ip]] = A[i1,i2,...,ip]
*
* @note calls trans function
*
* @param[in] a tensor object of rank p
* @param[in] tau one-based permutation tuple of length p
* @returns a transposed tensor object with the same storage format F and allocator type A
*/
template<class V, class F, class A>
auto trans(tensor<V,F,A> const& a, std::vector<std::size_t> const& tau)
{
using tensor_type = tensor<V,F,A>;
using extents_type = typename tensor_type::extents_type;
// using strides_type = typename tensor_type::strides_type;
if( a.empty() )
return tensor<V,F,A>{};
auto const p = a.rank();
auto const& na = a.extents();
auto nc = typename extents_type::base_type (p);
for(auto i = 0u; i < p; ++i)
nc.at(tau.at(i)-1) = na.at(i);
// auto wc = strides_type(extents_type(nc));
auto c = tensor_type(extents_type(nc));
trans( a.rank(), a.extents().data(), tau.data(),
c.data(), c.strides().data(),
a.data(), a.strides().data());
// auto wc_pi = typename strides_type::base_type (p);
// for(auto i = 0u; i < p; ++i)
// wc_pi.at(tau.at(i)-1) = c.strides().at(i);
//copy(a.rank(),
// a.extents().data(),
// c.data(), wc_pi.data(),
// a.data(), a.strides().data() );
return c;
}
/** @brief Computes the frobenius norm of a tensor expression
*
* @note evaluates the tensor expression and calls the accumulate function
*
*
* Implements the two-norm with
* k = sqrt( sum_(i1,...,ip) A(i1,...,ip)^2 )
*
* @param[in] a tensor object of rank p
* @returns the frobenius norm of the tensor
*/
//template<class V, class F, class A>
//auto norm(tensor<V,F,A> const& a)
template<class T, class D>
auto norm(detail::tensor_expression<T,D> const& expr)
{
using tensor_type = typename detail::tensor_expression<T,D>::tensor_type;
using value_type = typename tensor_type::value_type;
auto a = tensor_type( expr );
if( a.empty() )
throw std::runtime_error("error in boost::numeric::ublas::norm: tensors should not be empty.");
return std::sqrt( accumulate( a.order(), a.extents().data(), a.data(), a.strides().data(), value_type{},
[](auto const& l, auto const& r){ return l + r*r; } ) ) ;
}
/** @brief Extract the real component of tensor elements within a tensor expression
*
* @param[in] lhs tensor expression
* @returns unary tensor expression
*/
template<class T, class D>
auto real(detail::tensor_expression<T,D> const& expr) {
return detail::make_unary_tensor_expression<T> (expr(), [] (auto const& l) { return std::real( l ); } );
}
/** @brief Extract the real component of tensor elements within a tensor expression
*
* @param[in] lhs tensor expression
* @returns unary tensor expression
*/
template<class V, class F, class A, class D>
auto real(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
{
using tensor_complex_type = tensor<std::complex<V>,F,A>;
using tensor_type = tensor<V,F,typename storage_traits<A>::template rebind<V>>;
if( detail::retrieve_extents( expr ).empty() )
throw std::runtime_error("error in boost::numeric::ublas::real: tensors should not be empty.");
auto a = tensor_complex_type( expr );
auto c = tensor_type( a.extents() );
std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::real(l) ; } );
return c;
}
/** @brief Extract the imaginary component of tensor elements within a tensor expression
*
* @param[in] lhs tensor expression
* @returns unary tensor expression
*/
template<class T, class D>
auto imag(detail::tensor_expression<T,D> const& lhs) {
return detail::make_unary_tensor_expression<T> (lhs(), [] (auto const& l) { return std::imag( l ); } );
}
/** @brief Extract the imag component of tensor elements within a tensor expression
*
* @param[in] lhs tensor expression
* @returns unary tensor expression
*/
template<class V, class A, class F, class D>
auto imag(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
{
using tensor_complex_type = tensor<std::complex<V>,F,A>;
using tensor_type = tensor<V,F,typename storage_traits<A>::template rebind<V>>;
if( detail::retrieve_extents( expr ).empty() )
throw std::runtime_error("error in boost::numeric::ublas::real: tensors should not be empty.");
auto a = tensor_complex_type( expr );
auto c = tensor_type( a.extents() );
std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::imag(l) ; } );
return c;
}
/** @brief Computes the complex conjugate component of tensor elements within a tensor expression
*
* @param[in] expr tensor expression
* @returns complex tensor
*/
template<class T, class D>
auto conj(detail::tensor_expression<T,D> const& expr)
{
using tensor_type = T;
using value_type = typename tensor_type::value_type;
using layout_type = typename tensor_type::layout_type;
using array_type = typename tensor_type::array_type;
using new_value_type = std::complex<value_type>;
using new_array_type = typename storage_traits<array_type>::template rebind<new_value_type>;
using tensor_complex_type = tensor<new_value_type,layout_type, new_array_type>;
if( detail::retrieve_extents( expr ).empty() )
throw std::runtime_error("error in boost::numeric::ublas::conj: tensors should not be empty.");
auto a = tensor_type( expr );
auto c = tensor_complex_type( a.extents() );
std::transform( a.begin(), a.end(), c.begin(), [](auto const& l){ return std::conj(l) ; } );
return c;
}
/** @brief Computes the complex conjugate component of tensor elements within a tensor expression
*
* @param[in] lhs tensor expression
* @returns unary tensor expression
*/
template<class V, class A, class F, class D>
auto conj(detail::tensor_expression<tensor<std::complex<V>,F,A>,D> const& expr)
{
return detail::make_unary_tensor_expression<tensor<std::complex<V>,F,A>> (expr(), [] (auto const& l) { return std::conj( l ); } );
}
}
}
}
#endif
| 31.864043 | 150 | 0.641029 | [
"object",
"vector",
"transform"
] |
ac29ae1e8d5e05704e433a550b7b809c27b34747 | 49,340 | cc | C++ | src/core/device/swap_cuda_gpu.cc | lijiansong/singa | 352cfc910deff0d6a8383c5e97f45795c67cb206 | [
"Apache-2.0"
] | null | null | null | src/core/device/swap_cuda_gpu.cc | lijiansong/singa | 352cfc910deff0d6a8383c5e97f45795c67cb206 | [
"Apache-2.0"
] | null | null | null | src/core/device/swap_cuda_gpu.cc | lijiansong/singa | 352cfc910deff0d6a8383c5e97f45795c67cb206 | [
"Apache-2.0"
] | null | null | null | /**
* Cuda gpu device with variable swap in / out supporting.
*/
#include "singa/singa_config.h"
#ifdef USE_CUDA
#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand.h>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
#include "singa/core/device.h"
#include "singa/utils/cuda_utils.h"
namespace singa {
const cudaMemcpyKind copyKind[] = {cudaMemcpyHostToHost, cudaMemcpyHostToDevice,
cudaMemcpyDeviceToHost,
cudaMemcpyDeviceToDevice};
// ===========================================================================
// Helper Utilities.
/// Sort DeviceOptInfo by ptr and then idx.
struct sort_by_ptr_idx_ascending {
inline bool operator()(const DeviceOptInfo& info1,
const DeviceOptInfo& info2) {
return ((info1.ptr < info2.ptr) ||
((info1.ptr == info2.ptr) && (info1.idx < info2.idx)));
}
};
/// Sort DeviceOptInfo by idx.
struct sort_by_idx_ascending {
inline bool operator()(const DeviceOptInfo& info1,
const DeviceOptInfo& info2) {
return (info1.idx < info2.idx);
}
};
/// SwapCudaGPU device info: DeviceOptInfo is defined in
/// include/singa/core/device.h.
/// Format of DeviceOptInfo [ptr, size/-1, mem_op_type, idx, time_stamp].
/// Simplified device info: [idx, mem_op_type, size_delta].
struct DeviceOptSimplifiedInfo {
// If mem_op_type is Malloc, size_delta is size, else delta to the last index.
size_t size_delta;
int mem_op_type;
int idx;
DeviceOptSimplifiedInfo(size_t size, int opt, int i)
: size_delta(size), mem_op_type(opt), idx(i) {}
};
/// Sort DeviceOptSimplifiedInfo by idx.
struct sort_by_DeviceOptSimplifiedInfo_idx_ascending {
inline bool operator()(const DeviceOptSimplifiedInfo& info1,
const DeviceOptSimplifiedInfo& info2) {
return (info1.idx < info2.idx);
}
};
/// Sort SwapBlock by DOA_origin, descending.
struct sort_by_DOA_origin_descending {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.DOA_origin > blk2.DOA_origin);
}
};
/// Sort SwapBlock by weighted DOA_origin, descending.
struct sort_by_WDOA_descending {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.WDOA > blk2.WDOA);
}
};
/// Sort SwapBlock by AOA, descending.
struct sort_by_AOA_descending {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.AOA > blk2.AOA);
}
};
/// Sort DeviceOptInfo_Swap by idx.
struct sort_by_idx_ascending_swap {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.r_idx < blk2.r_idx);
}
};
/// Sort DeviceOptInfo_Swap by idx. reverse.
struct sort_by_idx_descending_swap {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.d_idx > blk2.d_idx);
}
};
/// Sort majority voting, ascending.
struct sort_by_majority_voting_ascending {
inline bool operator()(const SwapBlock& blk1, const SwapBlock& blk2) {
return (blk1.majority_voting < blk2.majority_voting);
}
};
/// String delimiter.
/// Example: given input str: "Malloc 1000 Free 500", delimiter: " ",
/// return ["Malloc", "1000", "Free", "500"].
std::vector<std::string> SplitOptString(std::string str,
std::string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
std::string token;
std::vector<std::string> res;
while ((pos_end = str.find(delimiter, pos_start)) != std::string::npos) {
token = str.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back(token);
}
res.push_back(str.substr(pos_start));
return res;
}
/// TODO: Wrap these utility functions into common.h.
/// Convert vector of string into vector of DeviceOptInfo, sorted by ptr
/// and then idx, and update idx_range to pieceMsgVec size.
/// Format of DeviceOptInfo: [ptr, size/-1, flag, idx, time_stamp], where
/// flag values: <1, Malloc>; <-1, Free>; <2, Read>; <3, Layer>; <4, Mutable>.
std::vector<DeviceOptInfo> DeviceOptSeqStrToStruct(std::vector<std::string> vec,
int& idx_range) {
std::vector<DeviceOptInfo> vec_opt_info;
for (int i = 0; i < vec.size(); i++) {
std::vector<std::string> v = SplitOptString(vec[i], " ");
int op_type;
if (v[0] == "Malloc") {
op_type = 1;
} else if (v[0] == "Free") {
op_type = -1;
} else if (v[0] == "Read") {
op_type = 2;
} else if (v[0] == "Layer") {
op_type = 3;
} else if (v[0] == "Mutable") {
op_type = 4;
}
size_t result;
std::stringstream cvt(v[2]);
if (!(cvt >> result)) {
result = -1;
std::cout << "ERROR for convert size from str to int." << std::endl;
}
// ptr, size, mem_op_type, idx.
DeviceOptInfo item(v[1], result, op_type, i);
double tmp_time;
std::stringstream cvt2(v[3]);
cvt2 >> tmp_time;
item.time_stamp = tmp_time;
vec_opt_info.push_back(item);
}
std::sort(vec_opt_info.begin(), vec_opt_info.end(),
sort_by_ptr_idx_ascending());
idx_range = static_cast<int>(vec_opt_info.size());
return vec_opt_info;
}
/// Pre-process device operation sequence struct info for repeatable test,
/// return a vector of int for fast detection.
std::vector<size_t> DeviceOptSeqRepeatableTestPreProcess(
std::vector<DeviceOptInfo> vec_opt_info) {
// For DeviceOptSimplifiedInfo, if mem_op_type is Malloc, size_delta is
// size, else delta to last index.
std::vector<DeviceOptSimplifiedInfo> vec_opt_simplified_info;
std::string tmp_str;
int tmp_idx = 0;
for (int i = 0; i < vec_opt_info.size(); i++) {
if (vec_opt_info[i].mem_op_type == 1) {
// Update tmp_str and idx.
tmp_str = vec_opt_info[i].ptr;
tmp_idx = vec_opt_info[i].idx;
DeviceOptSimplifiedInfo item(vec_opt_info[i].size, 1,
vec_opt_info[i].idx);
vec_opt_simplified_info.push_back(item);
} else {
DeviceOptSimplifiedInfo item(vec_opt_info[i].idx - tmp_idx,
vec_opt_info[i].mem_op_type,
vec_opt_info[i].idx);
tmp_idx = vec_opt_info[i].idx;
vec_opt_simplified_info.push_back(item);
}
}
std::sort(vec_opt_simplified_info.begin(), vec_opt_simplified_info.end(),
sort_by_DeviceOptSimplifiedInfo_idx_ascending());
// Only after sort then can create vec_rep.
// Vector of size_delta.
std::vector<size_t> vec_rep;
for (int i = 0; i < vec_opt_simplified_info.size(); i++) {
vec_rep.push_back(vec_opt_simplified_info[i].size_delta);
}
return vec_rep;
}
/// Repeatable test, input vector of int,
/// in-place update max_legth (length of iteration)
/// and location_of_2nd_iteration (where 2nd iteration starts).
void RepeatableTest(std::vector<size_t> rep, int& iteration_length,
int& location_of_2nd_iteration,
int iteration_length_threshold, int global_index) {
int idx_range = (int)rep.size();
int threshold = iteration_length_threshold;
std::vector<std::pair<int, int>> iteration_length_location_of_2nd_iteration;
for (int i = 0; i < idx_range; i++) {
if (iteration_length > threshold) {
break;
}
for (int len = 1; len < (idx_range - i); len++) {
if (iteration_length > threshold) {
break;
}
if ((std::equal(rep.begin() + i, rep.begin() + i - 1 + len,
rep.begin() + i + len)) &&
(iteration_length < len)) {
iteration_length = len;
location_of_2nd_iteration = i;
iteration_length_location_of_2nd_iteration.push_back(
std::make_pair(iteration_length, location_of_2nd_iteration));
}
}
}
}
/// Linux PCIe: <https://www.cnblogs.com/lsgxeva/p/9542975.html>
/// Host motherboard: MAXIMUS VI EXTREME.
///
/// Measured by cuda-samples/1_Utilities/bandwidthTest
/// Device 0: TITAN Xp COLLECTORS EDITION
///
/// Host to Device Bandwidth, 1 Device(s)
/// PINNED Memory Transfers
/// Transfer Size (Bytes) Bandwidth(GB/s)
/// 32000000 6.3
///
/// Device to Host Bandwidth, 1 Device(s)
/// PINNED Memory Transfers
/// Transfer Size (Bytes) Bandwidth(GB/s)
/// 32000000 6.4
///
/// Device to Device Bandwidth, 1 Device(s)
/// PINNED Memory Transfers
/// Transfer Size (Bytes) Bandwidth(GB/s)
/// 32000000 422.7
///
/// TODO: How to measure swap in / out time?
/// Pinned PCIe bus and gpu memory bandwidth and get the linear function?
/// 20 round result:
/// ===---------------- swap in ----------------===
/// k: [[0.15742704]]
/// b: [[12352.18468599]]
/// f(1): [[12352.34211303]]
/// ===---------------- swap out ----------------===
/// k: [[0.156329]]
/// b: [[8242.79951244]]
/// f(1): [[8242.95584144]]
int SwapOutTime(size_t size) {
int ans = 0;
if (size == 0) {
ans = 8242;
} else {
ans = 0.1563 * size + 8242;
}
return ans;
}
int SwapInTime(size_t size) {
int ans = 0;
if (size == 0) {
ans = 12352;
} else {
ans = 0.1574 * size + 12352;
}
return ans;
}
/// Get operation index (range) that above the load limit.
/// Input: vec_load, mem_limit, range [start_idx, end_idx),
/// return range overlimit [first_over_limit, first_below_limit).
std::pair<int, int> GetOptIdxAboveLoadLimit(std::vector<double> vec_load,
size_t mem_limit, int start_idx,
int end_idx, int iteration_length) {
int first_over_limit = start_idx;
int first_below_limit = end_idx;
for (int i = start_idx + iteration_length; i < end_idx + iteration_length;
i++) {
if (vec_load[i] > mem_limit) {
first_over_limit = i - iteration_length;
break;
}
}
for (int i = end_idx + iteration_length;
i > first_over_limit + iteration_length; i--) {
if (vec_load[i] > mem_limit) {
first_below_limit = i - 1 - iteration_length;
break;
}
}
if (first_over_limit == start_idx) first_over_limit = -1;
if (first_below_limit == end_idx) first_below_limit = -1;
return std::make_pair(first_over_limit, first_below_limit);
}
/// Return memory load value and index of load peak.
std::pair<double, int> GetLoadPeak(std::vector<double> vec_load_test,
int iteration_length) {
double max_load_test = 0;
int max_idx_test = 0;
for (int i = iteration_length; i < iteration_length * 2; i++) {
if (max_load_test < vec_load_test[i]) {
max_load_test = vec_load_test[i];
max_idx_test = i - iteration_length;
}
}
return std::make_pair(max_load_test, max_idx_test);
}
/// Update load [start_idx, end_idx) by plus_minus*size.
/// Here plus_minus maybe -1.
void UpdateLoad(std::vector<double>& vec_load, int start_idx, int end_idx,
int plus_minus, size_t size, int iteration_length) {
for (int i = start_idx + iteration_length; i < end_idx + iteration_length;
i++) {
vec_load[i] = vec_load[i] + static_cast<double>(size) * plus_minus;
}
}
/// Select swapping blocks based on a cetain priority score or BO score with
/// load updated. After get the score info, we can select block one by one till
/// updated peak load is no larger than limit.
/// Return the candidate swapping memory blocks.
std::vector<SwapBlock> SwapCudaGPU::SelectBlock(std::vector<SwapBlock> vec_swap,
std::vector<double> tmp_load,
double mem_limit,
std::string mode) {
std::vector<SwapBlock> vec_swap_select;
if (mode == "DOA_origin") {
std::sort(vec_swap.begin(), vec_swap.end(),
sort_by_DOA_origin_descending());
}
if (mode == "AOA") {
std::sort(vec_swap.begin(), vec_swap.end(), sort_by_AOA_descending());
}
if (mode == "WDOA") {
for (int i = 0; i < vec_swap.size(); i++) {
auto item = vec_swap[i];
for (int j = item.r_idx; j < item.d_idx; j++) {
item.WDOA += origin_load[i + iteration_length] - mem_limit;
}
}
std::sort(vec_swap.begin(), vec_swap.end(), sort_by_WDOA_descending());
}
if (mode == "majority_voting") {
// Add order for DOA.
std::sort(vec_swap.begin(), vec_swap.end(),
sort_by_DOA_origin_descending());
for (int i = 0; i < vec_swap.size(); i++) {
vec_swap[i].majority_voting += i;
}
// Add order for AOA.
std::sort(vec_swap.begin(), vec_swap.end(), sort_by_AOA_descending());
for (int i = 0; i < vec_swap.size(); i++) {
vec_swap[i].majority_voting += i;
}
// Add order for WDOA.
for (int i = 0; i < vec_swap.size(); i++) {
auto item = vec_swap[i];
for (int j = item.r_idx; j < item.d_idx; j++) {
item.WDOA += origin_load[i + iteration_length] - mem_limit;
}
}
std::sort(vec_swap.begin(), vec_swap.end(), sort_by_WDOA_descending());
for (int i = 0; i < vec_swap.size(); i++) {
vec_swap[i].majority_voting += i;
}
std::sort(vec_swap.begin(), vec_swap.end(),
sort_by_majority_voting_ascending());
}
// Select block one by one till updated peak load is no larger than limit.
for (int i = 0; i < vec_swap.size(); i++) {
UpdateLoad(tmp_load, vec_swap[i].r_idx_ready, vec_swap[i].d_idx, -1,
vec_swap[i].size, iteration_length);
vec_swap_select.push_back(vec_swap[i]);
auto tmp_over_limit_ = GetOptIdxAboveLoadLimit(
tmp_load, mem_limit, 0, iteration_length, iteration_length);
auto max_current = GetLoadPeak(tmp_load, iteration_length);
auto newmax_load = max_current.first;
if (newmax_load < mem_limit) {
break;
}
}
return vec_swap_select;
}
/// Get ideal load, which is equivalent to load by synchronous swapping.
std::vector<double> SwapCudaGPU::GetIdealLoad(
std::vector<double> vec_load, std::vector<SwapBlock> vec_swap_select) {
auto vec_load_return = vec_load;
for (int i = 0; i < vec_swap_select.size(); i++) {
int auto_buffer = 0;
auto item = vec_swap_select[i];
if (item.cat == "A2") auto_buffer = data_buffer;
if (item.cat == "A3") auto_buffer = mutable_data_buffer;
UpdateLoad(vec_load_return, item.r_idx + auto_buffer, item.d_idx, -1,
item.size, iteration_length);
}
return vec_load_return;
}
/// Swap scheduling algorothm.
/// vec_swap_select contains the swapping blocks.
/// Update idx_out_end, idx_in_start,
/// compute overhead time.
/// Two mode selection: stick-to-limit or no-overhead.
void SwapCudaGPU::Scheduling(std::vector<SwapBlock>& vec_swap_select,
std::vector<double>& vec_load_tmp,
double& overhead, double mem_limit,
std::string mode) {
overhead = 0;
/// Stick to memory load limit mode.
if (mode == "stick-to-limit") {
std::sort(vec_swap_select.begin(), vec_swap_select.end(),
sort_by_idx_ascending_swap());
for (int i = 0; i < vec_swap_select.size(); i++) {
auto item = vec_swap_select[i];
int ready_idx = item.r_idx_ready;
if (i > 0) {
ready_idx = std::max(ready_idx, vec_swap_select[i - 1].idx_out_end);
}
item.idx_out_start = ready_idx;
item.t_out_start = vec_run[ready_idx + iteration_length].time_stamp;
item.t_out_end = item.t_out_start + SwapOutTime(item.size);
total_swap_out_time += SwapOutTime(item.size);
while (item.t_out_end >
vec_run[ready_idx + iteration_length].time_stamp) {
// Here ready means when able to finish the swap-out, with or without
// overhead.
ready_idx++;
}
// Get min compare with max_idx and ready_idx.
ready_idx = std::min(max_idx, ready_idx);
UpdateLoad(vec_load_tmp, ready_idx + 1, item.d_idx, -1, item.size,
iteration_length);
// tmp_over_limit_ is the operation index range that above the load limit.
auto tmp_over_limit_ = GetOptIdxAboveLoadLimit(
vec_load_tmp, mem_limit, 0, iteration_length, iteration_length);
if ((tmp_over_limit_.first != -1) &&
(tmp_over_limit_.first <= ready_idx)) {
UpdateLoad(vec_load_tmp, tmp_over_limit_.first - 1, ready_idx + 1, -1,
item.size, iteration_length);
ready_idx = tmp_over_limit_.first - 1;
overhead +=
(item.t_out_end - vec_run[ready_idx + iteration_length].time_stamp);
}
item.idx_out_end = ready_idx;
vec_swap_select[i] = item;
}
std::sort(vec_swap_select.begin(), vec_swap_select.end(),
sort_by_idx_descending_swap());
for (int i = 0; i < vec_swap_select.size(); i++) {
auto item = vec_swap_select[i];
int need_idx = item.d_idx;
if (i > 0) {
need_idx = std::min(need_idx, vec_swap_select[i - 1].idx_in_start);
}
item.idx_in_end = need_idx;
double prepare_time = vec_run[need_idx + iteration_length].time_stamp -
SwapInTime(item.size);
total_swap_in_time += SwapInTime(item.size);
while (prepare_time < vec_run[need_idx + iteration_length].time_stamp) {
need_idx--;
}
need_idx = std::max(need_idx, max_idx + 1);
item.idx_in_start = need_idx;
item.t_in_start = prepare_time;
UpdateLoad(vec_load_tmp, item.idx_in_start, item.d_idx, 1, item.size,
iteration_length);
auto tmp_over_limit_3 = GetOptIdxAboveLoadLimit(
vec_load_tmp, mem_limit, 0, iteration_length, iteration_length);
if ((tmp_over_limit_3.second != -1) &&
(vec_run[tmp_over_limit_3.second + iteration_length].time_stamp >
item.t_in_start)) {
overhead +=
(vec_run[tmp_over_limit_3.second + iteration_length].time_stamp -
item.t_in_start);
UpdateLoad(vec_load_tmp, item.idx_in_start, tmp_over_limit_3.second + 1,
-1, item.size, iteration_length);
item.idx_in_start = tmp_over_limit_3.second + 1;
auto tmp_over_limit_4 = GetOptIdxAboveLoadLimit(
vec_load_tmp, mem_limit, 0, iteration_length, iteration_length);
}
vec_swap_select[i] = item;
}
}
/// Zero-overhead mode.
if (mode == "no-overhead") {
// Update idx_out_end.
// Sort by r_idx for idx_out_end updating.
std::sort(vec_swap_select.begin(), vec_swap_select.end(),
sort_by_idx_ascending_swap());
for (int i = 0; i < vec_swap_select.size(); i++) {
auto item = vec_swap_select[i];
int ready_idx = 0;
if (item.cat == "A1") {
ready_idx = item.r_idx;
}
if (item.cat == "A2") {
ready_idx = item.r_idx + data_buffer;
}
if (item.cat == "A3") {
ready_idx = item.r_idx + mutable_data_buffer;
}
if (i > 0) {
ready_idx = std::max(ready_idx, vec_swap_select[i - 1].idx_out_end);
}
item.idx_out_start = ready_idx;
item.t_out_start = vec_run[ready_idx].time_stamp;
item.t_out_end = item.t_out_start + SwapOutTime(item.size);
while (item.t_out_end > vec_run[ready_idx].time_stamp) {
ready_idx++;
}
item.idx_out_end = ready_idx;
vec_swap_select[i] = item;
}
// Update idx_in_start.
std::sort(vec_swap_select.begin(), vec_swap_select.end(),
sort_by_idx_descending_swap());
for (int i = 0; i < vec_swap_select.size(); i++) {
auto item = vec_swap_select[i];
int need_idx = item.d_idx;
if (i > 0) {
need_idx = std::min(need_idx, vec_swap_select[i - 1].idx_in_start);
}
item.idx_in_end = need_idx;
double prepare_time =
vec_run[need_idx].time_stamp - SwapInTime(item.size);
while (prepare_time < vec_run[need_idx].time_stamp) {
--need_idx;
}
item.idx_in_start = need_idx;
item.t_in_start = prepare_time;
vec_swap_select[i] = item;
UpdateLoad(vec_load_tmp, item.idx_out_end, item.idx_in_start + 1, -1,
item.size, iteration_length);
}
}
}
/// Construct table_sched and table_meta.
void SwapCudaGPU::BuildMetaTables(std::vector<SwapBlock> vec_swap_select) {
cudaStream_t cu_strm1;
cudaStream_t cu_strm2;
std::sort(vec_swap_select.begin(), vec_swap_select.end(),
sort_by_idx_ascending_swap());
// For each swap select, make table_sched and table_meta.
// table_sched value is <swap_idx, swap_dir, sync_idx, sync_dir>
// for (int i = static_cast<int>(vec_swap_select.size() - 1); i>=0; i--) {
for (int i = 0; i < vec_swap_select.size(); i++) {
auto item = vec_swap_select[i];
if (table_sched.find(item.idx_out_start) == table_sched.end()) {
// swap_dir 0 is swap-out.
table_sched[item.idx_out_start] = std::make_tuple(item.r_idx, 0, -1, -1);
} else {
std::get<0>(table_sched.find(item.idx_out_start)->second) = item.r_idx;
std::get<1>(table_sched.find(item.idx_out_start)->second) = 0;
}
// idx_in_start swap.
if (table_sched.find(item.idx_in_start) == table_sched.end()) {
// swap_dir 1 is swap-in.
table_sched[item.idx_in_start] = std::make_tuple(item.r_idx, 1, -1, -1);
} else {
std::get<0>(table_sched.find(item.idx_in_start)->second) = item.r_idx;
std::get<1>(table_sched.find(item.idx_in_start)->second) = 1;
}
// idx_out_end sync.
if (table_sched.find(item.idx_out_end) == table_sched.end()) {
table_sched[item.idx_out_end] = std::make_tuple(-1, -1, item.r_idx, 0);
} else {
// Update sync_dir. 0 is sync swap-out.
std::get<2>(table_sched.find(item.idx_out_end)->second) = item.r_idx;
std::get<3>(table_sched.find(item.idx_out_end)->second) = 0;
}
// i2 sync
if (table_sched.find(item.idx_in_end) == table_sched.end()) {
table_sched[item.idx_in_end] = std::make_tuple(-1, -1, item.r_idx, 1);
} else {
// Update sync_dir. 1 is sync swap-in.
std::get<2>(table_sched.find(item.idx_in_end)->second) = item.r_idx;
std::get<3>(table_sched.find(item.idx_in_end)->second) = 1;
}
/// Make table_meta.
void* tmp_ptr = nullptr;
// Malloc host cpu memory, pinned memory.
cudaMallocHost(&tmp_ptr, item.size);
BlockMeta meta;
meta.size = item.size;
meta.cpu_ptr = tmp_ptr;
meta.out_stream = cu_strm1;
meta.in_stream = cu_strm2;
table_meta[item.r_idx] = meta;
}
}
/// Update table_meta's block_ and data_;
/// Update once atfer swap test is passed.
/// Enable to update negative r_idx.
/// It's safe in below procedure, as r_global_index and relative_counter should
/// never be the same.
void SwapCudaGPU::UpdateMetaTables(Block* block_ptr) {
if (past_test_flag == 1) {
// Update positive r_idx.
// location_of_2nd_iteration is the index of start of 2nd iteration.
int r_global_index =
(global_index - location_of_2nd_iteration) % iteration_length;
if (!(table_meta.find(r_global_index) == table_meta.end())) {
table_meta.find(r_global_index)->second.block_ = block_ptr;
table_meta.find(r_global_index)->second.data_ = block_ptr->get_data();
}
// Update negative r_idx.
int relative_counter = r_global_index - iteration_length;
if (!(table_meta.find(relative_counter) == table_meta.end())) {
table_meta.find(relative_counter)->second.block_ = block_ptr;
table_meta.find(relative_counter)->second.data_ = block_ptr->get_data();
}
}
}
/// Test repeatability, detect iteration, and return global_index_threshold.
int SwapCudaGPU::Detection(std::vector<std::string> vec_block,
int& iteration_length,
int& location_of_2nd_iteration) {
/// vec_str (vec_block) to vec_opt_info, sort by ptr and idx.
int idx_range = 0;
std::vector<DeviceOptInfo> vec_opt_info =
DeviceOptSeqStrToStruct(vec_block, idx_range);
/// Repeatable test.
std::vector<size_t> vec_rep =
DeviceOptSeqRepeatableTestPreProcess(vec_opt_info);
RepeatableTest(vec_rep, iteration_length, location_of_2nd_iteration,
iteration_length_threshold, global_index);
// Note here location_of_2nd_iteration not exactly start of one iteration,
// adjust to nearly start of one by restricting "Malloc".
int shift_counter = 0;
for (int i = 0; i < iteration_length; i++) {
std::vector<std::string> v =
SplitOptString(vec_block[location_of_2nd_iteration + i], " ");
if (v[0] == "Malloc") {
shift_counter = i;
break;
}
}
location_of_2nd_iteration = location_of_2nd_iteration + shift_counter;
if (iteration_length < iteration_length_threshold) {
return -1;
}
return global_index + iteration_length -
(global_index - location_of_2nd_iteration) % iteration_length;
}
/// Major stream of functions: from make candidate blocks, selection swaps, make
/// tables, etc.
void SwapCudaGPU::Plan() {
int idx_range = 0;
// Convert DeviceOptInfo squence from string to struct.
std::vector<DeviceOptInfo> vec_opt_info =
DeviceOptSeqStrToStruct(vec_block, idx_range);
std::sort(vec_opt_info.begin(), vec_opt_info.end(), sort_by_idx_ascending());
// Scale down idx, to middle iteration.
tmp_time_baseline = vec_opt_info[location_of_5th_iteration].time_stamp;
for (int i = 0; i < vec_opt_info.size(); i++) {
vec_opt_info[i].idx =
vec_opt_info[i].idx - location_of_5th_iteration - iteration_length;
vec_opt_info[i].time_stamp = vec_opt_info[i].time_stamp - tmp_time_baseline;
}
// Build op sequence and size sequence.
std::vector<DeviceOptInfo> one_iter(
&vec_opt_info[location_of_2nd_iteration + 4 * iteration_length],
&vec_opt_info[location_of_2nd_iteration + 5 * iteration_length]);
for (int i = 0; i < one_iter.size(); i++) {
operation_sequence.push_back(one_iter[i].mem_op_type);
size_sequence.push_back(one_iter[i].size);
}
// 3 iterations of vec_run and vec_load, max_idx and max_load.
std::vector<DeviceOptInfo> tmp_vec_run(
&vec_opt_info[location_of_2nd_iteration + 3 * iteration_length],
&vec_opt_info[location_of_2nd_iteration + 6 * iteration_length]);
vec_run = tmp_vec_run;
std::vector<DeviceOptInfo> tmp_vec_run2(
&vec_opt_info[location_of_2nd_iteration],
&vec_opt_info[location_of_2nd_iteration + 3 * iteration_length]);
auto vec_run2 = tmp_vec_run2;
std::vector<double> vec_load(
&global_load[location_of_2nd_iteration],
&global_load[location_of_2nd_iteration + 3 * iteration_length]);
// origin_load is 3 iteration load, for scheduling plan.
origin_load = vec_load;
auto max_current = GetLoadPeak(vec_load, iteration_length);
max_load = max_current.first;
max_idx = max_current.second;
// Sort by ptr & idx, sorting the duplicate.
auto vec_run_dup = vec_run;
std::sort(vec_run_dup.begin(), vec_run_dup.end(),
sort_by_ptr_idx_ascending());
/// Formulate swappable items and calculate PS: DOA and AOA.
std::vector<SwapBlock> vec_swap;
for (int i = 1; i < vec_run_dup.size(); i++) {
// SwapBlock: [ptr, size, r_idx, d_idx, r_time, d_time].
if ((vec_run_dup[i].size >= smallest_block) &&
(vec_run_dup[i - 1].idx < max_idx) && (vec_run_dup[i].idx > max_idx) &&
(vec_run_dup[i - 1].ptr == vec_run_dup[i].ptr) &&
((vec_run_dup[i - 1].mem_op_type == 3) or
(vec_run_dup[i - 1].mem_op_type == 2) or
(vec_run_dup[i - 1].mem_op_type == 4))) {
SwapBlock item(vec_run_dup[i].ptr, vec_run_dup[i].size,
vec_run_dup[i - 1].idx, vec_run_dup[i].idx,
vec_run_dup[i - 1].time_stamp, vec_run_dup[i].time_stamp);
item.DOA_origin = item.d_time - item.r_time;
// TODO: To simulate the gpu swap io time, system clock will be better?
// https://stackoverflow.com/questions/16177295/get-time-since-epoch-in-milliseconds-preferably-using-c11-chrono
item.DOA = item.d_time - item.r_time - SwapOutTime(item.size) -
SwapOutTime(item.size);
if (item.DOA >= 0) {
item.AOA = item.DOA * item.size;
} else {
item.AOA = item.DOA * 1 / item.size;
}
// Categories.
if (vec_run_dup[i - 1].mem_op_type == 3) {
item.cat = "A1";
item.r_idx_ready = item.r_idx;
}
if (vec_run_dup[i - 1].mem_op_type == 2) {
item.cat = "A2";
item.r_idx_ready = item.r_idx + data_buffer;
}
if (vec_run_dup[i - 1].mem_op_type == 4) {
item.cat = "A3";
item.r_idx_ready = item.r_idx + mutable_data_buffer;
}
vec_swap.push_back(item);
}
}
/// Load ideal, swap all vec_swap, least possible memory by one-swap, for data
/// collection only.
auto vec_load_ideal = GetIdealLoad(vec_load, vec_swap);
std::fstream file_load_ideal("load_ideal.csv",
std::ios::in | std::ios::out | std::ios::app);
for (int i = iteration_length; i < iteration_length * 2; i++) {
file_load_ideal << vec_load_ideal[i] << std::endl;
}
auto max_ideal = GetLoadPeak(vec_load_ideal, iteration_length);
size_t max_load_ideal = max_ideal.first;
int max_idx_ideal = max_ideal.second;
/// Majority voting, can specify mode here, can specify load_limit.
auto tmp_load = origin_load;
// FIXME: mem_limit_majority_voting is a tunable parm.
// TODO: auto determine the mem_limit_majority_voting.
// auto mem_limit_majority_voting = 550 << 20;
int mem_limit = GetWorkloadMemoryLimit();
auto mem_limit_majority_voting = mem_limit << 20;
// Select swapping blocks based on the PS(priority score) or BO score with
// load updated. vec_swap_majority_voting contains the candidate swapping
// blocks.
std::string blk_sel_mode = GetBlockSelectMode();
auto vec_swap_majority_voting =
SelectBlock(vec_swap, tmp_load, mem_limit_majority_voting, blk_sel_mode);
// vec_swap_select_global = vec_swap_majority_voting;
// Here origin_load is 3 iteration load, for scheduling plan.
// std::vector<double>
auto vec_load_WDOA = origin_load;
// Here we set the scheduling mode to: stick to the memory load limit.
std::string blk_sched_mode = GetBlockScheduleMode();
double overhead_WDOA = 0;
Scheduling(vec_swap_majority_voting, vec_load_WDOA, overhead_WDOA,
mem_limit_majority_voting, blk_sched_mode);
BuildMetaTables(vec_swap_majority_voting);
}
SwapCudaGPU::~SwapCudaGPU() {
// Dump each memory block info.
std::fstream file_blk_full("vec_block_full.csv",
std::ios::in | std::ios::out | std::ios::app);
for (int i = 0; i < vec_block.size(); i++) {
file_blk_full << vec_block[i] << std::endl;
}
if (ctx_.cublas_handle) CUBLAS_CHECK(cublasDestroy(ctx_.cublas_handle));
if (ctx_.curand_generator)
CURAND_CHECK(curandDestroyGenerator(ctx_.curand_generator));
#ifdef USE_CUDNN
if (ctx_.cudnn_handle) {
auto status = cudnnDestroy(ctx_.cudnn_handle);
CHECK_EQ(status, CUDNN_STATUS_SUCCESS) << cudnnGetErrorString(status);
}
#endif
}
const int kNumCudaStream = 1;
SwapCudaGPU::SwapCudaGPU(const std::string& blk_sel_mode,
const std::string& blk_sched_mode,
const int& mem_limit, int id)
: Device(DT_SwapCudaGPU, id, kNumCudaStream),
blk_select_mode(blk_sel_mode),
blk_scheduling_mode(blk_sched_mode),
workload_mem_limit(mem_limit) {
MemPoolConf conf;
conf.add_device(id);
// Replace this pool with swap in/out support.
pool_ = std::make_shared<SwapPool>(conf);
Setup();
}
SwapCudaGPU::SwapCudaGPU(const std::string& blk_sel_mode,
const std::string& blk_sched_mode,
const int& mem_limit, int id,
std::shared_ptr<DeviceMemPool> pool)
: Device(DT_SwapCudaGPU, id, kNumCudaStream),
blk_select_mode(blk_sel_mode),
blk_scheduling_mode(blk_sched_mode),
workload_mem_limit(mem_limit) {
CHECK(pool != nullptr);
pool_ = pool;
Setup();
}
void SwapCudaGPU::Setup() {
device_type_ = DT_SwapCudaGPU;
lang_ = kCuda;
ctx_.stream = NULL; // use the default sync stream
// TODO: create one handle for each steam?
// Preserse for future use instead of default sync stream, for concurrency
// cudaStreamCreate(&ctx_.stream);
CUDA_CHECK(cudaSetDevice(id_));
// use curandCreateGeneratorHost for CudaHost device
CURAND_CHECK(
curandCreateGenerator(&ctx_.curand_generator, CURAND_RNG_PSEUDO_DEFAULT));
CURAND_CHECK(curandSetStream(ctx_.curand_generator, ctx_.stream));
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
SetRandSeed(seed);
// TODO: if one generator per stream, then need diff offset per gen?
CURAND_CHECK(curandSetGeneratorOffset(ctx_.curand_generator, 0));
CUBLAS_CHECK(cublasCreate(&(ctx_.cublas_handle)));
CUBLAS_CHECK(cublasSetStream(ctx_.cublas_handle, ctx_.stream));
#ifdef USE_CUDNN
// TODO: create one handle for each stream?
auto status = cudnnCreate(&ctx_.cudnn_handle);
CHECK_EQ(status, CUDNN_STATUS_SUCCESS) << cudnnGetErrorString(status);
cudnnSetStream(ctx_.cudnn_handle, ctx_.stream);
#endif // USE_CUDNN
}
void SwapCudaGPU::SetRandSeed(unsigned seed) {
CHECK(ctx_.curand_generator);
CURAND_CHECK(curandSetPseudoRandomGeneratorSeed(ctx_.curand_generator, seed));
}
void SwapCudaGPU::DoExec(function<void(Context*)>&& fn, int executor) {
fn(&ctx_);
}
void SwapCudaGPU::CopyToFrom(void* dst, const void* src, size_t nBytes,
CopyDirection direction, Context* ctx) {
cudaMemcpy(dst, src, nBytes, copyKind[direction]);
// cudaMemcpyAsync(dst, src, nBytes, copyKind[direction], ctx_.stream);
}
size_t SwapCudaGPU::GetAllocatedMem() {
if (pool_ != nullptr) {
auto ret = pool_->GetMemUsage();
return ret.second - ret.first;
}
LOG(ERROR) << "The memory pool is not set";
return 0u;
}
/// Allocate gpu memory.
void* SwapCudaGPU::Malloc(int size) {
void* ptr = nullptr;
if (size > 0) {
CUDA_CHECK(cudaSetDevice(id_));
pool_->Malloc((void**)&ptr, size);
// Append vec_block_mf, for swap & pool.
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold) &&
((global_index - iteration_length) >=
three_more_iteration_global_index_threshold)) {
std::string tmp_str1 = "Malloc ";
std::stringstream ss2;
ss2 << ptr;
std::string tmp_str2 = ss2.str();
std::stringstream ss3;
ss3 << size;
std::string tmp_str3 = ss3.str();
// String tmp would be like: "Malloc <ptr> <size>".
std::string tmp = tmp_str1 + tmp_str2 + " " + tmp_str3;
vec_block_mf.push_back(tmp);
}
// Record Malloc/Free semantics after swap plan done.
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold)) {
std::fstream file_mf_one_iter(
"mf_one_iter.csv", std::ios::in | std::ios::out | std::ios::app);
file_mf_one_iter << "Malloc " << ptr << " " << size;
file_mf_one_iter << std::endl;
}
// TODO: remove the memset.
CUDA_CHECK(cudaMemset(ptr, 0, size));
// Comment out for future analysis: without cnmem
// CUDA_CHECK(cudaMemsetAsync(ptr, 0, size, ctx_.stream));
}
return ptr;
}
/// Free gpu memory.
void SwapCudaGPU::Free(void* ptr) {
if (ptr != nullptr) {
CUDA_CHECK(cudaSetDevice(id_));
pool_->Free(ptr);
/// Append vec_block_mf, for swap & pool.
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold) &&
((global_index - iteration_length) >=
three_more_iteration_global_index_threshold)) {
std::string tmp_str1 = "Free ";
std::stringstream ss2;
ss2 << ptr;
std::string tmp_str2 = ss2.str();
// String tmp would be like: "Free <ptr>".
std::string tmp = tmp_str1 + tmp_str2;
vec_block_mf.push_back(tmp);
}
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold)) {
std::fstream file_mf_one_iter(
"mf_one_iter.csv", std::ios::in | std::ios::out | std::ios::app);
file_mf_one_iter << "Free " << ptr << std::endl;
}
}
}
/// Test after every index, at append order and index changed.
void SwapCudaGPU::DetectionPlan() {
// Test iteration.
if (((global_index + 1) % (iteration_length_threshold) == 0) &&
(async_swap_flag == 0) && (past_test_flag == 0)) {
global_index_threshold =
Detection(vec_block, iteration_length, location_of_2nd_iteration);
iteration_length_threshold =
std::max(iteration_length_threshold, global_index / 10);
iteration_length_threshold = std::min(2000, iteration_length_threshold);
if (iteration_length > iteration_length_threshold) {
past_test_flag = 1;
three_more_iteration_global_index_threshold =
global_index_threshold + 3 * iteration_length;
location_of_5th_iteration =
location_of_2nd_iteration + 3 * iteration_length;
}
}
// Switch flag, next idx.
if ((global_index + 1) == three_more_iteration_global_index_threshold) {
// If we not reach here, we will get error.
Plan();
async_swap_flag = 1;
}
}
/// Append info right after Malloc; make block_ptr - data_ptr pair-wise table.
/// Since Block* is not available till Malloc() done.
void SwapCudaGPU::AppendAfterMalloc(Block* block_ptr, void* data_ptr,
int size) {
// Append necessary instrument info.
std::stringstream ss;
ss << block_ptr;
std::string tmp_str = ss.str();
DeviceOptInfoToAppend dev_opt_info("Malloc", tmp_str, size);
auto t = (std::chrono::system_clock::now()).time_since_epoch().count();
dev_opt_info.time_stamp = t;
Append(dev_opt_info);
}
/// Swap and sync as per schedule, at every index, by calling DeploySwapExec().
void SwapCudaGPU::DeploySwap() {
int r_global_index =
(global_index - location_of_2nd_iteration) % iteration_length;
int r_global_index_n = r_global_index - iteration_length;
if (async_swap_flag == 1) {
if ((global_index <
three_more_iteration_global_index_threshold + iteration_length) &&
(!(table_sched.find(r_global_index_n) == table_sched.end()))) {
DeploySwapExec(r_global_index_n);
}
if ((global_index >=
three_more_iteration_global_index_threshold + iteration_length) &&
(!(table_sched.find(r_global_index_n) == table_sched.end()))) {
DeploySwapExec(r_global_index_n);
}
if ((global_index >=
three_more_iteration_global_index_threshold + iteration_length) &&
(!(table_sched.find(r_global_index) == table_sched.end()))) {
DeploySwapExec(r_global_index);
}
}
}
// Execute DeploySwap.
void SwapCudaGPU::DeploySwapExec(int r_global_index) {
auto swap_idx = std::get<0>(table_sched.find(r_global_index)->second);
auto swap_dir = std::get<1>(table_sched.find(r_global_index)->second);
auto sync_idx = std::get<2>(table_sched.find(r_global_index)->second);
auto sync_dir = std::get<3>(table_sched.find(r_global_index)->second);
if (swap_dir == 0) {
SwapOut(swap_idx);
}
if (swap_dir == 1) {
SwapIn(swap_idx);
}
if (sync_dir == 0) {
/// Sync swap-out, actions to perform including sync, update block's data_
/// to nullptr, free
/// data_, update meta.
auto last_meta = table_meta.find(sync_idx)->second;
auto t1 = (std::chrono::system_clock::now()).time_since_epoch().count();
// FIXME: check status of cudaEventSynchronize.
cudaEventSynchronize(last_meta.in_event);
auto t2 = (std::chrono::system_clock::now()).time_since_epoch().count();
// Record the r_idx of the block/meta.
table_not_at_device[last_meta.block_] = sync_idx;
last_meta.block_->update_data(nullptr);
// Free this memory block from gpu memory pool.
pool_->Free(last_meta.data_);
/// Append vec_block_mf.
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold) &&
((global_index - iteration_length) >=
three_more_iteration_global_index_threshold)) {
std::string tmp_str1 = "Free ";
std::stringstream ss2;
ss2 << last_meta.data_;
std::string tmp_str2 = ss2.str();
// String tmp would be like: "Free <data_>".
std::string tmp = tmp_str1 + tmp_str2;
vec_block_mf.push_back(tmp);
}
if ((async_swap_flag == 1) &&
((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold)) {
std::fstream file_mf_one_iter(
"mf_one_iter.csv", std::ios::in | std::ios::out | std::ios::app);
file_mf_one_iter << "Free " << last_meta.data_ << " SwapOut(Sync)"
<< std::endl;
}
last_meta.data_ = nullptr;
// Update table_meta.
table_meta.find(sync_idx)->second = last_meta;
}
if (sync_dir == 1) {
/// Sync swap-in, actions to perform including sync, update block's data_ to
/// new gpu address,
/// update meta.
auto last_meta = table_meta.find(sync_idx)->second;
auto t1 = (std::chrono::system_clock::now()).time_since_epoch().count();
cudaEventSynchronize(last_meta.out_event);
auto t2 = (std::chrono::system_clock::now()).time_since_epoch().count();
// Remove the block from table_not_at_device.
table_not_at_device.erase(last_meta.block_);
// Update the block's data_ ptr to new gpu address.
last_meta.block_->update_data(last_meta.data_);
// Update table_meta.
table_meta.find(sync_idx)->second = last_meta;
}
}
// DeviceOptInfoToAppend: [mem_op_type, block_ptr, size, time_stamp].
void SwapCudaGPU::Append(DeviceOptInfoToAppend dev_opt_info) {
// Convert block_ptr from string to Block*.
void* tmp_ptr;
std::stringstream cvt(dev_opt_info.block_ptr);
cvt >> tmp_ptr;
auto block_ptr = static_cast<Block*>(tmp_ptr);
// Update the global memory load.
if (iteration_length < iteration_length_threshold) {
if (dev_opt_info.mem_op_type == "Malloc") {
if (global_load.size() > 0) {
// Global memory load increases with the Malloc operation.
global_load.push_back(global_load[global_load.size() - 1] +
block_ptr->size());
} else {
// If we reach here, first Malloc.
global_load.push_back(block_ptr->size());
}
} else if (dev_opt_info.mem_op_type == "Free") {
global_load.push_back(global_load[global_load.size() - 1] -
block_ptr->size());
} else {
// For other mem_op_type, e.g, Read or Mutable, the global
// memory load maintains.
global_load.push_back(global_load[global_load.size() - 1]);
}
}
// Append into vec_block.
std::stringstream ss1;
ss1 << dev_opt_info.size;
std::string tmp_str1 = ss1.str();
std::stringstream ss4;
ss4 << dev_opt_info.time_stamp;
std::string tmp_str4 = ss4.str();
// String block_info would be like: "<mem_op_type> <blk_ptr> <size>
// <time_stamp>".
std::string block_info = dev_opt_info.mem_op_type + " " +
dev_opt_info.block_ptr + " " + tmp_str1 + " " +
tmp_str4;
// std::cout << "1 " << block_info << std::endl;
vec_block.push_back(block_info);
// Change swap flag on and off.
// 0: sync, 1: async.
if (async_swap_flag == 1) {
int r_global_index =
(global_index - location_of_2nd_iteration) % iteration_length;
if (block_ptr->size() != size_sequence[r_global_index]) {
async_swap_flag = 0;
std::cout << "!!!! async_swap_flag changed back to 0" << std::endl;
}
}
// Update table_meta and table_sched.
UpdateMetaTables(block_ptr);
// Deploy swap at every index.
DeploySwap();
// Test moved from start of malloc/free to end of append, only global_index+1
// changed.
DetectionPlan();
// NOTE: This global_index includes read/write and AppendLayer as well, in
// addition to malloc/free.
global_index++;
// Call PoolOpt to Construct Pool.
if ((async_swap_flag == 1) && ((global_index - 4 * iteration_length) ==
three_more_iteration_global_index_threshold)) {
pool_->PoolOpt(vec_block_mf);
}
}
/// In case that block is not at device memory, swap-in ad hoc.
/// Used in the Block class to update ptr after swap-in is done, if variable is
/// not
/// swapped back yet as expected.
void* SwapCudaGPU::UpdateGpuPtr(const Block* block_ptr) {
auto r_idx = table_not_at_device.find(block_ptr)->second;
cudaError_t err;
BlockMeta meta = table_meta.find(r_idx)->second;
cudaEventCreate(&meta.in_event);
void* ptr = nullptr;
// FIXME: Malloc here?
pool_->Malloc((void**)&ptr, meta.size);
meta.data_ = ptr;
err = cudaMemcpyAsync(meta.data_, meta.cpu_ptr, meta.size,
cudaMemcpyHostToDevice, meta.in_stream);
cudaEventRecord(meta.in_event, meta.in_stream);
cudaEventSynchronize(meta.out_event);
table_meta.find(r_idx)->second = meta;
return ptr;
}
/// Memory copy asynchronously from GPU to CPU and update meta.
void SwapCudaGPU::SwapOut(const int idx) {
cudaError_t err;
BlockMeta meta = table_meta.find(idx)->second;
cudaEventCreate(&meta.out_event);
err = cudaMemcpyAsync(meta.cpu_ptr, meta.data_, meta.size,
cudaMemcpyDeviceToHost, meta.out_stream);
cudaEventRecord(meta.out_event, meta.out_stream);
table_meta.find(idx)->second = meta;
}
/// Memory copy asynchronously from CPU to GPU and update meta.
void SwapCudaGPU::SwapIn(const int idx) {
cudaError_t err;
BlockMeta meta = table_meta.find(idx)->second;
cudaEventCreate(&meta.in_event);
void* ptr = nullptr;
pool_->Malloc((void**)&ptr, meta.size);
/// Append vec_block_mf.
if ((async_swap_flag == 1) && ((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold) &&
((global_index - iteration_length) >=
three_more_iteration_global_index_threshold)) {
std::string tmp_str1 = "Malloc ";
std::stringstream ss2;
ss2 << ptr;
std::string tmp_str2 = ss2.str();
std::stringstream ss3;
ss3 << meta.size;
std::string tmp_str3 = ss3.str();
// String tmp would be like: "Malloc <ptr> <size>".
std::string tmp = tmp_str1 + tmp_str2 + " " + tmp_str3;
vec_block_mf.push_back(tmp);
}
if ((async_swap_flag == 1) && ((global_index - 4 * iteration_length) <
three_more_iteration_global_index_threshold)) {
std::fstream file_mf_one_iter("mf_one_iter.csv",
std::ios::in | std::ios::out | std::ios::app);
file_mf_one_iter << "Malloc " << ptr << " " << meta.size << " swapIn"
<< std::endl;
}
meta.data_ = ptr;
err = cudaMemcpyAsync(meta.data_, meta.cpu_ptr, meta.size,
cudaMemcpyHostToDevice, meta.in_stream);
cudaEventRecord(meta.in_event, meta.in_stream);
table_meta.find(idx)->second = meta;
}
/// Synchronous swap, collect speed info.
void SwapCudaGPU::SwapOutSynchronous(const Block* block_ptr) {
if (global_index < 1000 && block_ptr->size() > 1 << 20) {
std::fstream file_block5("speed.csv",
std::ios::in | std::ios::out | std::ios::app);
BlockMeta meta;
meta.data_ = meta.block_->get_data();
void* tmp_ptr = nullptr;
// Pinned memory.
cudaMallocHost(&tmp_ptr, block_ptr->size());
meta.cpu_ptr = tmp_ptr;
table_block_meta[block_ptr] = meta;
auto t1 = (std::chrono::system_clock::now()).time_since_epoch().count();
cudaError_t err;
err = cudaMemcpy(meta.cpu_ptr, meta.data_, block_ptr->size(),
cudaMemcpyDeviceToHost);
auto t2 = (std::chrono::system_clock::now()).time_since_epoch().count();
file_block5 << "Out " << block_ptr->size() << ' ' << t2 - t1 << std::endl;
}
}
/// Synchronous swap, collect speed info.
void SwapCudaGPU::SwapInSynchronous(const Block* block_ptr) {
if (global_index < 1000 && block_ptr->size() > 1 << 20) {
std::fstream file_block5("speed.csv",
std::ios::in | std::ios::out | std::ios::app);
BlockMeta meta = table_block_meta.find(block_ptr)->second;
auto t1 = (std::chrono::system_clock::now()).time_since_epoch().count();
cudaError_t err;
err = cudaMemcpy(meta.data_, meta.cpu_ptr, block_ptr->size(),
cudaMemcpyHostToDevice);
auto t2 = (std::chrono::system_clock::now()).time_since_epoch().count();
file_block5 << "In " << block_ptr->size() << ' ' << t2 - t1 << std::endl;
}
}
void SwapCudaGPU::Sync() {
Exec([this](Context* ctx) { CUDA_CHECK(cudaStreamSynchronize(ctx_.stream)); },
OpType::kSync, {}, {});
}
} // namespace singa
#endif // USE_CUDA
| 37.924673 | 118 | 0.649757 | [
"vector"
] |
ac2c67f29328d386da5c8c81c5fe42d9cd7bc781 | 777 | hpp | C++ | libs/core/render/include/bksge/core/render/d3d12/detail/inl/bool_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/include/bksge/core/render/d3d12/detail/inl/bool_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/include/bksge/core/render/d3d12/detail/inl/bool_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file bool_inl.hpp
*
* @brief Bool の実装
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BOOL_INL_HPP
#define BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BOOL_INL_HPP
#include <bksge/core/render/config.hpp>
#if BKSGE_CORE_RENDER_HAS_D3D12_RENDERER
#include <bksge/core/render/d3d12/detail/bool.hpp>
#include <bksge/core/render/d3d_common/d3d12.hpp>
namespace bksge
{
namespace render
{
namespace d3d12
{
BKSGE_INLINE
Bool::Bool(bool b)
: m_bool(b ? TRUE : FALSE)
{}
BKSGE_INLINE
Bool::operator BOOL() const
{
return m_bool;
}
} // namespace d3d12
} // namespace render
} // namespace bksge
#endif // BKSGE_CORE_RENDER_HAS_D3D12_RENDERER
#endif // BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BOOL_INL_HPP
| 16.531915 | 58 | 0.722008 | [
"render"
] |
ac30910dede0b9a843595b5f4c25609fa3a22a0e | 2,934 | cpp | C++ | video/test/test_exceptions_handler.cpp | fgenolini/frank | 0581c503f0a724cb29dc1901df9da5893947190f | [
"MIT"
] | 1 | 2020-10-12T03:08:22.000Z | 2020-10-12T03:08:22.000Z | video/test/test_exceptions_handler.cpp | fgenolini/frank | 0581c503f0a724cb29dc1901df9da5893947190f | [
"MIT"
] | 17 | 2020-04-23T08:32:59.000Z | 2020-08-20T16:58:26.000Z | video/test/test_exceptions_handler.cpp | fgenolini/frank | 0581c503f0a724cb29dc1901df9da5893947190f | [
"MIT"
] | 1 | 2020-10-12T03:33:27.000Z | 2020-10-12T03:33:27.000Z | #include "config.h"
#ifndef _TEST_EXCEPTIONS_HANDLER_
#error _TEST_EXCEPTIONS_HANDLER_ not defined
#endif
WARNINGS_OFF
#include <exception>
#include <catch2/catch.hpp>
WARNINGS_ON
#include "exception/exceptions.h"
#include "test/testable_exit.h"
namespace test::frank {
struct test_exception : public std::exception {
char const *what() const noexcept override {
return "exceptions_handler exception";
}
};
class mock_aborter {
public:
void abort() noexcept { abort_called_ = true; }
bool abort_called() { return abort_called_; }
private:
bool abort_called_{};
};
} // namespace test::frank
namespace frank::video {
aborter::aborter(void *mock_data) : mock_data_(mock_data) {}
void aborter::abort() noexcept {
auto mock = static_cast<::test::frank::mock_aborter *>(mock_data_);
mock->abort();
}
} // namespace frank::video
SCENARIO("frank video exceptions_handler", "[exceptions_handler]") {
GIVEN("exception thrown from the frank video application") {
WHEN("no exception thrown") {
test::frank::test_exception exception_object{};
test::frank::mock_aborter mocked_aborter{};
frank::video::aborter mock{&mocked_aborter};
frank::video::global_injected_aborter = nullptr;
frank::video::exceptions exception_test{&mock};
try {
// do nothing
} catch (...) {
exception_test.handler();
}
THEN("abort is not called") {
REQUIRE(mocked_aborter.abort_called() == false);
}
}
WHEN("exception object thrown") {
test::frank::test_exception exception_object{};
test::frank::mock_aborter mocked_aborter{};
frank::video::aborter mock{&mocked_aborter};
frank::video::global_injected_aborter = nullptr;
frank::video::exceptions exception_test{&mock};
try {
throw exception_object;
} catch (const std::exception &e) {
exception_test.handler(&e);
}
THEN("abort is called") {
REQUIRE(mocked_aborter.abort_called() == true);
}
}
WHEN("int number thrown") {
constexpr auto INT_EXCEPTION = 42;
test::frank::mock_aborter mocked_aborter{};
frank::video::aborter mock{&mocked_aborter};
frank::video::global_injected_aborter = nullptr;
frank::video::exceptions exception_test{&mock};
try {
throw INT_EXCEPTION;
} catch (...) {
exception_test.handler();
}
THEN("abort is called") {
REQUIRE(mocked_aborter.abort_called() == true);
}
}
WHEN("exception thrown") {
test::frank::mock_aborter mocked_aborter{};
frank::video::aborter mock{&mocked_aborter};
frank::video::global_injected_aborter = &mock;
try {
throw nullptr;
} catch (...) {
frank::video::unhandled_exception_handler();
}
THEN("abort is called") {
REQUIRE(mocked_aborter.abort_called() == true);
}
}
}
}
| 25.076923 | 69 | 0.64758 | [
"object"
] |
ac326f7f23b13d85a661e6a7afeb3250ed1d6ab0 | 19,030 | cpp | C++ | test_PDE/test_Gray_Scott.cpp | koutasekine/vcp | 3ce9a6f87be516158622219792668844d7a3a50f | [
"MIT"
] | null | null | null | test_PDE/test_Gray_Scott.cpp | koutasekine/vcp | 3ce9a6f87be516158622219792668844d7a3a50f | [
"MIT"
] | null | null | null | test_PDE/test_Gray_Scott.cpp | koutasekine/vcp | 3ce9a6f87be516158622219792668844d7a3a50f | [
"MIT"
] | null | null | null | // VCP Library
// http ://verified.computation.jp
//
// VCP Library is licensed under the BSD 3 - clause "New" or "Revised" License
// Copyright(c) 2017, Kouta Sekine <k.sekine@computation.jp>
// 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.
// * Neither the name of the Kouta Sekine nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// 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 KOUTA SEKINE 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 <iostream>
#include <kv/interval.hpp>
#include <kv/rdouble.hpp>
#include <kv/dd.hpp>
#include <kv/rdd.hpp>
#include <kv/mpfr.hpp>
#include <kv/rmpfr.hpp>
#include <vcp/pdblas.hpp>
#include <vcp/pidblas.hpp>
#include <vcp/matrix.hpp>
#include <vcp/matrix_assist.hpp>
#include <vcp/ldbase.hpp>
#include <vcp/vcp_timer.hpp>
#include <cmath>
//typedef double AppData;
typedef kv::dd AppData;
//typedef kv::mpfr<110> AppData;
typedef kv::interval<kv::mpfr<2000>> DataType;
//typedef vcp::pdblas POLICY;
typedef vcp::mats<AppData> POLICY;
typedef kv::interval<AppData> VAccData;
typedef vcp::imats<AppData> VAccPOLICY;
typedef double Data;
typedef kv::interval<Data> VData;
typedef vcp::pidblas VPOLICY;
typedef vcp::pdblas PDBLAS;
typedef kv::dd ResData;
typedef kv::interval<ResData> VResData;
typedef vcp::imats<ResData> VResPOLICY;
int main(void)
{
std::cout.precision(17);
std::cout << "/**********************************************************************************/" << std::endl;
std::cout << "/**********************************************************************************/" << std::endl;
std::cout << "/*********** *************/" << std::endl;
std::cout << "/*********** Verified computation for solution to Gray-Scott equation *************/" << std::endl;
std::cout << "/*********** *************/" << std::endl;
std::cout << "/**********************************************************************************/" << std::endl;
std::cout << "/**********************************************************************************/\n"
<< std::endl;
vcp::matrix<AppData, POLICY> uh, uh1, uh2, zh;
vcp::Legendre_Bases_Generator<DataType, AppData, POLICY> Approximate_Generator;
int epsilon = 100;
std::cout << "Epsilon = " << epsilon << std::endl;
int Order_legendre = 30;
int uh_Order_legendre = 40;
int p = 3;
int Dimension = 2;
int Number_of_variables = 2;
std::cout << "Dimension = " << Dimension << std::endl;
std::cout << "uh of Legendre Bases Order = " << uh_Order_legendre << std::endl;
std::cout << "Inverse Norm for Legendre Bases Order = " << Order_legendre << std::endl;
std::cout << "p (which is maximum order of uh^p) = " << p << std::endl;
std::cout << "Number of Variables (e.g. 2 => u and v) = " << Number_of_variables << std::endl;
// Setting of Approximate_Generator
std::cout << "Setting the Generator by Approximate mode " << std::endl;
Approximate_Generator.setting(uh_Order_legendre, p, Dimension, Number_of_variables, 15);
// Setting the list of Approximate_Generator
//Approximate_Generator.setting_list();
Approximate_Generator.setting_evenlist();
// output the list => list_uh
vcp::matrix<int> list_uh = Approximate_Generator.output_list();
// setting initialization value of uh
// uh.rand(list_uh.rowsize(), Number_of_variables);
// uh = 30 * uh;
// uh(0, 0) = 40;
// uh(1, 0) = 50;
// uh(0, 1) = 40;
// uh(1, 1) = 50;
vcp::load(uh, "Data_Gray_Scott/uh_solution1_eps55");
//vcp::load(uh, "Data_Gray_Scott/uh_solution2_eps55");
uh.resize(list_uh.rowsize(), Number_of_variables);
std::cout << "Newton Method Start " << std::endl;
{
// Make the matrix ((\nabla \phi_i, \nabla \phi_j)_{L^2})_{i,j}
vcp::matrix<AppData, POLICY> DL = Approximate_Generator.dphidphi();
// Make the matrix ((phi_i, \phi_j)_{L^2})_{i,j}
vcp::matrix<AppData, POLICY> L = Approximate_Generator.phiphi();
vcp::matrix<AppData, POLICY> uh2vhphi;
vcp::matrix<AppData, POLICY> uhphi;
vcp::matrix<AppData, POLICY> vhphi;
vcp::matrix<AppData, POLICY> fphi;
vcp::matrix<AppData, POLICY> uhvhphiphi;
vcp::matrix<AppData, POLICY> uh2phiphi;
vcp::matrix<AppData, POLICY> DF;
vcp::matrix<AppData, POLICY> F;
vcp::matrix<AppData, POLICY> syuusei;
vcp::matrix<AppData, POLICY> check;
uh1 = uh.submatrix({0, uh.rowsize() - 1}, {0});
uh2 = uh.submatrix({0, uh.rowsize() - 1}, {1});
zh = vercat(uh1, uh2); // zh = [u; v]
{
AppData cc;
while (1)
{
uh = horzcat(uh1, uh2); // uh = [u, v]
Approximate_Generator.setting_uh(uh);
uh2vhphi = Approximate_Generator.uhphi(2, 1); // vector (u^2 v, phi)
uhphi = Approximate_Generator.uhphi(1, 0); // vector (u, phi)
vhphi = Approximate_Generator.uhphi(0, 1); // vector (v, phi)
fphi = Approximate_Generator.fphi(); // vector (f, phi)
uh2phiphi = Approximate_Generator.uhphiphi(2, 0); // matrix (u^2 phi, phi)
uhvhphiphi = Approximate_Generator.uhphiphi(1, 1); // matrix (u v phi, phi)
DF = vercat(horzcat(DL - epsilon * (2 * uhvhphiphi - L), -epsilon * uh2phiphi), horzcat(2 * uhvhphiphi, DL - (-uh2phiphi - 10 * L)));
F = vercat(DL * uh1 - epsilon * (uh2vhphi - uhphi), DL * uh2 - (-uh2vhphi + 10 * (fphi - vhphi)));
syuusei = lss(DF, F);
zh = zh - syuusei;
check = max(abs(syuusei));
cc = check(0);
std::cout << cc << std::endl;
if (cc < pow(2.0, -90))
{
std::cout << "Convergence \n"
<< std::endl;
uh1 = zh.submatrix({0, uh.rowsize() - 1}, {0});
uh2 = zh.submatrix({uh.rowsize(), zh.rowsize() - 1}, {0});
uh = horzcat(uh1, uh2);
Approximate_Generator.setting_uh(uh);
break;
}
uh1 = zh.submatrix({0, uh.rowsize() - 1}, {0});
uh2 = zh.submatrix({uh.rowsize(), zh.rowsize() - 1}, {0});
}
}
}
// uh data for Grafics
// std::cout << "list_uh = " << std::endl;
// std::cout << list_uh << std::endl;
// vcp::save(list_uh, "Data_Gray_Scott/list_uh_solution3");
// std::cout << "uh = " << std::endl;
// std::cout << uh << std::endl;
// vcp::save(uh, "Data_Gray_Scott/uh_solution3");
vcp::matrix<AppData, POLICY> Grafics = Approximate_Generator.output_uh_for_graphics(100);
std::cout << "Grafics = " << std::endl;
std::cout << Grafics << std::endl;
// vcp::save(Grafics, "Data_Gray_Scott/uh_Graf_solution3");
// minimal and maximum value of approximate solution uh
std::vector<kv::interval<double>> x;
x.resize(Dimension);
for (int d = 0; d < Dimension; d++)
{
x[d] = kv::interval<double>(0, 1);
}
std::vector<double> uh_min = Approximate_Generator.global_min(x, std::pow(2.0, -9));
std::vector<double> uh_max = Approximate_Generator.global_max(x, std::pow(2.0, -9));
for (int i = 0; i < Number_of_variables; i++)
{
std::cout << "uh in [" << uh_min[i] << ", " << uh_max[i] << "]" << std::endl;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/******************* Calculate Inverse Norm || F'[uh]^-1 ||_(H-1,H10) <= K *********************/
/////////////////////////////////////////////////////////////////////////////////////////////////
vcp::time.tic();
VData CN, Cs6, C2;
VData K = VData(1);
vcp::matrix<VData, VPOLICY> uh_max_min;
uh_max_min.zeros(Number_of_variables, 1);
for (int i = 0; i < Number_of_variables; i++)
{
uh_max_min(i) = kv::interval<double>(uh_min[i], uh_max[i]);
}
{
std::cout << "\n>>> Calculate Inverse Norm || F'[uh]^-1 ||_(H-1,H10) <= K" << std::endl;
vcp::Legendre_Bases_Generator<DataType, VAccData, VAccPOLICY> Verification_Generator;
Verification_Generator.setting(Order_legendre, p, Dimension, Number_of_variables, 1, uh_Order_legendre);
Verification_Generator.setting_list();
//Verification_Generator.setting_evenlist();
vcp::matrix<VAccData, VAccPOLICY> uhi;
vcp::interval(uh, uhi);
// uh setting : Last Argument is list divide : full list => 1 , even list => 2
Verification_Generator.setting_uh(uhi, list_uh, 2);
// Make the matrix ((\nabla \phi_i, \nabla \phi_j)_{L^2})_{i,j}
vcp::matrix<VAccData, VAccPOLICY> DLAcc = Verification_Generator.dphidphi();
vcp::matrix<VAccData, VAccPOLICY> LAcc = Verification_Generator.phiphi();
vcp::matrix<VAccData, VAccPOLICY> uh2phiphiAcc = Verification_Generator.uhphiphi(2, 0); // matrix (u^2 phi, phi)
vcp::matrix<VAccData, VAccPOLICY> uhvhphiphiAcc = Verification_Generator.uhphiphi(1, 1); // matrix (u v phi, phi)
vcp::matrix<VAccData, VAccPOLICY> Zero;
Zero.zeros(DLAcc.rowsize(), DLAcc.columnsize());
DLAcc = vercat(horzcat(DLAcc, Zero), horzcat(Zero, DLAcc));
vcp::matrix<VAccData, VAccPOLICY> NAcc = vercat(horzcat(epsilon * (2 * uhvhphiphiAcc - LAcc), epsilon * uh2phiphiAcc), horzcat(-2 * uhvhphiphiAcc, -uh2phiphiAcc - 10 * LAcc));
vcp::matrix<VAccData, VAccPOLICY> NTAcc = vercat(horzcat(epsilon * (2 * uhvhphiphiAcc - LAcc), -2 * uhvhphiphiAcc), horzcat(epsilon * uh2phiphiAcc, -uh2phiphiAcc - 10 * LAcc));
uh2phiphiAcc.clear();
uhvhphiphiAcc.clear();
LAcc = vercat(horzcat(LAcc, Zero), horzcat(Zero, LAcc));
Zero.clear();
vcp::matrix<VAccData, VAccPOLICY> DFAcc = DLAcc - (NAcc + NTAcc);
vcp::matrix<VData, VPOLICY> DF, DL, L, N, NT;
vcp::convert(DFAcc, DF);
DFAcc.clear();
vcp::convert(DLAcc, DL);
DLAcc.clear();
vcp::convert(LAcc, L);
LAcc.clear();
vcp::convert(NAcc, N);
NAcc.clear();
vcp::convert(NTAcc, NT);
NTAcc.clear();
DF = DF + N * lss(DL, NT);
DL.clear();
N.clear();
NT.clear();
vcp::matrix<VData, VPOLICY> E;
compsym(DF); // Forced symmetrization
compsym(L);
eigsymge(DF, L, E);
E = diag(E);
std::cout << min(E) << std::endl;
// Calculate some constants
C2 = Verification_Generator.Poincare_constant<VData>();
std::cout << "C2 = " << C2 << std::endl;
Cs6 = Verification_Generator.Sobolev_constant<VData>(6);
std::cout << "Cs6 = " << Cs6 << ", p ="
<< "6" << std::endl;
CN = Verification_Generator.Ritz_projection_error<VData>();
std::cout << "CN = " << CN << std::endl;
Verification_Generator.clear();
vcp::matrix<VData, VPOLICY> Q_max_min;
Q_max_min.zeros(Number_of_variables, Number_of_variables);
Q_max_min(0, 0) = epsilon * (2 * uh_max_min(0) * uh_max_min(1) - 1);
Q_max_min(0, 1) = epsilon * pow(uh_max_min(0), 2);
Q_max_min(1, 0) = -2 * uh_max_min(0) * uh_max_min(1);
Q_max_min(1, 1) = -pow(uh_max_min(0), 2) - 10;
vcp::matrix<VData, VPOLICY> QQ_norm;
Q_max_min = intervalmag(Q_max_min + transpose(Q_max_min));
QQ_norm = normtwo(Q_max_min);
std::cout << "QQ_norm = " << std::endl;
std::cout << QQ_norm << std::endl;
VData sigma = QQ_norm(0) + 0.01;
std::cout << "sigma = " << std::endl;
std::cout << sigma << std::endl;
Q_max_min.zeros(Number_of_variables, Number_of_variables);
Q_max_min(0, 0) = sigma - epsilon * (2 * uh_max_min(0) * uh_max_min(1) - 1);
Q_max_min(0, 1) = -epsilon * pow(uh_max_min(0), 2);
Q_max_min(1, 0) = 2 * uh_max_min(0) * uh_max_min(1);
Q_max_min(1, 1) = sigma + pow(uh_max_min(0), 2) + 10;
vcp::matrix<VData, VPOLICY> Qsigma_norm;
Q_max_min = intervalmag(Q_max_min + transpose(Q_max_min));
Qsigma_norm = normtwo(Q_max_min);
std::cout << "Qsigma_norm = " << std::endl;
std::cout << Qsigma_norm << std::endl;
Q_max_min.zeros(Number_of_variables, Number_of_variables);
Q_max_min(0, 0) = epsilon * (2 * uh_max_min(0) * uh_max_min(1) - 1);
Q_max_min(0, 1) = epsilon * pow(uh_max_min(0), 2);
Q_max_min(1, 0) = -2 * uh_max_min(0) * uh_max_min(1);
Q_max_min(1, 1) = -pow(uh_max_min(0), 2) - 10;
vcp::matrix<VData, VPOLICY> Q_norm;
Q_max_min = intervalmag(Q_max_min);
Q_norm = normtwo(Q_max_min);
std::cout << "Q_norm = " << std::endl;
std::cout << Q_norm << std::endl;
VData mu_sh1 = E(0) + sigma;
std::cout << "mu_sh1 = " << std::endl;
std::cout << mu_sh1 << std::endl;
VData C_Msigma = CN * sqrt(1 + pow(CN, 2) * (Qsigma_norm(0) + pow(C2 * Q_norm(0), 2)));
std::cout << "C_Msigma = " << std::endl;
std::cout << C_Msigma << std::endl;
vcp::matrix< VData, VPOLICY > mu_sh;
vcp::matrix< VData, VPOLICY > Lambda;
Lambda = E;
mu_sh = E + sigma;
VData mu_low;
for (int i = 0; i < mu_sh.rowsize(); i++){
mu_low = mu_sh(i)/(1 + pow(C_Msigma,2)*mu_sh(i) );
mu_sh(i).lower() = mu_low.lower();
Lambda(i).lower() = (mu_sh(i) - sigma).lower();
}
VData lambda = Lambda(0);
std::cout << "lambda = " << std::endl;
std::cout << lambda << std::endl;
if (lambda.lower() > 0){
using std::sqrt;
K = 1/sqrt(lambda);
std::cout << "Pre K = " << std::endl;
std::cout << K << std::endl;
sigma = 0;
}
else {
std::cout << "Can not estimate Pre K" << std::endl;
sigma = VData(abs(lambda.lower())) + 1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/******************* Calculate Residual Norm || Laplace(uh) - f(uh) ||_L2 **********************/
/////////////////////////////////////////////////////////////////////////////////////////////////
vcp::time.tic();
VData Res = VData(0);
VData Res1 = VData(0);
VData Res2 = VData(0);
{
std::cout << "\n>>> Calculate Residual Norm || Laplace(uh) - f(uh) ||_L2" << std::endl;
vcp::Legendre_Bases_Generator<DataType, VResData, VResPOLICY> Verification_Generator;
Verification_Generator.setting(uh_Order_legendre, p, Dimension, Number_of_variables, 2);
// Setting the list of Verification_Generator
//Verification_Generator.setting_list();
Verification_Generator.setting_evenlist();
vcp::matrix<VResData, VResPOLICY> uhi;
vcp::interval(uh, uhi);
//vcp::convert(uh, uhi);
Verification_Generator.setting_uh(uhi);
// 1. First form
// F1(uh, vh) = - DL * uh - epsilon*(uh2vhphi - uhphi)
VResData LuhLuh = Verification_Generator.integral_LuhLuh(0);
VResData Luh_uh2vh = Verification_Generator.integral_Luhuh(0, 2, 1);
VResData Luh_uh = Verification_Generator.integral_Luhuh(0, 1, 0);
VResData uh4vh2 = Verification_Generator.integral_uh(4, 2);
VResData uh3vh = Verification_Generator.integral_uh(3, 1);
VResData uh2 = Verification_Generator.integral_uh(2, 0);
{
using std::abs;
using std::sqrt;
vcp::convert(sqrt(abs(LuhLuh + 2 * epsilon * (Luh_uh2vh - Luh_uh) + epsilon * epsilon * (uh4vh2 - 2 * uh3vh + uh2))), Res1);
std::cout << "First Residual Norm : || Laplace(uh) - f1(uh, vh) ||_L2 <= " << Res1 << std::endl;
}
// 2. Second form
// F2(uh, vh) = - DL * vh - ( -uh2v + 10( 1 - vh ) )
VResData LvhLvh = Verification_Generator.integral_LuhLuh(1);
VResData Lvh_uh2vh = Verification_Generator.integral_Luhuh(1, 2, 1);
VResData Lvh_f = Verification_Generator.integral_Luhuh(1, 0, 0);
VResData Lvh_vh = Verification_Generator.integral_Luhuh(1, 0, 1);
VResData uh2vh = Verification_Generator.integral_uh(2, 1);
VResData uh2vh2 = Verification_Generator.integral_uh(2, 2);
VResData vh = Verification_Generator.integral_uh(0, 1);
VResData vh2 = Verification_Generator.integral_uh(0, 2);
{
using std::abs;
using std::sqrt;
vcp::convert(sqrt(abs(LvhLvh + 2 * (-Lvh_uh2vh + 10 * (Lvh_f - Lvh_vh)) + uh4vh2 + 20 * (uh2vh2 - uh2vh) + 100 * (1 + vh2) - 200 * vh)), Res2);
std::cout << "Second Residual Norm : || Laplace(vh) - f2(uh, vh) ||_L2 <= " << Res2 << std::endl;
}
using std::sqrt;
Res = sqrt(Res1 * Res1 + Res2 * Res2);
std::cout << "Residual Norm : || F(uh, vh) ||_X <= " << Res << std::endl;
// Res = Cp * Res;
// std::cout << "Residual Norm : || F(uh) ||_(H-1) <= " << Res << std::endl;
}
vcp::time.toc();
/////////////////////////////////////////////////////////////////////////////////////////////////
/**** Calculate Lipschitz constant || F'[w1] - F'[w2] ||_(H-1,H10) <= G || w1 - w2 ||_(H10) ****/
/////////////////////////////////////////////////////////////////////////////////////////////////
vcp::time.tic();
VData G = VData(0);
{
std::cout << "\n>>> Calculate Lipschitz constant || F'[w1] - F'[w2] ||_(H-1,H10) <= G || w1 - w2 ||_(H10)" << std::endl;
using std::pow;
vcp::Legendre_Bases_Generator<DataType, VData, VPOLICY> Verification_Generator;
Verification_Generator.setting(uh_Order_legendre, 1, Dimension, Number_of_variables, 1, uh_Order_legendre);
// Setting the list of Verification_Generator
//Verification_Generator.setting_list();
Verification_Generator.setting_evenlist();
// Make the matrix ((\nabla \phi_i, \nabla \phi_j)_{L^2})_{i,j}
vcp::matrix<VData, VPOLICY> DL = Verification_Generator.dphidphi();
// Make the matrix ((phi_i, \phi_j)_{L^2})_{i,j}
vcp::matrix<VData, VPOLICY> L = Verification_Generator.phiphi();
vcp::matrix<VData, VPOLICY> uhi;
vcp::convert(uh, uhi);
vcp::matrix<VData, VPOLICY> uh_H10_norm = sqrt(abs(transpose(uhi) * (DL * uhi)));
std::cout << "|| uh ||_(H10) = " << uh_H10_norm << std::endl;
vcp::matrix<VData, VPOLICY> Gm;
vcp::matrix<VData, VPOLICY> E;
Gm.zeros(Number_of_variables, Number_of_variables);
std::cout << "Cs6 = " << Cs6 << ", p ="
<< "6" << std::endl;
Gm(0, 0) = 2 * epsilon * pow(Cs6, 3) * (2 * uh_H10_norm(0, 0) + uh_H10_norm(1, 1) + 6 * K * Res);
Gm(0, 1) = epsilon * pow(Cs6, 3) * (uh_H10_norm(0, 0) + 2 * K * Res);
Gm(1, 0) = 2 * pow(Cs6, 3) * (2 * uh_H10_norm(0, 0) + uh_H10_norm(1, 1) + 6 * K * Res);
Gm(1, 1) = pow(Cs6, 3) * (uh_H10_norm(0, 0) + 2 * K * Res);
std::cout << "Gm = " << std::endl;
std::cout << Gm << std::endl;
Gm = ltransmul(Gm);
std::cout << "Gm^T * Gm = " << std::endl;
std::cout << Gm << std::endl;
eigsym(Gm, E);
E = diag(E);
G = sqrt(abs(E(1, 0)));
std::cout << "G = " << std::endl;
std::cout << G << std::endl;
}
vcp::time.toc();
return 0;
}
}
| 38.06 | 178 | 0.606148 | [
"vector"
] |
ac3b70aa7d9d09b627fa2fc1ee258c629b1c8646 | 556 | hpp | C++ | Source/Ilum/Graphics/Descriptor/DescriptorSet.hpp | Chaf-Libraries/Ilum | 83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8 | [
"MIT"
] | 11 | 2022-01-09T05:32:56.000Z | 2022-03-28T06:35:16.000Z | Source/Ilum/Graphics/Descriptor/DescriptorSet.hpp | LavenSun/IlumEngine | 94841e56af3c5214f04e7a94cb7369f4935c5788 | [
"MIT"
] | null | null | null | Source/Ilum/Graphics/Descriptor/DescriptorSet.hpp | LavenSun/IlumEngine | 94841e56af3c5214f04e7a94cb7369f4935c5788 | [
"MIT"
] | 1 | 2021-11-20T15:39:03.000Z | 2021-11-20T15:39:03.000Z | #pragma once
#include "Utils/PCH.hpp"
namespace Ilum
{
class Pipeline;
class CommandBuffer;
class Shader;
class DescriptorSet
{
public:
DescriptorSet(const Shader &shader, uint32_t set_index = 0);
~DescriptorSet();
void update(const std::vector<VkWriteDescriptorSet> &write_descriptor_sets) const;
const VkDescriptorSet &getDescriptorSet() const;
operator const VkDescriptorSet &() const;
uint32_t index() const;
private:
VkDescriptorSet m_handle = VK_NULL_HANDLE;
uint32_t m_set_index = 0;
};
} // namespace Ilum | 18.533333 | 83 | 0.732014 | [
"vector"
] |
ac462d517283092e459f71d0c825efac97f05a1d | 3,956 | hxx | C++ | main/chart2/source/view/axes/VPolarGrid.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/chart2/source/view/axes/VPolarGrid.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/chart2/source/view/axes/VPolarGrid.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _CHART2_VPOLARGRID_HXX
#define _CHART2_VPOLARGRID_HXX
#include "VAxisOrGridBase.hxx"
#include "Tickmarks.hxx"
#include "VLineProperties.hxx"
#include <com/sun/star/drawing/PointSequenceSequence.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class PolarPlottingPositionHelper;
class VPolarGrid : public VAxisOrGridBase
{
//-------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------
public:
VPolarGrid( sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
, const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > > & rGridPropertiesList //main grid, subgrid, subsubgrid etc
);
virtual ~VPolarGrid();
virtual void createShapes();
void setIncrements( const std::vector< ExplicitIncrementData >& rIncrements );
static void createLinePointSequence_ForAngleAxis(
::com::sun::star::drawing::PointSequenceSequence& rPoints
, ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos
, const ExplicitIncrementData& rIncrement
, const ExplicitScaleData& rScale
, PolarPlottingPositionHelper* pPosHelper
, double fLogicRadius, double fLogicZ );
private: //member
::com::sun::star::uno::Sequence<
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > > m_aGridPropertiesList;//main grid, subgrid, subsubgrid etc
PolarPlottingPositionHelper* m_pPosHelper;
::std::vector< ExplicitIncrementData > m_aIncrements;
void getAllTickInfos( sal_Int32 nDimensionIndex, ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos ) const;
void create2DRadiusGrid( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget
, ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
, ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
, const ::std::vector<VLineProperties>& rLinePropertiesList );
#if NOTYET
void create2DAngleGrid( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget
, ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
, ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
, const ::std::vector<VLineProperties>& rLinePropertiesList );
#endif
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
| 43.472527 | 122 | 0.553589 | [
"vector"
] |
ac46dcfc7b441f9450d015ec92f3f0afb80c9e96 | 3,919 | hpp | C++ | three/core/geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | three/core/geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | three/core/geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | #ifndef THREE_GEOMETRY_HPP
#define THREE_GEOMETRY_HPP
#include <three/common.hpp>
#include <three/core/geometry_buffer.hpp>
#include <three/core/geometry_group.hpp>
#include <three/core/math.hpp>
#include <three/core/color.hpp>
#include <three/core/face.hpp>
#include <three/core/vector3.hpp>
#include <three/core/vertex.hpp>
#include <three/core/uv.hpp>
#include <three/core/interfaces.hpp>
#include <three/materials/material.hpp>
#include <three/utils/memory.hpp>
#include <array>
#include <unordered_map>
#include <tuple>
namespace three {
struct MorphTarget
{
std::string name;
std::vector<Vertex> vertices;
};
struct Box
{
Vector3 min;
Vector3 max;
Box() {}
Box(const Vector3& min, const Vector3& max)
: min(min), max(max) {}
void bound(const Vector3& pos)
{
if (pos.x < min.x)
{
min.x = pos.x;
}
else if (pos.x > max.x)
{
max.x = pos.x;
}
if (pos.y < min.y)
{
min.y = pos.y;
}
else if (pos.y > max.y)
{
max.y = pos.y;
}
if (pos.z < min.z)
{
min.z = pos.z;
}
else if (pos.z > max.z)
{
max.z = pos.z;
}
}
};
struct Sphere
{
Sphere()
: radius(0.0f) {}
float radius;
};
class Geometry : public IGeometry, public GeometryBuffer
{
public:
typedef std::shared_ptr<Geometry> Ptr;
static Ptr create() { return make_shared<Geometry>(); }
virtual THREE::GeometryType type() const { return THREE::Geometry; }
/////////////////////////////////////////////////////////////////////////
int id;
std::string name;
std::vector<Vertex> vertices;
std::vector<Color> colors; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
std::vector<Material::Ptr> materials;
Attributes attributes;
std::vector<Face> faces;
std::vector<std::vector<UV>> faceUvs;
std::vector<std::vector<std::array<UV, 4>>> faceVertexUvs;
std::vector<MorphTarget> morphTargets;
std::vector<Color> morphColors;
//std::vector<Vector3> morphNormals;
std::vector<Face> morphNormals;
std::vector<Vector3> skinVerticesA;
std::vector<Vector3> skinVerticesB;
std::vector<Vector4> skinWeights;
struct SkinIndices
{
int x, y, z, w;
};
std::vector<SkinIndices> skinIndices;
struct Offset
{
int index, count, start;
};
std::vector<Offset> offsets;
Box boundingBox;
Sphere boundingSphere;
bool hasTangents;
bool dynamic;
std::unordered_map<std::string, GeometryGroup::Ptr> geometryGroups;
std::vector<GeometryGroup*> geometryGroupsList;
bool verticesNeedUpdate;
bool morphTargetsNeedUpdate;
bool elementsNeedUpdate;
bool uvsNeedUpdate;
bool normalsNeedUpdate;
bool tangentsNeedUpdate;
bool colorsNeedUpdate;
/////////////////////////////////////////////////////////////////////////
virtual THREE_DECL void applyMatrix(const Matrix4& matrix);
virtual THREE_DECL void computeCentroids();
virtual THREE_DECL void computeFaceNormals();
virtual THREE_DECL void computeVertexNormals();
virtual THREE_DECL void computeTangents();
virtual THREE_DECL void computeBoundingBox();
virtual THREE_DECL void computeBoundingSphere();
THREE_DECL void mergeVertices();
/////////////////////////////////////////////////////////////////////////
protected:
THREE_DECL Geometry();
THREE_DECL virtual ~Geometry();
private:
std::vector<Vector3> normals;
static int& GeometryCount()
{
static int sGeometryCount = 0;
return sGeometryCount;
}
};
} // namespace three
#if defined(THREE_HEADER_ONLY)
# include <three/core/impl/geometry.ipp>
#endif // defined(THREE_HEADER_ONLY)
#endif // THREE_GEOMETRY_HPP | 21.893855 | 99 | 0.599898 | [
"geometry",
"vector"
] |
ac47a38078c4f2b012493acaa05131fac2a41171 | 1,470 | cpp | C++ | plugin/plugin/core/moduleloader.cpp | perandersson/plugin | 1602fa6cd97fcacb62d72084c03f22bd7117951a | [
"MIT"
] | 9 | 2016-03-30T03:05:03.000Z | 2020-04-14T00:48:35.000Z | plugin/plugin/core/moduleloader.cpp | perandersson/plugin | 1602fa6cd97fcacb62d72084c03f22bd7117951a | [
"MIT"
] | null | null | null | plugin/plugin/core/moduleloader.cpp | perandersson/plugin | 1602fa6cd97fcacb62d72084c03f22bd7117951a | [
"MIT"
] | 3 | 2016-08-03T04:12:29.000Z | 2020-04-14T00:48:36.000Z | #include "moduleloader.h"
#include <cassert>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
LibraryHandle ModuleLoader::GetLibraryHandle(const char* fileName)
{
char tmp[1024] = { 0 };
sprintf(tmp, "%s.dll", fileName);
auto library = LoadLibraryA(tmp);
if (library == nullptr)
return nullptr;
assert(((PIMAGE_DOS_HEADER)library)->e_magic == IMAGE_DOS_SIGNATURE);
return library;
}
void ModuleLoader::UnloadLibrary(LibraryHandle library)
{
FreeLibrary((HMODULE)library);
}
void* ModuleLoader::GetFunctionPtr(LibraryHandle library, const char* name)
{
FARPROC addr = GetProcAddress((HMODULE)library, name);
return addr;
}
std::vector<std::string> ModuleLoader::GetFunctionNames(LibraryHandle library)
{
std::vector<std::string> functions;
HMODULE lib = (HMODULE)library;
PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS)((BYTE *)lib + ((PIMAGE_DOS_HEADER)lib)->e_lfanew);
assert(header->Signature == IMAGE_NT_SIGNATURE);
assert(header->OptionalHeader.NumberOfRvaAndSizes > 0);
PIMAGE_EXPORT_DIRECTORY exports = (PIMAGE_EXPORT_DIRECTORY)((BYTE *)lib + header->
OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
PVOID names = (BYTE *)lib + exports->AddressOfNames;
for (DWORD i = 0; i < exports->NumberOfNames; i++) {
char* cname = (char *)lib + ((DWORD *)names)[i];
std::string name = std::string(cname);
functions.push_back(name);
}
return functions;
}
#else
#error Not implemented
#endif
| 24.5 | 98 | 0.742177 | [
"vector"
] |
ac50937ef3e28c1ac5aae651f9cf266ad07abcc4 | 3,640 | cpp | C++ | paddle/gserver/activations/MKLDNNActivation.cpp | AI-books/Paddle | 5b5f4f514047975ac09ec42b31e46dabf235e7dd | [
"Apache-2.0"
] | null | null | null | paddle/gserver/activations/MKLDNNActivation.cpp | AI-books/Paddle | 5b5f4f514047975ac09ec42b31e46dabf235e7dd | [
"Apache-2.0"
] | null | null | null | paddle/gserver/activations/MKLDNNActivation.cpp | AI-books/Paddle | 5b5f4f514047975ac09ec42b31e46dabf235e7dd | [
"Apache-2.0"
] | 1 | 2020-06-04T04:27:15.000Z | 2020-06-04T04:27:15.000Z | /* Copyright (c) 2017 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 "MKLDNNActivation.h"
#include "mkldnn.hpp"
#include "paddle/utils/ClassRegistrar.h"
namespace paddle {
static ClassRegistrar<ActivationFunction> gMKLDNNActivationRegistrar;
/**
* @def MKLDNN_ACTIVATION_CLASS_NAME
* @note MKLDNN_ACTIVATION_CLASS_NAME(relu) relu_;
* means mkldnn_reluActivation relu_;
*/
#define MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE) mkldnn_##ACT_TYPE##Activation
/**
* @def DEFINE_MKLDNN_ELTWISE_ACTIVATION
*/
#define DEFINE_MKLDNN_ELTWISE_ACTIVATION(ACT_TYPE, ALPHA, BWD_ALPHA) \
class MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE) \
: public MKLDNNEltwiseActivation { \
private: \
static const std::string name; \
static const float alpha; \
static const float bwdAlpha; \
\
public: \
const std::string& getName() const { return name; } \
float getAlpha() const { return alpha; } \
float getBwdAlpha() const { return bwdAlpha; } \
}; \
const std::string MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE)::name = \
"mkldnn_" #ACT_TYPE; \
const float MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE)::alpha = ALPHA; \
const float MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE)::bwdAlpha = BWD_ALPHA; \
static InitFunction __reg_activation__mkldnn_##ACT_TYPE([] { \
gMKLDNNActivationRegistrar \
.registerClass<MKLDNN_ACTIVATION_CLASS_NAME(ACT_TYPE)>( \
"mkldnn_" #ACT_TYPE); \
});
/**
* @brief MKLDNN Relu Activation.
* Actually mkldnn_relu is Leaky Relu.
* f(x) = x (x >= 0)
* f(x) = negative_slope * x (x < 0)
* @note the negative_slope should be -0.f in forward
*/
DEFINE_MKLDNN_ELTWISE_ACTIVATION(relu, -0.f, 0.f)
/**
* @brief MKLDNN Tanh Activation.
*/
DEFINE_MKLDNN_ELTWISE_ACTIVATION(tanh, 0.f, 0.f)
/**
* @brief MKLDNN ELU(Exponential Linear Unit) Activation.
* f(x) = x (x >= 0)
* f(x) = negative_slope * (exp(x) - 1) (x < 0)
*/
DEFINE_MKLDNN_ELTWISE_ACTIVATION(elu, 0.f, 0.f)
ActivationFunction* MKLDNNActivation::create(const std::string& type) {
return gMKLDNNActivationRegistrar.createByType(type);
}
std::vector<std::string> MKLDNNActivation::getAllRegisteredTypes() {
std::vector<std::string> types;
gMKLDNNActivationRegistrar.forEachType(
[&](const std::string& type) { types.push_back(type); });
return types;
}
} // namespace paddle
| 41.363636 | 77 | 0.571978 | [
"vector"
] |
ac5f04dd9416cef6c425bab371ee6032bbbdd502 | 3,272 | cpp | C++ | source/aeonlog.cpp | AeonSplice/aeonsplice | 0228a4b69d798c020410e4b06fa7d51f5efaafc7 | [
"MIT"
] | null | null | null | source/aeonlog.cpp | AeonSplice/aeonsplice | 0228a4b69d798c020410e4b06fa7d51f5efaafc7 | [
"MIT"
] | 15 | 2016-09-09T03:46:00.000Z | 2017-01-31T20:14:56.000Z | source/aeonlog.cpp | AeonSplice/aeonsplice | 0228a4b69d798c020410e4b06fa7d51f5efaafc7 | [
"MIT"
] | null | null | null | #include "aeonlog.hpp"
// Don't include stuff above here. Because standards.
#include <iostream>
#include "aeonconfig.hpp"
#include "aeonutil.hpp"
using namespace std;
namespace aeon
{
bool isDebug = true;
bool overwriteLog = false;
std::string logLocation = "";
void overwriteLogFile()
{
if(overwriteLog)
{
FILE* logFile;
logFile = fopen(logLocation.c_str(),"w");
if(logFile==NULL)
{
std::cout << "ERROR - Failed to overwrite log file." << std::endl;
}
else
{
fclose(logFile);
}
}
}
void getLogSettings(Config * settings)
{
static bool overwritten = false;
isDebug = initKeyPair(settings, "debug", "debugging", false);
initKeyPair(settings, "debug", "debugInput", false);
overwriteLog = initKeyPair(settings, "debug", "overwriteLog", true);
if(overwriteLog && !overwritten)
overwriteLogFile();
overwritten = true;
}
void setLogFile(std::string file)
{
logLocation = file;
}
FILE* getLogFile()
{
FILE* logFile;
logFile = fopen(logLocation.c_str(),"a");
return logFile;
}
void log(std::string message)
{
if(isDebug)
{
std::cout << message << std::endl;
if(!logLocation.empty())
{
FILE* logFile;
logFile = fopen(logLocation.c_str(),"a");
if(logFile==NULL)
{
std::cout << "ERROR - Failed to write to log file." << std::endl;
}
else
{
std::string temp;
if(message.at(message.size()-1)!='\n')
{
temp = currentDateTime()+" - "+message+"\n";
}
else
{
temp = currentDateTime()+" - "+message;
}
fputs(temp.c_str(),logFile);
fclose(logFile);
}
}
}
else
{
std::cout << message << std::endl;
}
}
void log(const char* message)
{
log(toString(message));
}
void log(vector<char> message)
{
log(toString(message));
}
void log(string message, int mode)
{
// TODO: Utilize Configuration for verboseness.
switch(mode)
{
case AEON_FATAL:
log("FATAL - "+message);
break;
case AEON_ERROR:
log("ERROR - "+message);
break;
case AEON_WARNING:
log("WARNING - "+message);
break;
case AEON_INFO:
log("INFO - "+message);
break;
default:
log("Tried to use invalid log mode \""+toString(mode)+"\"", AEON_WARNING);
log("UNKNOWN - "+message);
break;
}
}
void log(const char* message, int mode)
{
log(toString(message), mode);
}
void log(vector<char> message, int mode)
{
log(toString(message), mode);
}
}
| 25.968254 | 86 | 0.460269 | [
"vector"
] |
ac5ff7f54ed24822b23c3ec377ffdbaaf5889795 | 2,181 | cpp | C++ | isis/src/base/objs/OriginalLabel/OriginalLabel.cpp | Kelvinrr/ISIS3 | 6e2df9c22d8d11564c0c3cda5d1606da58af547f | [
"CC0-1.0"
] | null | null | null | isis/src/base/objs/OriginalLabel/OriginalLabel.cpp | Kelvinrr/ISIS3 | 6e2df9c22d8d11564c0c3cda5d1606da58af547f | [
"CC0-1.0"
] | null | null | null | isis/src/base/objs/OriginalLabel/OriginalLabel.cpp | Kelvinrr/ISIS3 | 6e2df9c22d8d11564c0c3cda5d1606da58af547f | [
"CC0-1.0"
] | null | null | null | /** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <fstream>
#include <sstream>
#include <string>
#include "OriginalLabel.h"
#include "Application.h"
#include "PvlObject.h"
using namespace std;
namespace Isis {
/**
* Constructor for creating an original blob with a given name
*/
OriginalLabel::OriginalLabel() : Isis::Blob("IsisCube", "OriginalLabel") {
m_originalLabel.setTerminator("");
}
/**
* Constructor for creating an original blob with a given name and file to
* read labels from.
*
* @param file File to read labels from
*/
OriginalLabel::OriginalLabel(const QString &file) :
Isis::Blob("IsisCube", "OriginalLabel") {
Blob::Read(file);
}
/**
* Constructor for creating an original blob with a given name and Pvl
* container.
*
* @param pvl Pvl containing labels of the source
*/
OriginalLabel::OriginalLabel(Pvl pvl) : Isis::Blob("IsisCube", "OriginalLabel") {
m_originalLabel = pvl;
}
// Destructor
OriginalLabel::~OriginalLabel() {
}
/**
* Prepare labels for writing to the output cube.
*/
void OriginalLabel::WriteInit() {
ostringstream ostr;
if(p_nbytes > 0) ostr << std::endl;
// store labels
ostr << m_originalLabel;
string orglblStr = ostr.str();
int bytes = orglblStr.size();
// Copy label data to bytes variable
char *temp = p_buffer;
p_buffer = new char[p_nbytes+bytes];
if(temp != NULL) memcpy(p_buffer, temp, p_nbytes);
const char *ptr = orglblStr.c_str();
memcpy(&p_buffer[p_nbytes], (void *)ptr, bytes);
p_nbytes += bytes;
if(temp != NULL) delete [] temp;
}
/**
* Returns the labels in a Pvl object
*
* @return (Isis::Pvl) original labels
*/
Pvl OriginalLabel::ReturnLabels() {
Pvl pvl;
stringstream os;
for(int i = 0; i < p_nbytes; i++) os << p_buffer[i];
os >> pvl;
return pvl;
}
}
| 25.964286 | 83 | 0.657955 | [
"object"
] |
ac65c5eea7314ba8376ed69f7a8a588d0bed970b | 1,254 | cpp | C++ | PolyDock/PolyDock/src/pd/ecs/sys/root/DesktopSystem.cpp | Qt-Widgets/PolyDock | f32def214753ca0f6bab9968bc2bb5e451cb6e4f | [
"MIT"
] | 1 | 2021-01-10T06:43:03.000Z | 2021-01-10T06:43:03.000Z | PolyDock/PolyDock/src/pd/ecs/sys/root/DesktopSystem.cpp | Qt-Widgets/PolyDock | f32def214753ca0f6bab9968bc2bb5e451cb6e4f | [
"MIT"
] | null | null | null | PolyDock/PolyDock/src/pd/ecs/sys/root/DesktopSystem.cpp | Qt-Widgets/PolyDock | f32def214753ca0f6bab9968bc2bb5e451cb6e4f | [
"MIT"
] | null | null | null | #include <pd/pch/PCH.h>
#include <pd/ecs/sys/root/DesktopSystem.hpp>
#include <pd/ecs/cmp/root/Desktop.hpp>
using namespace ::pd::ecs::sys;
using namespace ::pd::ecs::cmp::root;
using namespace ::Eigen;
// ---------------------------------------------------------------------------------------------------------
void DesktopSystem::update(entt::registry& registry, entt::entity root) const
{
auto view = registry.view<Desktop>();
Expects(view.size() == 1);
for (auto entity : view)
{
auto& cmp = view.get<Desktop>(entity);
cmp.screens.clear();
Vector2i min{ 0, 0 };
Vector2i max{ 0, 0 };
for (QScreen* screen : qApp->screens())
{
QRect geometry = screen->geometry();
if (geometry.topLeft().x() < min.x())
min.x() = geometry.topLeft().x();
if (geometry.topLeft().y() < min.y())
min.y() = geometry.topLeft().y();
if (geometry.bottomRight().x() > max.x())
max.x() = geometry.bottomRight().x();
if (geometry.bottomRight().y() > max.y())
max.y() = geometry.bottomRight().y();
cmp.screens.push_back(AlignedBox2i{
Vector2i{geometry.topLeft().x(), geometry.topLeft().y()},
Vector2i{geometry.bottomRight().x(), geometry.bottomRight().y()} });
}
cmp.desktopSize = AlignedBox2i{ min, max };
}
} | 29.857143 | 108 | 0.578947 | [
"geometry"
] |
ac6a2d7bc28385ec4662b06f901d5f3cbf1b56d6 | 17,362 | cpp | C++ | copasi/bindings/common/downcast_common.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/bindings/common/downcast_common.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/bindings/common/downcast_common.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | // Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/common/downcast_common.cpp,v $
// $Revision: 1.3 $
// $Name: $
// $Author: shoops $
// $Date: 2012/06/21 16:46:55 $
// End CVS Header
// Copyright (C) 2012 - 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// These are the downcast rules for the non Java languages
// Out of some reason, Java does it differently
// here we add the declaration in alphabetic order so that we can use all function in
// other functions below without having to worry about the order
// CCopasiAbstractArray
struct swig_type_info*
GetDowncastSwigTypeForCCopasiAbstractArray(CCopasiAbstractArray* array);
// CCopasiContainer
struct swig_type_info*
GetDowncastSwigTypeForCCopasiContainer(CCopasiContainer* container);
// CCopasiMethod
struct swig_type_info*
GetDowncastSwigTypeForMethod(CCopasiMethod* method);
// CCopasiObject
struct swig_type_info*
GetDowncastSwigTypeForCCopasiObject(CCopasiObject* object);
// CObjectInterface
struct swig_type_info*
GetDowncastSwigTypeForCObjectInterface(CObjectInterface* objectInterface);
// CCopasiParameter
struct swig_type_info*
GetDowncastSwigTypeForCCopasiParameter(CCopasiParameter* parameter);
// CCopasiParameterGroup
struct swig_type_info*
GetDowncastSwigTypeForCCopasiParameterGroup(CCopasiParameterGroup* group);
// CCopasiProblem
struct swig_type_info*
GetDowncastSwigTypeForProblem(CCopasiProblem* problem);
// CCopasiTask
struct swig_type_info*
GetDowncastSwigTypeForTask(CCopasiTask* task);
// CEvaluationTree
struct swig_type_info*
GetDowncastSwigTypeForCEvaluationTree(CEvaluationTree* tree);
// CFitItem
struct swig_type_info*
GetDowncastSwigTypeForCFitItem(CFitItem* fitItem);
// CModelEntity
struct swig_type_info*
GetDowncastSwigTypeForCModelEntity(CModelEntity* entity);
// COptItem
struct swig_type_info*
GetDowncastSwigTypeForCOptItem(COptItem* optItem);
// COptMethod
struct swig_type_info*
GetDowncastSwigTypeForCOptMethod(COptMethod* optMethod);
// COptProblem
struct swig_type_info*
GetDowncastSwigTypeForCOptProblem(COptProblem* optProblem);
// COptTask
struct swig_type_info*
GetDowncastSwigTypeForCOptTask(COptTask* optTask);
/**
* @return the most specific Swig type for the given CCopasiAbstractArray object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCCopasiAbstractArray(CCopasiAbstractArray* array)
{
if (array == NULL) return SWIGTYPE_p_CCopasiAbstractArray;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiAbstractArray;
if (dynamic_cast<CCopasiArray*>(array))
{
pInfo = SWIGTYPE_p_CCopasiArray;
}
/* The following code no longer compiles out of some reason
else if (dynamic_cast<CCopasiMatrixInterface<CMatrix<C_FLOAT64> >*>(array))
{
pInfo = SWIGTYPE_p_CCopasiMatrixInterfaceTCMatrixTdouble_t_t;
}
*/
return pInfo;
}
/**
* @return the most specific Swig type for the given CCopasiContainer object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCCopasiContainer(CCopasiContainer* container)
{
if (container == NULL) return SWIGTYPE_p_CCopasiContainer;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiContainer;
if (dynamic_cast<CCopasiRootContainer*>(container))
{
pInfo = SWIGTYPE_p_CCopasiRootContainer;
}
else if (dynamic_cast<CCopasiDataModel*>(container))
{
pInfo = SWIGTYPE_p_CCopasiDataModel;
}
else if (dynamic_cast<CModelEntity*>(container))
{
pInfo = GetDowncastSwigTypeForCModelEntity(static_cast<CModelEntity*>(container));
}
else if (dynamic_cast<CCopasiParameter*>(container))
{
pInfo = GetDowncastSwigTypeForCCopasiParameter(static_cast<CCopasiParameter*>(container));
}
else if (dynamic_cast<CEvent*>(container))
{
pInfo = SWIGTYPE_p_CEvent;
}
else if (dynamic_cast<CEventAssignment*>(container))
{
pInfo = SWIGTYPE_p_CEventAssignment;
}
else if (dynamic_cast<CReference*>(container))
{
pInfo = SWIGTYPE_p_CReference;
}
else if (dynamic_cast<CBiologicalDescription*>(container))
{
pInfo = SWIGTYPE_p_CBiologicalDescription;
}
else if (dynamic_cast<CModification*>(container))
{
pInfo = SWIGTYPE_p_CModification;
}
else if (dynamic_cast<CCreator*>(container))
{
pInfo = SWIGTYPE_p_CCreator;
}
else if (dynamic_cast<CMIRIAMInfo*>(container))
{
pInfo = SWIGTYPE_p_CMIRIAMInfo;
}
else if (container->isNameVector())
{
if (dynamic_cast<CCopasiDataModelVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorT_CCopasiDataModel_t;
}
else if (dynamic_cast<TaskVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNT_CCopasiTask_t;
}
else if (dynamic_cast<ModelValueVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNT_CModelValue_t;
}
else if (dynamic_cast<MetabVectorNS*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNST_CMetab_t;
}
else if (dynamic_cast<CompartmentVectorNS*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNST_CCompartment_t;
}
else if (dynamic_cast<ReactionVectorNS*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNST_CReaction_t;
}
else if (dynamic_cast<CEvaluationTreeVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNT_CEvaluationTree_t;
}
else if (dynamic_cast<EventVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNT_CEvent_t;
}
else if (dynamic_cast<EventAssignmentVectorN*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorNT_CEventAssignment_t;
}
}
else if (container->isVector())
{
if (dynamic_cast<MoietyVector*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorT_CMoiety_t;
}
else if (dynamic_cast<MetabVector*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorT_CMetab_t;
}
else if (dynamic_cast<ReportItemVector*>(container))
{
#ifdef SWIGPERL
pInfo = SWIGTYPE_p_std__vectorT_CRegisteredObjectName_t;
#else
pInfo = SWIGTYPE_p_std__vectorT_CRegisteredObjectName_std__allocatorT_CRegisteredObjectName_t_t;
#endif // SWIGPERL
}
else if (dynamic_cast<ParameterVector*>(container))
{
#ifdef SWIGPERL
pInfo = SWIGTYPE_p_std__vectorT_CCopasiParameter_p_t;
#else
pInfo = SWIGTYPE_p_std__vectorT_CCopasiParameter_p_std__allocatorT_CCopasiParameter_p_t_t;
#endif // SWIGPERL
}
else if (dynamic_cast<CFunctionStdVector*>(container))
{
#ifdef SWIGPERL
pInfo = SWIGTYPE_p_std__vectorT_CFunction_p_t;
#else
pInfo = SWIGTYPE_p_std__vectorT_CFunction_p_std__allocatorT_CFunction_p_t_t;
#endif // SWIGPERL
}
else if (dynamic_cast<CChemEqElementVector*>(container))
{
pInfo = SWIGTYPE_p_CCopasiVectorT_CChemEqElement_t;
}
}
else if (dynamic_cast<CEvaluationTree*>(container))
{
pInfo = GetDowncastSwigTypeForCEvaluationTree(static_cast<CEvaluationTree*>(container));
}
else if (dynamic_cast<CCopasiTask*>(container))
{
pInfo = GetDowncastSwigTypeForTask(static_cast<CCopasiTask*>(container));
}
else if (dynamic_cast<CChemEq*>(container))
{
pInfo = SWIGTYPE_p_CChemEq;
}
else if (dynamic_cast<CChemEqElement*>(container))
{
pInfo = SWIGTYPE_p_CChemEqElement;
}
else if (dynamic_cast<CFunctionDB*>(container))
{
pInfo = SWIGTYPE_p_CFunctionDB;
}
else if (dynamic_cast<CFunctionParameter*>(container))
{
pInfo = SWIGTYPE_p_CFunctionParameter;
}
else if (dynamic_cast<CFunctionParameters*>(container))
{
pInfo = SWIGTYPE_p_CFunctionParameters;
}
else if (dynamic_cast<CMoiety*>(container))
{
pInfo = SWIGTYPE_p_CMoiety;
}
else if (dynamic_cast<CReaction*>(container))
{
pInfo = SWIGTYPE_p_CReaction;
}
else if (dynamic_cast<CArrayAnnotation*>(container))
{
pInfo = SWIGTYPE_p_CArrayAnnotation;
}
else if (dynamic_cast<CFittingPoint*>(container))
{
pInfo = SWIGTYPE_p_CFittingPoint;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CCopasiMethod object.
*/
struct swig_type_info*
GetDowncastSwigTypeForMethod(CCopasiMethod* method)
{
if (method == NULL) return SWIGTYPE_p_CCopasiMethod;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiMethod;
if (dynamic_cast<COptMethod*>(method))
{
pInfo = GetDowncastSwigTypeForCOptMethod(static_cast<COptMethod*>(method));
}
else if (dynamic_cast<CTrajectoryMethod*>(method))
{
pInfo = SWIGTYPE_p_CTrajectoryMethod;
}
else if (dynamic_cast<CScanMethod*>(method))
{
pInfo = SWIGTYPE_p_CScanMethod;
}
else if (dynamic_cast<CSteadyStateMethod*>(method))
{
pInfo = SWIGTYPE_p_CSteadyStateMethod;
}
else if (dynamic_cast<CMCAMethod*>(method))
{
pInfo = SWIGTYPE_p_CMCAMethod;
}
else if (dynamic_cast<CLyapMethod*>(method))
{
pInfo = SWIGTYPE_p_CLyapMethod;
}
else if (dynamic_cast<CSensMethod*>(method))
{
pInfo = SWIGTYPE_p_CSensMethod;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CCopasiObject object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCCopasiObject(CCopasiObject* object)
{
if (object == NULL) return SWIGTYPE_p_CCopasiObject;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiObject;
if (dynamic_cast<CCopasiContainer*>(object))
{
pInfo = GetDowncastSwigTypeForCCopasiContainer(static_cast<CCopasiContainer*>(object));
}
else if (dynamic_cast<CReportDefinition*>(object))
{
pInfo = SWIGTYPE_p_CReportDefinition;
}
else if (dynamic_cast<CCopasiStaticString*>(object))
{
if (dynamic_cast<CCopasiReportSeparator*>(object))
{
pInfo = SWIGTYPE_p_CCopasiReportSeparator;
}
else
{
pInfo = SWIGTYPE_p_CCopasiStaticString;
}
}
return pInfo;
}
// CObjectInterface
struct swig_type_info*
GetDowncastSwigTypeForCObjectInterface(CObjectInterface* objectInterface)
{
if (objectInterface == NULL) return SWIGTYPE_p_CObjectInterface;
struct swig_type_info* pInfo = SWIGTYPE_p_CObjectInterface;
if (dynamic_cast<CCopasiObject*>(objectInterface))
{
pInfo = GetDowncastSwigTypeForCCopasiObject(static_cast<CCopasiObject*>(objectInterface));
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CCopasiParameter object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCCopasiParameter(CCopasiParameter* parameter)
{
if (parameter == NULL) return SWIGTYPE_p_CCopasiParameter;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameter;
if (dynamic_cast<CCopasiParameterGroup*>(parameter))
{
pInfo = GetDowncastSwigTypeForCCopasiParameterGroup(static_cast<CCopasiParameterGroup*>(parameter));
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CCopasiParameterGroup object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCCopasiParameterGroup(CCopasiParameterGroup* group)
{
if (group == NULL) return SWIGTYPE_p_CCopasiParameterGroup;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiParameterGroup;
if (dynamic_cast<CCopasiMethod*>(group))
{
pInfo = GetDowncastSwigTypeForMethod(static_cast<CCopasiMethod*>(group));
}
else if (dynamic_cast<CCopasiProblem*>(group))
{
pInfo = GetDowncastSwigTypeForProblem(static_cast<CCopasiProblem*>(group));
}
else if (dynamic_cast<CExperiment*>(group))
{
pInfo = SWIGTYPE_p_CExperiment;
}
else if (dynamic_cast<CExperimentObjectMap*>(group))
{
pInfo = SWIGTYPE_p_CExperimentObjectMap;
}
else if (dynamic_cast<CExperimentSet*>(group))
{
pInfo = SWIGTYPE_p_CExperimentSet; //GetDowncastSwigTypeForCExperimentSet(static_cast<CExperimentSet*>(group));
}
else if (dynamic_cast<COptItem*>(group))
{
pInfo = GetDowncastSwigTypeForCOptItem(static_cast<COptItem*>(group));
}
return pInfo;
}
/**
* @return the most specific Swig type for the given Problem object.
*/
struct swig_type_info*
GetDowncastSwigTypeForProblem(CCopasiProblem* problem)
{
if (problem == NULL) return SWIGTYPE_p_CCopasiProblem;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiProblem;
if (dynamic_cast<COptProblem*>(problem))
{
pInfo = GetDowncastSwigTypeForCOptProblem(static_cast<COptProblem*>(problem));
}
else if (dynamic_cast<CTrajectoryProblem*>(problem))
{
pInfo = SWIGTYPE_p_CTrajectoryProblem;
}
else if (dynamic_cast<CScanProblem*>(problem))
{
pInfo = SWIGTYPE_p_CScanProblem;
}
else if (dynamic_cast<CSteadyStateProblem*>(problem))
{
pInfo = SWIGTYPE_p_CSteadyStateProblem;
}
else if (dynamic_cast<CMCAProblem*>(problem))
{
pInfo = SWIGTYPE_p_CMCAProblem;
}
else if (dynamic_cast<CLyapProblem*>(problem))
{
pInfo = SWIGTYPE_p_CLyapProblem;
}
else if (dynamic_cast<CSensProblem*>(problem))
{
pInfo = SWIGTYPE_p_CSensProblem;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given Task object.
*/
struct swig_type_info*
GetDowncastSwigTypeForTask(CCopasiTask* task)
{
if (task == NULL) return SWIGTYPE_p_CCopasiTask;
struct swig_type_info* pInfo = SWIGTYPE_p_CCopasiTask;
if (dynamic_cast<COptTask*>(task))
{
pInfo = GetDowncastSwigTypeForCOptTask(static_cast<COptTask*>(task));
}
else if (dynamic_cast<CTrajectoryTask*>(task))
{
pInfo = SWIGTYPE_p_CTrajectoryTask;
}
else if (dynamic_cast<CScanTask*>(task))
{
pInfo = SWIGTYPE_p_CScanTask;
}
else if (dynamic_cast<CSteadyStateTask*>(task))
{
pInfo = SWIGTYPE_p_CSteadyStateTask;
}
else if (dynamic_cast<CMCATask*>(task))
{
pInfo = SWIGTYPE_p_CMCATask;
}
else if (dynamic_cast<CLyapTask*>(task))
{
pInfo = SWIGTYPE_p_CLyapTask;
}
else if (dynamic_cast<CSensTask*>(task))
{
pInfo = SWIGTYPE_p_CSensTask;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CEvaluationTree object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCEvaluationTree(CEvaluationTree* tree)
{
if (tree == NULL) return SWIGTYPE_p_CEvaluationTree;
struct swig_type_info* pInfo = SWIGTYPE_p_CEvaluationTree;
if (dynamic_cast<CFunction*>(tree))
{
pInfo = SWIGTYPE_p_CFunction;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CFitItem object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCFitItem(CFitItem* fitItem)
{
if (fitItem == NULL) return SWIGTYPE_p_CFitItem;
struct swig_type_info* pInfo = SWIGTYPE_p_CFitItem;
if (dynamic_cast<CFitConstraint*>(fitItem))
{
pInfo = SWIGTYPE_p_CFitConstraint;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given CModelEntity object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCModelEntity(CModelEntity* entity)
{
if (entity == NULL) return SWIGTYPE_p_CModelEntity;
struct swig_type_info* pInfo = SWIGTYPE_p_CModelEntity;
if (dynamic_cast<CCompartment*>(entity))
{
pInfo = SWIGTYPE_p_CCompartment;
}
else if (dynamic_cast<CMetab*>(entity))
{
pInfo = SWIGTYPE_p_CMetab;
}
else if (dynamic_cast<CModelValue*>(entity))
{
pInfo = SWIGTYPE_p_CModelValue;
}
else if (dynamic_cast<CModel*>(entity))
{
pInfo = SWIGTYPE_p_CModel;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given COptItem object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCOptItem(COptItem* optItem)
{
if (optItem == NULL) return SWIGTYPE_p_COptItem;
struct swig_type_info* pInfo = SWIGTYPE_p_COptItem;
if (dynamic_cast<CFitItem*>(optItem))
{
pInfo = GetDowncastSwigTypeForCFitItem(static_cast<CFitItem*>(optItem));
}
return pInfo;
}
/**
* @return the most specific Swig type for the given COptMethod object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCOptMethod(COptMethod* optMethod)
{
if (optMethod == NULL) return SWIGTYPE_p_COptMethod;
struct swig_type_info* pInfo = SWIGTYPE_p_COptMethod;
if (dynamic_cast<CFitMethod*>(optMethod))
{
pInfo = SWIGTYPE_p_CFitMethod;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given COptProblem object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCOptProblem(COptProblem* optProblem)
{
if (optProblem == NULL) return SWIGTYPE_p_COptProblem;
struct swig_type_info* pInfo = SWIGTYPE_p_COptProblem;
if (dynamic_cast<CFitProblem*>(optProblem))
{
pInfo = SWIGTYPE_p_CFitProblem;
}
return pInfo;
}
/**
* @return the most specific Swig type for the given COptTask object.
*/
struct swig_type_info*
GetDowncastSwigTypeForCOptTask(COptTask* optTask)
{
if (optTask == NULL) return SWIGTYPE_p_COptTask;
struct swig_type_info* pInfo = SWIGTYPE_p_COptTask;
if (dynamic_cast<CFitTask*>(optTask))
{
pInfo = SWIGTYPE_p_CFitTask;
}
return pInfo;
}
| 26.108271 | 117 | 0.71835 | [
"object"
] |
ac74d7274ce445fb272f3860888690ed0fd8092f | 48,714 | cc | C++ | be/src/exec/parquet-column-readers.cc | michaelhkw/impala | 4aa8e2d5cf590d6366a600f15bed3e998ccc4031 | [
"Apache-2.0"
] | null | null | null | be/src/exec/parquet-column-readers.cc | michaelhkw/impala | 4aa8e2d5cf590d6366a600f15bed3e998ccc4031 | [
"Apache-2.0"
] | null | null | null | be/src/exec/parquet-column-readers.cc | michaelhkw/impala | 4aa8e2d5cf590d6366a600f15bed3e998ccc4031 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "parquet-column-readers.h"
#include <boost/scoped_ptr.hpp>
#include <string>
#include <sstream>
#include <gflags/gflags.h>
#include <gutil/strings/substitute.h>
#include "exec/hdfs-parquet-scanner.h"
#include "exec/parquet-metadata-utils.h"
#include "exec/parquet-scratch-tuple-batch.h"
#include "exec/read-write-util.h"
#include "gutil/bits.h"
#include "rpc/thrift-util.h"
#include "runtime/collection-value-builder.h"
#include "runtime/tuple-row.h"
#include "runtime/tuple.h"
#include "runtime/runtime-state.h"
#include "runtime/mem-pool.h"
#include "util/codec.h"
#include "util/debug-util.h"
#include "util/dict-encoding.h"
#include "util/rle-encoding.h"
#include "common/names.h"
// Provide a workaround for IMPALA-1658.
DEFINE_bool(convert_legacy_hive_parquet_utc_timestamps, false,
"When true, TIMESTAMPs read from files written by Parquet-MR (used by Hive) will "
"be converted from UTC to local time. Writes are unaffected.");
// Max data page header size in bytes. This is an estimate and only needs to be an upper
// bound. It is theoretically possible to have a page header of any size due to string
// value statistics, but in practice we'll have trouble reading string values this large.
// Also, this limit is in place to prevent impala from reading corrupt parquet files.
DEFINE_int32(max_page_header_size, 8*1024*1024, "max parquet page header size in bytes");
// Trigger debug action on every 128 tuples produced. This is useful in exercising the
// failure or cancellation path.
#ifndef NDEBUG
#define DEBUG_ACTION_TRIGGER (127)
#define SHOULD_TRIGGER_DEBUG_ACTION(x) ((x & DEBUG_ACTION_TRIGGER) == 0)
#else
#define SHOULD_TRIGGER_DEBUG_ACTION(x) (false)
#endif
namespace impala {
const string PARQUET_COL_MEM_LIMIT_EXCEEDED =
"ParquetColumnReader::$0() failed to allocate $1 bytes for $2.";
Status ParquetLevelDecoder::Init(const string& filename,
parquet::Encoding::type encoding, MemPool* cache_pool, int cache_size,
int max_level, int num_buffered_values, uint8_t** data, int* data_size) {
DCHECK_GE(num_buffered_values, 0);
encoding_ = encoding;
max_level_ = max_level;
num_buffered_values_ = num_buffered_values;
filename_ = filename;
RETURN_IF_ERROR(InitCache(cache_pool, cache_size));
// Return because there is no level data to read, e.g., required field.
if (max_level == 0) return Status::OK();
int32_t num_bytes = 0;
switch (encoding) {
case parquet::Encoding::RLE: {
Status status;
if (!ReadWriteUtil::Read(data, data_size, &num_bytes, &status)) {
return status;
}
if (num_bytes < 0) {
return Status(TErrorCode::PARQUET_CORRUPT_RLE_BYTES, filename, num_bytes);
}
int bit_width = Bits::Log2Ceiling64(max_level + 1);
Reset(*data, num_bytes, bit_width);
break;
}
case parquet::Encoding::BIT_PACKED:
num_bytes = BitUtil::Ceil(num_buffered_values, 8);
bit_reader_.Reset(*data, num_bytes);
break;
default: {
stringstream ss;
ss << "Unsupported encoding: " << encoding;
return Status(ss.str());
}
}
if (UNLIKELY(num_bytes < 0 || num_bytes > *data_size)) {
return Status(Substitute("Corrupt Parquet file '$0': $1 bytes of encoded levels but "
"only $2 bytes left in page", filename, num_bytes, data_size));
}
*data += num_bytes;
*data_size -= num_bytes;
return Status::OK();
}
Status ParquetLevelDecoder::InitCache(MemPool* pool, int cache_size) {
num_cached_levels_ = 0;
cached_level_idx_ = 0;
// Memory has already been allocated.
if (cached_levels_ != NULL) {
DCHECK_EQ(cache_size_, cache_size);
return Status::OK();
}
cached_levels_ = reinterpret_cast<uint8_t*>(pool->TryAllocate(cache_size));
if (cached_levels_ == NULL) {
return pool->mem_tracker()->MemLimitExceeded(
NULL, "Definition level cache", cache_size);
}
memset(cached_levels_, 0, cache_size);
cache_size_ = cache_size;
return Status::OK();
}
inline int16_t ParquetLevelDecoder::ReadLevel() {
bool valid;
uint8_t level;
if (encoding_ == parquet::Encoding::RLE) {
valid = Get(&level);
} else {
DCHECK_EQ(encoding_, parquet::Encoding::BIT_PACKED);
valid = bit_reader_.GetValue(1, &level);
}
return LIKELY(valid) ? level : HdfsParquetScanner::INVALID_LEVEL;
}
Status ParquetLevelDecoder::CacheNextBatch(int batch_size) {
DCHECK_LE(batch_size, cache_size_);
cached_level_idx_ = 0;
if (max_level_ > 0) {
if (UNLIKELY(!FillCache(batch_size, &num_cached_levels_))) {
return Status(decoding_error_code_, num_buffered_values_, filename_);
}
} else {
// No levels to read, e.g., because the field is required. The cache was
// already initialized with all zeros, so we can hand out those values.
DCHECK_EQ(max_level_, 0);
num_cached_levels_ = batch_size;
}
return Status::OK();
}
bool ParquetLevelDecoder::FillCache(int batch_size,
int* num_cached_levels) {
DCHECK(num_cached_levels != NULL);
int num_values = 0;
if (encoding_ == parquet::Encoding::RLE) {
while (true) {
// Add RLE encoded values by repeating the current value this number of times.
uint32_t num_repeats_to_set =
min<uint32_t>(repeat_count_, batch_size - num_values);
memset(cached_levels_ + num_values, current_value_, num_repeats_to_set);
num_values += num_repeats_to_set;
repeat_count_ -= num_repeats_to_set;
// Add remaining literal values, if any.
uint32_t num_literals_to_set =
min<uint32_t>(literal_count_, batch_size - num_values);
int num_values_end = min<uint32_t>(num_values + literal_count_, batch_size);
for (; num_values < num_values_end; ++num_values) {
bool valid = bit_reader_.GetValue(bit_width_, &cached_levels_[num_values]);
if (UNLIKELY(!valid || cached_levels_[num_values] > max_level_)) return false;
}
literal_count_ -= num_literals_to_set;
if (num_values == batch_size) break;
if (UNLIKELY(!NextCounts<int16_t>())) return false;
if (repeat_count_ > 0 && current_value_ > max_level_) return false;
}
} else {
DCHECK_EQ(encoding_, parquet::Encoding::BIT_PACKED);
for (; num_values < batch_size; ++num_values) {
bool valid = bit_reader_.GetValue(1, &cached_levels_[num_values]);
if (UNLIKELY(!valid || cached_levels_[num_values] > max_level_)) return false;
}
}
*num_cached_levels = num_values;
return true;
}
/// Per column type reader. If MATERIALIZED is true, the column values are materialized
/// into the slot described by slot_desc. If MATERIALIZED is false, the column values
/// are not materialized, but the position can be accessed.
template<typename T, bool MATERIALIZED>
class ScalarColumnReader : public BaseScalarColumnReader {
public:
ScalarColumnReader(HdfsParquetScanner* parent, const SchemaNode& node,
const SlotDescriptor* slot_desc)
: BaseScalarColumnReader(parent, node, slot_desc),
dict_decoder_init_(false) {
if (!MATERIALIZED) {
// We're not materializing any values, just counting them. No need (or ability) to
// initialize state used to materialize values.
DCHECK(slot_desc_ == NULL);
return;
}
DCHECK(slot_desc_ != NULL);
DCHECK_NE(slot_desc_->type().type, TYPE_BOOLEAN);
if (slot_desc_->type().type == TYPE_DECIMAL) {
fixed_len_size_ = ParquetPlainEncoder::DecimalSize(slot_desc_->type());
} else if (slot_desc_->type().type == TYPE_VARCHAR) {
fixed_len_size_ = slot_desc_->type().len;
} else {
fixed_len_size_ = -1;
}
needs_conversion_ = slot_desc_->type().type == TYPE_CHAR ||
// TODO: Add logic to detect file versions that have unconverted TIMESTAMP
// values. Currently all versions have converted values.
(FLAGS_convert_legacy_hive_parquet_utc_timestamps &&
slot_desc_->type().type == TYPE_TIMESTAMP &&
parent->file_version_.application == "parquet-mr");
}
virtual ~ScalarColumnReader() { }
virtual bool ReadValue(MemPool* pool, Tuple* tuple) {
return ReadValue<true>(pool, tuple);
}
virtual bool ReadNonRepeatedValue(MemPool* pool, Tuple* tuple) {
return ReadValue<false>(pool, tuple);
}
virtual bool NeedsSeedingForBatchedReading() const { return false; }
virtual bool ReadValueBatch(MemPool* pool, int max_values, int tuple_size,
uint8_t* tuple_mem, int* num_values) {
return ReadValueBatch<true>(pool, max_values, tuple_size, tuple_mem, num_values);
}
virtual bool ReadNonRepeatedValueBatch(MemPool* pool, int max_values, int tuple_size,
uint8_t* tuple_mem, int* num_values) {
return ReadValueBatch<false>(pool, max_values, tuple_size, tuple_mem, num_values);
}
virtual DictDecoderBase* GetDictionaryDecoder() {
return HasDictionaryDecoder() ? &dict_decoder_ : nullptr;
}
virtual bool NeedsConversion() { return NeedsConversionInline(); }
virtual bool NeedsValidation() { return NeedsValidationInline(); }
protected:
template<bool IN_COLLECTION>
inline bool ReadValue(MemPool* pool, Tuple* tuple) {
// NextLevels() should have already been called and def and rep levels should be in
// valid range.
DCHECK_GE(rep_level_, 0);
DCHECK_LE(rep_level_, max_rep_level());
DCHECK_GE(def_level_, 0);
DCHECK_LE(def_level_, max_def_level());
DCHECK_GE(def_level_, def_level_of_immediate_repeated_ancestor()) <<
"Caller should have called NextLevels() until we are ready to read a value";
if (MATERIALIZED) {
if (def_level_ >= max_def_level()) {
if (page_encoding_ == parquet::Encoding::PLAIN_DICTIONARY) {
if (!ReadSlot<true>(tuple, pool)) return false;
} else {
if (!ReadSlot<false>(tuple, pool)) return false;
}
} else {
tuple->SetNull(null_indicator_offset_);
}
}
return NextLevels<IN_COLLECTION>();
}
/// Implementation of the ReadValueBatch() functions specialized for this
/// column reader type. This function drives the reading of data pages and
/// caching of rep/def levels. Once a data page and cached levels are available,
/// it calls into a more specialized MaterializeValueBatch() for doing the actual
/// value materialization using the level caches.
template<bool IN_COLLECTION>
bool ReadValueBatch(MemPool* pool, int max_values, int tuple_size,
uint8_t* tuple_mem, int* num_values) {
// Repetition level is only present if this column is nested in a collection type.
if (!IN_COLLECTION) DCHECK_EQ(max_rep_level(), 0) << slot_desc()->DebugString();
if (IN_COLLECTION) DCHECK_GT(max_rep_level(), 0) << slot_desc()->DebugString();
int val_count = 0;
bool continue_execution = true;
while (val_count < max_values && !RowGroupAtEnd() && continue_execution) {
// Read next page if necessary.
if (num_buffered_values_ == 0) {
if (!NextPage()) {
continue_execution = parent_->parse_status_.ok();
continue;
}
}
// Fill def/rep level caches if they are empty.
int level_batch_size = min(parent_->state_->batch_size(), num_buffered_values_);
if (!def_levels_.CacheHasNext()) {
parent_->parse_status_.MergeStatus(def_levels_.CacheNextBatch(level_batch_size));
}
// We only need the repetition levels for populating the position slot since we
// are only populating top-level tuples.
if (IN_COLLECTION && pos_slot_desc_ != NULL && !rep_levels_.CacheHasNext()) {
parent_->parse_status_.MergeStatus(rep_levels_.CacheNextBatch(level_batch_size));
}
if (UNLIKELY(!parent_->parse_status_.ok())) return false;
// This special case is most efficiently handled here directly.
if (!MATERIALIZED && !IN_COLLECTION) {
int vals_to_add = min(def_levels_.CacheRemaining(), max_values - val_count);
val_count += vals_to_add;
def_levels_.CacheSkipLevels(vals_to_add);
num_buffered_values_ -= vals_to_add;
continue;
}
// Read data page and cached levels to materialize values.
int cache_start_idx = def_levels_.CacheCurrIdx();
uint8_t* next_tuple = tuple_mem + val_count * tuple_size;
int remaining_val_capacity = max_values - val_count;
int ret_val_count = 0;
if (page_encoding_ == parquet::Encoding::PLAIN_DICTIONARY) {
continue_execution = MaterializeValueBatch<IN_COLLECTION, true>(
pool, remaining_val_capacity, tuple_size, next_tuple, &ret_val_count);
} else {
continue_execution = MaterializeValueBatch<IN_COLLECTION, false>(
pool, remaining_val_capacity, tuple_size, next_tuple, &ret_val_count);
}
val_count += ret_val_count;
num_buffered_values_ -= (def_levels_.CacheCurrIdx() - cache_start_idx);
if (SHOULD_TRIGGER_DEBUG_ACTION(val_count)) {
continue_execution &= TriggerDebugAction();
}
}
*num_values = val_count;
return continue_execution;
}
/// Helper function for ReadValueBatch() above that performs value materialization.
/// It assumes a data page with remaining values is available, and that the def/rep
/// level caches have been populated.
/// For efficiency, the simple special case of !MATERIALIZED && !IN_COLLECTION is not
/// handled in this function.
template<bool IN_COLLECTION, bool IS_DICT_ENCODED>
bool MaterializeValueBatch(MemPool* pool, int max_values, int tuple_size,
uint8_t* tuple_mem, int* num_values) {
DCHECK(MATERIALIZED || IN_COLLECTION);
DCHECK_GT(num_buffered_values_, 0);
DCHECK(def_levels_.CacheHasNext());
if (IN_COLLECTION && pos_slot_desc_ != NULL) DCHECK(rep_levels_.CacheHasNext());
uint8_t* curr_tuple = tuple_mem;
int val_count = 0;
while (def_levels_.CacheHasNext()) {
Tuple* tuple = reinterpret_cast<Tuple*>(curr_tuple);
int def_level = def_levels_.CacheGetNext();
if (IN_COLLECTION) {
if (def_level < def_level_of_immediate_repeated_ancestor()) {
// A containing repeated field is empty or NULL. Skip the value but
// move to the next repetition level if necessary.
if (pos_slot_desc_ != NULL) rep_levels_.CacheGetNext();
continue;
}
if (pos_slot_desc_ != NULL) {
int rep_level = rep_levels_.CacheGetNext();
// Reset position counter if we are at the start of a new parent collection.
if (rep_level <= max_rep_level() - 1) pos_current_value_ = 0;
void* pos_slot = tuple->GetSlot(pos_slot_desc()->tuple_offset());
*reinterpret_cast<int64_t*>(pos_slot) = pos_current_value_++;
}
}
if (MATERIALIZED) {
if (def_level >= max_def_level()) {
bool continue_execution = ReadSlot<IS_DICT_ENCODED>(tuple, pool);
if (UNLIKELY(!continue_execution)) return false;
} else {
tuple->SetNull(null_indicator_offset_);
}
}
curr_tuple += tuple_size;
++val_count;
if (UNLIKELY(val_count == max_values)) break;
}
*num_values = val_count;
return true;
}
virtual Status CreateDictionaryDecoder(uint8_t* values, int size,
DictDecoderBase** decoder) {
if (!dict_decoder_.Reset(values, size, fixed_len_size_)) {
return Status(TErrorCode::PARQUET_CORRUPT_DICTIONARY, filename(),
slot_desc_->type().DebugString(), "could not decode dictionary");
}
dict_decoder_init_ = true;
*decoder = &dict_decoder_;
return Status::OK();
}
virtual bool HasDictionaryDecoder() {
return dict_decoder_init_;
}
virtual void ClearDictionaryDecoder() {
dict_decoder_init_ = false;
}
virtual Status InitDataPage(uint8_t* data, int size) {
// Data can be empty if the column contains all NULLs
DCHECK_GE(size, 0);
page_encoding_ = current_page_header_.data_page_header.encoding;
if (page_encoding_ != parquet::Encoding::PLAIN_DICTIONARY &&
page_encoding_ != parquet::Encoding::PLAIN) {
stringstream ss;
ss << "File '" << filename() << "' is corrupt: unexpected encoding: "
<< PrintEncoding(page_encoding_) << " for data page of column '"
<< schema_element().name << "'.";
return Status(ss.str());
}
// If slot_desc_ is NULL, dict_decoder_ is uninitialized
if (page_encoding_ == parquet::Encoding::PLAIN_DICTIONARY && slot_desc_ != NULL) {
if (!dict_decoder_init_) {
return Status("File corrupt. Missing dictionary page.");
}
RETURN_IF_ERROR(dict_decoder_.SetData(data, size));
}
// TODO: Perform filter selectivity checks here.
return Status::OK();
}
private:
/// Writes the next value into the appropriate destination slot in 'tuple' using pool
/// if necessary.
///
/// Returns false if execution should be aborted for some reason, e.g. parse_error_ is
/// set, the query is cancelled, or the scan node limit was reached. Otherwise returns
/// true.
template<bool IS_DICT_ENCODED>
inline bool ReadSlot(Tuple* tuple, MemPool* pool) {
void* slot = tuple->GetSlot(tuple_offset_);
T val;
T* val_ptr = NeedsConversionInline() ? &val : reinterpret_cast<T*>(slot);
if (IS_DICT_ENCODED) {
DCHECK_EQ(page_encoding_, parquet::Encoding::PLAIN_DICTIONARY);
if (UNLIKELY(!dict_decoder_.GetNextValue(val_ptr))) {
SetDictDecodeError();
return false;
}
} else {
DCHECK_EQ(page_encoding_, parquet::Encoding::PLAIN);
int encoded_len =
ParquetPlainEncoder::Decode<T>(data_, data_end_, fixed_len_size_, val_ptr);
if (UNLIKELY(encoded_len < 0)) {
SetPlainDecodeError();
return false;
}
data_ += encoded_len;
}
if (UNLIKELY(NeedsValidationInline() && !ValidateSlot(val_ptr, tuple))) {
return false;
}
if (UNLIKELY(NeedsConversionInline() &&
!tuple->IsNull(null_indicator_offset_) &&
!ConvertSlot(&val, reinterpret_cast<T*>(slot), pool))) {
return false;
}
return true;
}
/// Most column readers never require conversion, so we can avoid branches by
/// returning constant false. Column readers for types that require conversion
/// must specialize this function.
inline bool NeedsConversionInline() const {
DCHECK(!needs_conversion_);
return false;
}
/// Similar to NeedsConversion(), most column readers do not require validation,
/// so to avoid branches, we return constant false. In general, types where not
/// all possible bit representations of the data type are valid should be
/// validated.
inline bool NeedsValidationInline() const {
return false;
}
/// Converts and writes src into dst based on desc_->type()
bool ConvertSlot(const T* src, T* dst, MemPool* pool) {
DCHECK(false);
return false;
}
/// Sets error message and returns false if the slot value is invalid, e.g., due to
/// being out of the valid value range.
bool ValidateSlot(T* src, Tuple* tuple) const {
DCHECK(false);
return false;
}
/// Pull out slow-path Status construction code
void __attribute__((noinline)) SetDictDecodeError() {
parent_->parse_status_ = Status(TErrorCode::PARQUET_DICT_DECODE_FAILURE, filename(),
slot_desc_->type().DebugString(), stream_->file_offset());
}
void __attribute__((noinline)) SetPlainDecodeError() {
parent_->parse_status_ = Status(TErrorCode::PARQUET_CORRUPT_PLAIN_VALUE, filename(),
slot_desc_->type().DebugString(), stream_->file_offset());
}
/// Dictionary decoder for decoding column values.
DictDecoder<T> dict_decoder_;
/// True if dict_decoder_ has been initialized with a dictionary page.
bool dict_decoder_init_;
/// true if decoded values must be converted before being written to an output tuple.
bool needs_conversion_;
/// The size of this column with plain encoding for FIXED_LEN_BYTE_ARRAY, or
/// the max length for VARCHAR columns. Unused otherwise.
int fixed_len_size_;
};
template<>
inline bool ScalarColumnReader<StringValue, true>::NeedsConversionInline() const {
return needs_conversion_;
}
template<>
bool ScalarColumnReader<StringValue, true>::ConvertSlot(
const StringValue* src, StringValue* dst, MemPool* pool) {
DCHECK(slot_desc() != NULL);
DCHECK(slot_desc()->type().type == TYPE_CHAR);
int len = slot_desc()->type().len;
StringValue sv;
sv.len = len;
if (slot_desc()->type().IsVarLenStringType()) {
sv.ptr = reinterpret_cast<char*>(pool->TryAllocate(len));
if (UNLIKELY(sv.ptr == NULL)) {
string details = Substitute(PARQUET_COL_MEM_LIMIT_EXCEEDED, "ConvertSlot",
len, "StringValue");
parent_->parse_status_ =
pool->mem_tracker()->MemLimitExceeded(parent_->state_, details, len);
return false;
}
} else {
sv.ptr = reinterpret_cast<char*>(dst);
}
int unpadded_len = min(len, src->len);
memcpy(sv.ptr, src->ptr, unpadded_len);
StringValue::PadWithSpaces(sv.ptr, len, unpadded_len);
if (slot_desc()->type().IsVarLenStringType()) *dst = sv;
return true;
}
template<>
inline bool ScalarColumnReader<TimestampValue, true>::NeedsConversionInline() const {
return needs_conversion_;
}
template<>
bool ScalarColumnReader<TimestampValue, true>::ConvertSlot(
const TimestampValue* src, TimestampValue* dst, MemPool* pool) {
// Conversion should only happen when this flag is enabled.
DCHECK(FLAGS_convert_legacy_hive_parquet_utc_timestamps);
*dst = *src;
if (dst->HasDateAndTime()) dst->UtcToLocal();
return true;
}
template<>
inline bool ScalarColumnReader<TimestampValue, true>::NeedsValidationInline() const {
return true;
}
template<>
bool ScalarColumnReader<TimestampValue, true>::ValidateSlot(
TimestampValue* src, Tuple* tuple) const {
if (UNLIKELY(!src->IsValidDate())) {
ErrorMsg msg(TErrorCode::PARQUET_TIMESTAMP_OUT_OF_RANGE,
filename(), node_.element->name);
Status status = parent_->state_->LogOrReturnError(msg);
if (!status.ok()) {
parent_->parse_status_ = status;
return false;
}
tuple->SetNull(null_indicator_offset_);
}
return true;
}
class BoolColumnReader : public BaseScalarColumnReader {
public:
BoolColumnReader(HdfsParquetScanner* parent, const SchemaNode& node,
const SlotDescriptor* slot_desc)
: BaseScalarColumnReader(parent, node, slot_desc) {
if (slot_desc_ != NULL) DCHECK_EQ(slot_desc_->type().type, TYPE_BOOLEAN);
}
virtual ~BoolColumnReader() { }
virtual bool ReadValue(MemPool* pool, Tuple* tuple) {
return ReadValue<true>(pool, tuple);
}
virtual bool ReadNonRepeatedValue(MemPool* pool, Tuple* tuple) {
return ReadValue<false>(pool, tuple);
}
protected:
virtual Status CreateDictionaryDecoder(uint8_t* values, int size,
DictDecoderBase** decoder) {
DCHECK(false) << "Dictionary encoding is not supported for bools. Should never "
<< "have gotten this far.";
return Status::OK();
}
virtual bool HasDictionaryDecoder() {
// Decoder should never be created for bools.
return false;
}
virtual void ClearDictionaryDecoder() { }
virtual Status InitDataPage(uint8_t* data, int size) {
// Initialize bool decoder
bool_values_ = BitReader(data, size);
return Status::OK();
}
private:
template<bool IN_COLLECTION>
inline bool ReadValue(MemPool* pool, Tuple* tuple) {
DCHECK(slot_desc_ != NULL);
// Def and rep levels should be in valid range.
DCHECK_GE(rep_level_, 0);
DCHECK_LE(rep_level_, max_rep_level());
DCHECK_GE(def_level_, 0);
DCHECK_LE(def_level_, max_def_level());
DCHECK_GE(def_level_, def_level_of_immediate_repeated_ancestor()) <<
"Caller should have called NextLevels() until we are ready to read a value";
if (def_level_ >= max_def_level()) {
return ReadSlot<IN_COLLECTION>(tuple, pool);
} else {
// Null value
tuple->SetNull(null_indicator_offset_);
return NextLevels<IN_COLLECTION>();
}
}
/// Writes the next value into the next slot in the *tuple using pool if necessary.
/// Also advances def_level_ and rep_level_ via NextLevels().
///
/// Returns false if execution should be aborted for some reason, e.g. parse_error_ is
/// set, the query is cancelled, or the scan node limit was reached. Otherwise returns
/// true.
template<bool IN_COLLECTION>
inline bool ReadSlot(Tuple* tuple, MemPool* pool) {
void* slot = tuple->GetSlot(tuple_offset_);
if (!bool_values_.GetValue(1, reinterpret_cast<bool*>(slot))) {
parent_->parse_status_ = Status("Invalid bool column.");
return false;
}
return NextLevels<IN_COLLECTION>();
}
BitReader bool_values_;
};
bool ParquetColumnReader::TriggerDebugAction() {
Status status = parent_->TriggerDebugAction();
if (!status.ok()) {
if (!status.IsCancelled()) parent_->parse_status_.MergeStatus(status);
return false;
}
return true;
}
bool ParquetColumnReader::ReadValueBatch(MemPool* pool, int max_values,
int tuple_size, uint8_t* tuple_mem, int* num_values) {
int val_count = 0;
bool continue_execution = true;
while (val_count < max_values && !RowGroupAtEnd() && continue_execution) {
Tuple* tuple = reinterpret_cast<Tuple*>(tuple_mem + val_count * tuple_size);
if (def_level_ < def_level_of_immediate_repeated_ancestor()) {
// A containing repeated field is empty or NULL
continue_execution = NextLevels();
continue;
}
// Fill in position slot if applicable
if (pos_slot_desc_ != NULL) ReadPosition(tuple);
continue_execution = ReadValue(pool, tuple);
++val_count;
if (SHOULD_TRIGGER_DEBUG_ACTION(val_count)) {
continue_execution &= TriggerDebugAction();
}
}
*num_values = val_count;
return continue_execution;
}
bool ParquetColumnReader::ReadNonRepeatedValueBatch(MemPool* pool,
int max_values, int tuple_size, uint8_t* tuple_mem, int* num_values) {
int val_count = 0;
bool continue_execution = true;
while (val_count < max_values && !RowGroupAtEnd() && continue_execution) {
Tuple* tuple = reinterpret_cast<Tuple*>(tuple_mem + val_count * tuple_size);
continue_execution = ReadNonRepeatedValue(pool, tuple);
++val_count;
if (SHOULD_TRIGGER_DEBUG_ACTION(val_count)) {
continue_execution &= TriggerDebugAction();
}
}
*num_values = val_count;
return continue_execution;
}
void ParquetColumnReader::ReadPosition(Tuple* tuple) {
DCHECK(pos_slot_desc() != NULL);
// NextLevels() should have already been called
DCHECK_GE(rep_level_, 0);
DCHECK_GE(def_level_, 0);
DCHECK_GE(pos_current_value_, 0);
DCHECK_GE(def_level_, def_level_of_immediate_repeated_ancestor()) <<
"Caller should have called NextLevels() until we are ready to read a value";
void* slot = tuple->GetSlot(pos_slot_desc()->tuple_offset());
*reinterpret_cast<int64_t*>(slot) = pos_current_value_++;
}
// In 1.1, we had a bug where the dictionary page metadata was not set. Returns true
// if this matches those versions and compatibility workarounds need to be used.
static bool RequiresSkippedDictionaryHeaderCheck(
const ParquetFileVersion& v) {
if (v.application != "impala") return false;
return v.VersionEq(1,1,0) || (v.VersionEq(1,2,0) && v.is_impala_internal);
}
Status BaseScalarColumnReader::ReadPageHeader(bool peek,
parquet::PageHeader* next_page_header, uint32_t* next_header_size, bool* eos) {
*eos = false;
uint8_t* buffer;
int64_t buffer_size;
RETURN_IF_ERROR(stream_->GetBuffer(true, &buffer, &buffer_size));
// check for end of stream
if (buffer_size == 0) {
// The data pages contain fewer values than stated in the column metadata.
DCHECK(stream_->eosr());
DCHECK_LT(num_values_read_, metadata_->num_values);
// TODO for 2.3: node_.element->name isn't necessarily useful
ErrorMsg msg(TErrorCode::PARQUET_COLUMN_METADATA_INVALID,
metadata_->num_values, num_values_read_, node_.element->name, filename());
RETURN_IF_ERROR(parent_->state_->LogOrReturnError(msg));
*eos = true;
return Status::OK();
}
// We don't know the actual header size until the thrift object is deserialized. Loop
// until we successfully deserialize the header or exceed the maximum header size.
uint32_t header_size;
Status status;
while (true) {
header_size = buffer_size;
status = DeserializeThriftMsg(buffer, &header_size, true, next_page_header);
if (status.ok()) break;
if (buffer_size >= FLAGS_max_page_header_size) {
stringstream ss;
ss << "ParquetScanner: could not read data page because page header exceeded "
<< "maximum size of "
<< PrettyPrinter::Print(FLAGS_max_page_header_size, TUnit::BYTES);
status.AddDetail(ss.str());
return status;
}
// Didn't read entire header, increase buffer size and try again
int64_t new_buffer_size = max<int64_t>(buffer_size * 2, 1024);
status = Status::OK();
bool success = stream_->GetBytes(
new_buffer_size, &buffer, &new_buffer_size, &status, /* peek */ true);
if (!success) {
DCHECK(!status.ok());
return status;
}
DCHECK(status.ok());
// Even though we increased the allowed buffer size, the number of bytes
// read did not change. The header is not limited by the buffer space,
// so it must be incomplete in the file.
if (buffer_size == new_buffer_size) {
DCHECK_NE(new_buffer_size, 0);
return Status(TErrorCode::PARQUET_HEADER_EOF, filename());
}
DCHECK_GT(new_buffer_size, buffer_size);
buffer_size = new_buffer_size;
}
*next_header_size = header_size;
// Successfully deserialized current_page_header_
if (!peek && !stream_->SkipBytes(header_size, &status)) return status;
int data_size = next_page_header->compressed_page_size;
if (UNLIKELY(data_size < 0)) {
return Status(Substitute("Corrupt Parquet file '$0': negative page size $1 for "
"column '$2'", filename(), data_size, schema_element().name));
}
int uncompressed_size = next_page_header->uncompressed_page_size;
if (UNLIKELY(uncompressed_size < 0)) {
return Status(Substitute("Corrupt Parquet file '$0': negative uncompressed page "
"size $1 for column '$2'", filename(), uncompressed_size,
schema_element().name));
}
return Status::OK();
}
Status BaseScalarColumnReader::InitDictionary() {
// Peek at the next page header
bool eos;
parquet::PageHeader next_page_header;
uint32_t next_header_size;
DCHECK(!HasDictionaryDecoder());
RETURN_IF_ERROR(ReadPageHeader(true /* peek */, &next_page_header,
&next_header_size, &eos));
if (eos) return Status::OK();
// The dictionary must be the first data page, so if the first page
// is not a dictionary, then there is no dictionary.
if (next_page_header.type != parquet::PageType::DICTIONARY_PAGE) return Status::OK();
current_page_header_ = next_page_header;
Status status;
if (!stream_->SkipBytes(next_header_size, &status)) return status;
int data_size = current_page_header_.compressed_page_size;
if (slot_desc_ == nullptr) {
// Skip processing the dictionary page if we don't need to decode any values. In
// addition to being unnecessary, we are likely unable to successfully decode the
// dictionary values because we don't necessarily create the right type of scalar
// reader if there's no slot to read into (see CreateReader()).
if (!stream_->SkipBytes(data_size, &status)) return status;
return Status::OK();
}
if (node_.element->type == parquet::Type::BOOLEAN) {
return Status("Unexpected dictionary page. Dictionary page is not"
" supported for booleans.");
}
const parquet::DictionaryPageHeader* dict_header = nullptr;
if (current_page_header_.__isset.dictionary_page_header) {
dict_header = ¤t_page_header_.dictionary_page_header;
} else {
if (!RequiresSkippedDictionaryHeaderCheck(parent_->file_version_)) {
return Status("Dictionary page does not have dictionary header set.");
}
}
if (dict_header != nullptr &&
dict_header->encoding != parquet::Encoding::PLAIN &&
dict_header->encoding != parquet::Encoding::PLAIN_DICTIONARY) {
return Status("Only PLAIN and PLAIN_DICTIONARY encodings are supported "
"for dictionary pages.");
}
if (!stream_->ReadBytes(data_size, &data_, &status)) return status;
data_end_ = data_ + data_size;
uint8_t* dict_values = nullptr;
if (decompressor_.get() != nullptr) {
int uncompressed_size = current_page_header_.uncompressed_page_size;
dict_values = parent_->dictionary_pool_->TryAllocate(uncompressed_size);
if (UNLIKELY(dict_values == nullptr)) {
string details = Substitute(PARQUET_COL_MEM_LIMIT_EXCEEDED, "InitDictionary",
uncompressed_size, "dictionary");
return parent_->dictionary_pool_->mem_tracker()->MemLimitExceeded(
parent_->state_, details, uncompressed_size);
}
RETURN_IF_ERROR(decompressor_->ProcessBlock32(true, data_size, data_,
&uncompressed_size, &dict_values));
VLOG_FILE << "Decompressed " << data_size << " to " << uncompressed_size;
if (current_page_header_.uncompressed_page_size != uncompressed_size) {
return Status(Substitute("Error decompressing dictionary page in file '$0'. "
"Expected $1 uncompressed bytes but got $2", filename(),
current_page_header_.uncompressed_page_size, uncompressed_size));
}
data_size = uncompressed_size;
} else {
if (current_page_header_.uncompressed_page_size != data_size) {
return Status(Substitute("Error reading dictionary page in file '$0'. "
"Expected $1 bytes but got $2", filename(),
current_page_header_.uncompressed_page_size, data_size));
}
// Copy dictionary from io buffer (which will be recycled as we read
// more data) to a new buffer
dict_values = parent_->dictionary_pool_->TryAllocate(data_size);
if (UNLIKELY(dict_values == nullptr)) {
string details = Substitute(PARQUET_COL_MEM_LIMIT_EXCEEDED, "InitDictionary",
data_size, "dictionary");
return parent_->dictionary_pool_->mem_tracker()->MemLimitExceeded(
parent_->state_, details, data_size);
}
memcpy(dict_values, data_, data_size);
}
DictDecoderBase* dict_decoder;
RETURN_IF_ERROR(CreateDictionaryDecoder(dict_values, data_size, &dict_decoder));
if (dict_header != nullptr &&
dict_header->num_values != dict_decoder->num_entries()) {
return Status(TErrorCode::PARQUET_CORRUPT_DICTIONARY, filename(),
slot_desc_->type().DebugString(),
Substitute("Expected $0 entries but data contained $1 entries",
dict_header->num_values, dict_decoder->num_entries()));
}
return Status::OK();
}
Status BaseScalarColumnReader::ReadDataPage() {
// We're about to move to the next data page. The previous data page is
// now complete, pass along the memory allocated for it.
parent_->scratch_batch_->mem_pool()->AcquireData(decompressed_data_pool_.get(), false);
// Read the next data page, skipping page types we don't care about.
// We break out of this loop on the non-error case (a data page was found or we read all
// the pages).
while (true) {
DCHECK_EQ(num_buffered_values_, 0);
if (num_values_read_ == metadata_->num_values) {
// No more pages to read
// TODO: should we check for stream_->eosr()?
break;
} else if (num_values_read_ > metadata_->num_values) {
ErrorMsg msg(TErrorCode::PARQUET_COLUMN_METADATA_INVALID,
metadata_->num_values, num_values_read_, node_.element->name, filename());
RETURN_IF_ERROR(parent_->state_->LogOrReturnError(msg));
return Status::OK();
}
bool eos;
uint32_t header_size;
RETURN_IF_ERROR(ReadPageHeader(false /* peek */, ¤t_page_header_,
&header_size, &eos));
if (eos) return Status::OK();
if (current_page_header_.type == parquet::PageType::DICTIONARY_PAGE) {
// Any dictionary is already initialized, as InitDictionary has already
// been called. There are two possibilities:
// 1. The parquet file has two dictionary pages
// OR
// 2. The parquet file does not have the dictionary as the first data page.
// Both are errors in the parquet file.
if (HasDictionaryDecoder()) {
return Status(Substitute("Corrupt Parquet file '$0': multiple dictionary pages "
"for column '$1'", filename(), schema_element().name));
} else {
return Status(Substitute("Corrupt Parquet file: '$0': dictionary page for "
"column '$1' is not the first page", filename(), schema_element().name));
}
}
Status status;
int data_size = current_page_header_.compressed_page_size;
if (current_page_header_.type != parquet::PageType::DATA_PAGE) {
// We can safely skip non-data pages
if (!stream_->SkipBytes(data_size, &status)) return status;
continue;
}
// Read Data Page
// TODO: when we start using page statistics, we will need to ignore certain corrupt
// statistics. See IMPALA-2208 and PARQUET-251.
if (!stream_->ReadBytes(data_size, &data_, &status)) return status;
data_end_ = data_ + data_size;
int num_values = current_page_header_.data_page_header.num_values;
if (num_values < 0) {
return Status(Substitute("Error reading data page in Parquet file '$0'. "
"Invalid number of values in metadata: $1", filename(), num_values));
}
num_buffered_values_ = num_values;
num_values_read_ += num_buffered_values_;
int uncompressed_size = current_page_header_.uncompressed_page_size;
if (decompressor_.get() != NULL) {
SCOPED_TIMER(parent_->decompress_timer_);
uint8_t* decompressed_buffer =
decompressed_data_pool_->TryAllocate(uncompressed_size);
if (UNLIKELY(decompressed_buffer == NULL)) {
string details = Substitute(PARQUET_COL_MEM_LIMIT_EXCEEDED, "ReadDataPage",
uncompressed_size, "decompressed data");
return decompressed_data_pool_->mem_tracker()->MemLimitExceeded(
parent_->state_, details, uncompressed_size);
}
RETURN_IF_ERROR(decompressor_->ProcessBlock32(true,
current_page_header_.compressed_page_size, data_, &uncompressed_size,
&decompressed_buffer));
VLOG_FILE << "Decompressed " << current_page_header_.compressed_page_size
<< " to " << uncompressed_size;
if (current_page_header_.uncompressed_page_size != uncompressed_size) {
return Status(Substitute("Error decompressing data page in file '$0'. "
"Expected $1 uncompressed bytes but got $2", filename(),
current_page_header_.uncompressed_page_size, uncompressed_size));
}
data_ = decompressed_buffer;
data_size = current_page_header_.uncompressed_page_size;
data_end_ = data_ + data_size;
} else {
DCHECK_EQ(metadata_->codec, parquet::CompressionCodec::UNCOMPRESSED);
if (current_page_header_.compressed_page_size != uncompressed_size) {
return Status(Substitute("Error reading data page in file '$0'. "
"Expected $1 bytes but got $2", filename(),
current_page_header_.compressed_page_size, uncompressed_size));
}
}
// Initialize the repetition level data
RETURN_IF_ERROR(rep_levels_.Init(filename(),
current_page_header_.data_page_header.repetition_level_encoding,
parent_->level_cache_pool_.get(), parent_->state_->batch_size(),
max_rep_level(), num_buffered_values_,
&data_, &data_size));
// Initialize the definition level data
RETURN_IF_ERROR(def_levels_.Init(filename(),
current_page_header_.data_page_header.definition_level_encoding,
parent_->level_cache_pool_.get(), parent_->state_->batch_size(),
max_def_level(), num_buffered_values_, &data_, &data_size));
// Data can be empty if the column contains all NULLs
RETURN_IF_ERROR(InitDataPage(data_, data_size));
break;
}
return Status::OK();
}
template<bool ADVANCE_REP_LEVEL>
bool BaseScalarColumnReader::NextLevels() {
if (!ADVANCE_REP_LEVEL) DCHECK_EQ(max_rep_level(), 0) << slot_desc()->DebugString();
if (UNLIKELY(num_buffered_values_ == 0)) {
if (!NextPage()) return parent_->parse_status_.ok();
}
--num_buffered_values_;
// Definition level is not present if column and any containing structs are required.
def_level_ = max_def_level() == 0 ? 0 : def_levels_.ReadLevel();
// The compiler can optimize these two conditions into a single branch by treating
// def_level_ as unsigned.
if (UNLIKELY(def_level_ < 0 || def_level_ > max_def_level())) {
parent_->parse_status_.MergeStatus(Status(Substitute("Corrupt Parquet file '$0': "
"invalid def level $1 > max def level $2 for column '$3'", filename(),
def_level_, max_def_level(), schema_element().name)));
return false;
}
if (ADVANCE_REP_LEVEL && max_rep_level() > 0) {
// Repetition level is only present if this column is nested in any collection type.
rep_level_ = rep_levels_.ReadLevel();
// Reset position counter if we are at the start of a new parent collection.
if (rep_level_ <= max_rep_level() - 1) pos_current_value_ = 0;
}
return parent_->parse_status_.ok();
}
bool BaseScalarColumnReader::NextPage() {
parent_->assemble_rows_timer_.Stop();
parent_->parse_status_ = ReadDataPage();
if (UNLIKELY(!parent_->parse_status_.ok())) return false;
if (num_buffered_values_ == 0) {
rep_level_ = HdfsParquetScanner::ROW_GROUP_END;
def_level_ = HdfsParquetScanner::INVALID_LEVEL;
pos_current_value_ = HdfsParquetScanner::INVALID_POS;
return false;
}
parent_->assemble_rows_timer_.Start();
return true;
}
bool CollectionColumnReader::NextLevels() {
DCHECK(!children_.empty());
DCHECK_LE(rep_level_, new_collection_rep_level());
for (int c = 0; c < children_.size(); ++c) {
do {
// TODO(skye): verify somewhere that all column readers are at end
if (!children_[c]->NextLevels()) return false;
} while (children_[c]->rep_level() > new_collection_rep_level());
}
UpdateDerivedState();
return true;
}
bool CollectionColumnReader::ReadValue(MemPool* pool, Tuple* tuple) {
DCHECK_GE(rep_level_, 0);
DCHECK_GE(def_level_, 0);
DCHECK_GE(def_level_, def_level_of_immediate_repeated_ancestor()) <<
"Caller should have called NextLevels() until we are ready to read a value";
if (tuple_offset_ == -1) {
return CollectionColumnReader::NextLevels();
} else if (def_level_ >= max_def_level()) {
return ReadSlot(tuple, pool);
} else {
// Null value
tuple->SetNull(null_indicator_offset_);
return CollectionColumnReader::NextLevels();
}
}
bool CollectionColumnReader::ReadNonRepeatedValue(
MemPool* pool, Tuple* tuple) {
return CollectionColumnReader::ReadValue(pool, tuple);
}
bool CollectionColumnReader::ReadSlot(Tuple* tuple, MemPool* pool) {
DCHECK(!children_.empty());
DCHECK_LE(rep_level_, new_collection_rep_level());
// Recursively read the collection into a new CollectionValue.
CollectionValue* coll_slot = reinterpret_cast<CollectionValue*>(
tuple->GetSlot(tuple_offset_));
*coll_slot = CollectionValue();
CollectionValueBuilder builder(
coll_slot, *slot_desc_->collection_item_descriptor(), pool, parent_->state_);
bool continue_execution = parent_->AssembleCollection(
children_, new_collection_rep_level(), &builder);
if (!continue_execution) return false;
// AssembleCollection() advances child readers, so we don't need to call NextLevels()
UpdateDerivedState();
return true;
}
void CollectionColumnReader::UpdateDerivedState() {
// We don't need to cap our def_level_ at max_def_level(). We always check def_level_
// >= max_def_level() to check if the collection is defined.
// TODO(skye): consider capping def_level_ at max_def_level()
def_level_ = children_[0]->def_level();
rep_level_ = children_[0]->rep_level();
// All children should have been advanced to the beginning of the next collection
for (int i = 0; i < children_.size(); ++i) {
DCHECK_EQ(children_[i]->rep_level(), rep_level_);
if (def_level_ < max_def_level()) {
// Collection not defined
FILE_CHECK_EQ(children_[i]->def_level(), def_level_);
} else {
// Collection is defined
FILE_CHECK_GE(children_[i]->def_level(), max_def_level());
}
}
if (RowGroupAtEnd()) {
// No more values
pos_current_value_ = HdfsParquetScanner::INVALID_POS;
} else if (rep_level_ <= max_rep_level() - 2) {
// Reset position counter if we are at the start of a new parent collection (i.e.,
// the current collection is the first item in a new parent collection).
pos_current_value_ = 0;
}
}
ParquetColumnReader* ParquetColumnReader::Create(const SchemaNode& node,
bool is_collection_field, const SlotDescriptor* slot_desc, HdfsParquetScanner* parent) {
ParquetColumnReader* reader = NULL;
if (is_collection_field) {
// Create collection reader (note this handles both NULL and non-NULL 'slot_desc')
reader = new CollectionColumnReader(parent, node, slot_desc);
} else if (slot_desc != NULL) {
// Create the appropriate ScalarColumnReader type to read values into 'slot_desc'
switch (slot_desc->type().type) {
case TYPE_BOOLEAN:
reader = new BoolColumnReader(parent, node, slot_desc);
break;
case TYPE_TINYINT:
reader = new ScalarColumnReader<int8_t, true>(parent, node, slot_desc);
break;
case TYPE_SMALLINT:
reader = new ScalarColumnReader<int16_t, true>(parent, node, slot_desc);
break;
case TYPE_INT:
reader = new ScalarColumnReader<int32_t, true>(parent, node, slot_desc);
break;
case TYPE_BIGINT:
reader = new ScalarColumnReader<int64_t, true>(parent, node, slot_desc);
break;
case TYPE_FLOAT:
reader = new ScalarColumnReader<float, true>(parent, node, slot_desc);
break;
case TYPE_DOUBLE:
reader = new ScalarColumnReader<double, true>(parent, node, slot_desc);
break;
case TYPE_TIMESTAMP:
reader = new ScalarColumnReader<TimestampValue, true>(parent, node, slot_desc);
break;
case TYPE_STRING:
case TYPE_VARCHAR:
case TYPE_CHAR:
reader = new ScalarColumnReader<StringValue, true>(parent, node, slot_desc);
break;
case TYPE_DECIMAL:
switch (slot_desc->type().GetByteSize()) {
case 4:
reader = new ScalarColumnReader<Decimal4Value, true>(
parent, node, slot_desc);
break;
case 8:
reader = new ScalarColumnReader<Decimal8Value, true>(
parent, node, slot_desc);
break;
case 16:
reader = new ScalarColumnReader<Decimal16Value, true>(
parent, node, slot_desc);
break;
}
break;
default:
DCHECK(false) << slot_desc->type().DebugString();
}
} else {
// Special case for counting scalar values (e.g. count(*), no materialized columns in
// the file, only materializing a position slot). We won't actually read any values,
// only the rep and def levels, so it doesn't matter what kind of reader we make.
reader = new ScalarColumnReader<int8_t, false>(parent, node, slot_desc);
}
return parent->obj_pool_.Add(reader);
}
}
| 38.815936 | 92 | 0.693435 | [
"object"
] |
ac87e555e262a0eb19f7c50fe6422de17f833299 | 2,251 | cpp | C++ | solutions/LeetCode/C++/225.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/225.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/225.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 4 ms submission
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
if (buf.size() == 0)
buf.push(x);
else
{
int sz = buf.size();
while (!buf.empty())
{
tmpbuf.push(buf.front());
buf.pop();
}
buf.push(x);
while (!tmpbuf.empty())
{
buf.push(tmpbuf.front());
tmpbuf.pop();
}
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if (buf.size() == 0)
return 0;
int x = buf.front();
buf.pop();
return x;
}
/** Get the top element. */
int top() {
return buf.empty() ? 0: buf.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return buf.empty();
}
private:
queue<int> buf;
queue<int> tmpbuf;
};
__________________________________________________________________________________________________
sample 8720 kb submission
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
if (Q.empty())
{
Q.push(x);
}
else
{
int qSize = Q.size();
Q.push(x);
while (qSize--)
{
Q.push(Q.front());
Q.pop();
}
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = Q.front();
Q.pop();
return x;
}
/** Get the top element. */
int top() {
if (!Q.empty())
return Q.front();
return -1;
}
/** Returns whether the stack is empty. */
bool empty() {
return Q.empty();
}
private:
queue<int> Q;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/
__________________________________________________________________________________________________
| 19.573913 | 98 | 0.555753 | [
"object"
] |
12cd41559dcddd58bea86cc0c36307a79f207f48 | 8,752 | cc | C++ | dense_map/geometry_mapper/src/interest_point.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | 1 | 2021-12-07T22:59:34.000Z | 2021-12-07T22:59:34.000Z | dense_map/geometry_mapper/src/interest_point.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | null | null | null | dense_map/geometry_mapper/src/interest_point.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The "ISAAC - Integrated System for Autonomous and Adaptive Caretaking
* platform" software is 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 <opencv2/xfeatures2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <interest_point.h> // from the isaac repo
#include <interest_point/matching.h> // from the astrobee repo
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
// SIFT is doing so much better than SURF for haz cam images.
DEFINE_string(refiner_feature_detector, "SIFT", "The feature detector to use. SIFT or SURF.");
DEFINE_int32(sift_nFeatures, 10000, "Number of SIFT features");
DEFINE_int32(sift_nOctaveLayers, 3, "Number of SIFT octave layers");
DEFINE_double(sift_contrastThreshold, 0.02,
"SIFT contrast threshold"); // decrease for more ip
DEFINE_double(sift_edgeThreshold, 10, "SIFT edge threshold");
DEFINE_double(sift_sigma, 1.6, "SIFT sigma");
namespace dense_map {
void detectFeatures(const cv::Mat& image, bool verbose,
// Outputs
cv::Mat* descriptors, Eigen::Matrix2Xd* keypoints) {
bool histogram_equalization = false;
// If using histogram equalization, need an extra image to store it
cv::Mat* image_ptr = const_cast<cv::Mat*>(&image);
cv::Mat hist_image;
if (histogram_equalization) {
cv::equalizeHist(image, hist_image);
image_ptr = &hist_image;
}
std::vector<cv::KeyPoint> storage;
if (FLAGS_refiner_feature_detector == "SIFT") {
cv::Ptr<cv::xfeatures2d::SIFT> sift =
cv::xfeatures2d::SIFT::create(FLAGS_sift_nFeatures, FLAGS_sift_nOctaveLayers, FLAGS_sift_contrastThreshold,
FLAGS_sift_edgeThreshold, FLAGS_sift_sigma);
sift->detect(image, storage);
sift->compute(image, storage, *descriptors);
} else if (FLAGS_refiner_feature_detector == "SURF") {
interest_point::FeatureDetector detector("SURF");
detector.Detect(*image_ptr, &storage, descriptors);
// Undo the shift in the detector
for (cv::KeyPoint& key : storage) {
key.pt.x += image.cols / 2.0;
key.pt.y += image.rows / 2.0;
}
} else {
LOG(FATAL) << "Unknown feature detector: " << FLAGS_refiner_feature_detector;
}
if (verbose) std::cout << "Features detected " << storage.size() << std::endl;
// Copy to data structures expected by subsequent code
keypoints->resize(2, storage.size());
Eigen::Vector2d output;
for (size_t j = 0; j < storage.size(); j++) {
keypoints->col(j) = Eigen::Vector2d(storage[j].pt.x, storage[j].pt.y);
}
}
// This really likes haz cam first and nav cam second
void matchFeatures(std::mutex* match_mutex, int left_image_index, int right_image_index,
cv::Mat const& left_descriptors, cv::Mat const& right_descriptors,
Eigen::Matrix2Xd const& left_keypoints, Eigen::Matrix2Xd const& right_keypoints, bool verbose,
// output
MATCH_PAIR* matches) {
std::vector<cv::DMatch> cv_matches;
interest_point::FindMatches(left_descriptors, right_descriptors, &cv_matches);
std::vector<cv::Point2f> left_vec;
std::vector<cv::Point2f> right_vec;
for (size_t j = 0; j < cv_matches.size(); j++) {
int left_ip_index = cv_matches.at(j).queryIdx;
int right_ip_index = cv_matches.at(j).trainIdx;
// Get the keypoints from the good matches
left_vec.push_back(cv::Point2f(left_keypoints.col(left_ip_index)[0], left_keypoints.col(left_ip_index)[1]));
right_vec.push_back(cv::Point2f(right_keypoints.col(right_ip_index)[0], right_keypoints.col(right_ip_index)[1]));
}
if (left_vec.empty()) return;
// These may need some tweaking but work reasonably well.
double ransacReprojThreshold = 20.0;
cv::Mat inlier_mask;
int maxIters = 10000;
double confidence = 0.8;
// cv::Mat H = cv::findHomography(left_vec, right_vec, cv::RANSAC,
// ransacReprojThreshold,
// inlier_mask, maxIters, confidence);
cv::Mat H =
cv::estimateAffine2D(left_vec, right_vec, inlier_mask, cv::RANSAC, ransacReprojThreshold, maxIters, confidence);
std::vector<InterestPoint> left_ip, right_ip;
for (size_t j = 0; j < cv_matches.size(); j++) {
int left_ip_index = cv_matches.at(j).queryIdx;
int right_ip_index = cv_matches.at(j).trainIdx;
if (inlier_mask.at<uchar>(j, 0) == 0) continue;
cv::Mat left_desc = left_descriptors.row(left_ip_index);
cv::Mat right_desc = right_descriptors.row(right_ip_index);
InterestPoint left;
left.setFromCvKeypoint(left_keypoints.col(left_ip_index), left_desc);
InterestPoint right;
right.setFromCvKeypoint(right_keypoints.col(right_ip_index), right_desc);
left_ip.push_back(left);
right_ip.push_back(right);
}
if (verbose) std::cout << "Number of matches: " << left_ip.size() << std::endl;
// Update the shared variable using a lock
match_mutex->lock();
*matches = std::make_pair(left_ip, right_ip);
match_mutex->unlock();
}
void writeIpRecord(std::ofstream& f, InterestPoint const& p) {
f.write(reinterpret_cast<const char*>(&(p.x)), sizeof(p.x));
f.write(reinterpret_cast<const char*>(&(p.y)), sizeof(p.y));
f.write(reinterpret_cast<const char*>(&(p.ix)), sizeof(p.ix));
f.write(reinterpret_cast<const char*>(&(p.iy)), sizeof(p.iy));
f.write(reinterpret_cast<const char*>(&(p.orientation)), sizeof(p.orientation));
f.write(reinterpret_cast<const char*>(&(p.scale)), sizeof(p.scale));
f.write(reinterpret_cast<const char*>(&(p.interest)), sizeof(p.interest));
f.write(reinterpret_cast<const char*>(&(p.polarity)), sizeof(p.polarity));
f.write(reinterpret_cast<const char*>(&(p.octave)), sizeof(p.octave));
f.write(reinterpret_cast<const char*>(&(p.scale_lvl)), sizeof(p.scale_lvl));
uint64_t size = p.size();
f.write(reinterpret_cast<const char*>((&size)), sizeof(uint64));
for (size_t i = 0; i < p.descriptor.size(); ++i)
f.write(reinterpret_cast<const char*>(&(p.descriptor[i])), sizeof(p.descriptor[i]));
}
// Write matches to disk
void writeMatchFile(std::string match_file, std::vector<InterestPoint> const& ip1,
std::vector<InterestPoint> const& ip2) {
std::ofstream f;
f.open(match_file.c_str(), std::ios::binary | std::ios::out);
std::vector<InterestPoint>::const_iterator iter1 = ip1.begin();
std::vector<InterestPoint>::const_iterator iter2 = ip2.begin();
uint64 size1 = ip1.size();
uint64 size2 = ip2.size();
f.write(reinterpret_cast<const char*>(&size1), sizeof(uint64));
f.write(reinterpret_cast<const char*>(&size2), sizeof(uint64));
for (; iter1 != ip1.end(); ++iter1) writeIpRecord(f, *iter1);
for (; iter2 != ip2.end(); ++iter2) writeIpRecord(f, *iter2);
f.close();
}
void saveImagesAndMatches(std::string const& left_prefix, std::string const& right_prefix,
std::pair<int, int> const& index_pair, MATCH_PAIR const& match_pair,
std::vector<cv::Mat> const& images) {
// Add 10000 to have them be listed nicely
std::ostringstream oss_left;
oss_left << left_prefix << "_image" << index_pair.first + 10000 << ".jpg";
std::string left_image_file = oss_left.str();
std::cout << "Writing: " << left_image_file << std::endl;
cv::imwrite(left_image_file, images[index_pair.first]);
std::ostringstream oss_right;
oss_right << right_prefix << "_image" << index_pair.second + 10000 << ".jpg";
std::string right_image_file = oss_right.str();
std::cout << "Writing: " << right_image_file << std::endl;
cv::imwrite(right_image_file, images[index_pair.second]);
std::string left_stem = boost::filesystem::path(left_image_file).stem().string();
std::string right_stem = boost::filesystem::path(right_image_file).stem().string();
std::string match_file = left_stem + "__" + right_stem + ".match";
std::cout << "Writing: " << left_image_file << ' ' << right_image_file << ' ' << match_file << std::endl;
writeMatchFile(match_file, match_pair.first, match_pair.second);
}
} // end namespace dense_map
| 41.875598 | 117 | 0.691271 | [
"vector"
] |
12cdcfabef6ccad08e17448333263904cc192e95 | 878 | cc | C++ | test/asyncworker.cc | ntoskrnl7/node-addon-api | 148fa2e4f71685e88ed7af7c4b2cbf3853d3960d | [
"MIT"
] | 13 | 2019-06-18T14:30:56.000Z | 2021-04-25T06:06:52.000Z | test/asyncworker.cc | ntoskrnl7/node-addon-api | 148fa2e4f71685e88ed7af7c4b2cbf3853d3960d | [
"MIT"
] | 7 | 2018-04-16T13:27:06.000Z | 2018-11-20T00:13:52.000Z | test/asyncworker.cc | ntoskrnl7/node-addon-api | 148fa2e4f71685e88ed7af7c4b2cbf3853d3960d | [
"MIT"
] | 4 | 2018-03-18T23:24:36.000Z | 2019-10-28T14:00:57.000Z | #include "napi.h"
using namespace Napi;
class TestWorker : public AsyncWorker {
public:
static void DoWork(const CallbackInfo& info) {
bool succeed = info[0].As<Boolean>();
Object resource = info[1].As<Object>();
Function cb = info[2].As<Function>();
Value data = info[3];
TestWorker* worker = new TestWorker(cb, "TestResource", resource);
worker->Receiver().Set("data", data);
worker->_succeed = succeed;
worker->Queue();
}
protected:
void Execute() override {
if (!_succeed) {
SetError("test error");
}
}
private:
TestWorker(Function cb, const char* resource_name, const Object& resource)
: AsyncWorker(cb, resource_name, resource) {}
bool _succeed;
};
Object InitAsyncWorker(Env env) {
Object exports = Object::New(env);
exports["doWork"] = Function::New(env, TestWorker::DoWork);
return exports;
}
| 23.72973 | 76 | 0.661731 | [
"object"
] |
12cf1f011c96bcf7fcff225377e29964e3bf7513 | 687 | cpp | C++ | cpp/6335.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/6335.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/6335.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
struct Info { int year, a, b; };
int main() {
fastio;
for (int c = 1, n; cin >> n && n; c++) {
vector<Info> v(n);
for (auto& [year, a, b] : v) cin >> year >> a >> b;
auto Sol = [&]() -> int {
for (int y = 0; y < 10000; y++) {
bool flag = 1;
for (const auto& [year, a, b] : v) {
if (y < a || (y - a) % (b - a) + a != year)
flag = 0;
}
if (flag) return y;
}
return -1;
};
auto res = Sol();
cout << "Case #" << c << ":\n";
if (res == -1) cout << "Unknown bugs detected." << "\n\n";
else cout << "The actual year is " << res << ".\n\n";
}
} | 22.9 | 60 | 0.465793 | [
"vector"
] |
12d5de0f4e690aac03361b641206d0eff29e142f | 895 | hpp | C++ | old/include/test/InputTest.hpp | edwino-stein/elrond-common | 145909bb883e9877e9de3325d2a9002639271200 | [
"Apache-2.0"
] | null | null | null | old/include/test/InputTest.hpp | edwino-stein/elrond-common | 145909bb883e9877e9de3325d2a9002639271200 | [
"Apache-2.0"
] | 47 | 2019-12-30T22:14:04.000Z | 2022-03-26T02:04:06.000Z | old/include/test/InputTest.hpp | edwino-stein/elrond-common | 145909bb883e9877e9de3325d2a9002639271200 | [
"Apache-2.0"
] | null | null | null | #if !defined _ELROND_TEST_INPUT_HPP
#define _ELROND_TEST_INPUT_HPP
#include "elrond_test_types.hpp"
namespace elrond {
namespace test {
class InputTest : public elrond::module::BaseInputModule {
protected:
using InputListenerCollection = std::vector<elrond::input::InputListener*>;
using InputListenerCollectionP = std::unique_ptr<InputListenerCollection>;
std::map<elrond::sizeT, InputListenerCollectionP> inputMap;
public:
void addInputListener(const elrond::sizeT key,
elrond::input::InputListener* listener) override;
void triggerInput(elrond::test::InputTriggerTest* trigger,
const elrond::word data);
};
}
}
#endif
| 30.862069 | 95 | 0.562011 | [
"vector"
] |
12ddf19aba7afa34ddfafd83cd7567c9c15e992e | 2,800 | cpp | C++ | src/FergilnadEngine/FergilnadSprite.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | src/FergilnadEngine/FergilnadSprite.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | src/FergilnadEngine/FergilnadSprite.cpp | anunez97/fergilnad-game-engine | 75528633d32aed41223e0f52d8d7715073d9210a | [
"MIT"
] | null | null | null | // Fergilnad Sprite
#include "FergilnadSprite.h"
#include "ModelManager.h"
#include "ShaderManager.h"
#include "TextureManager.h"
#include "ImageManager.h"
FergilnadSprite::FergilnadSprite(std::string imgKey)
:angle(0.0f), scaleX(1.0f), scaleY(1.0f), scalePX(1.0f), scalePY(1.0f), posX(0.0f), posY(0.0f)
{
Rect* r = new Rect(0.0f, 0.0f, ImageManager::Get(imgKey)->pImageRect->width, ImageManager::Get(imgKey)->pImageRect->height);
pGOSprite = new GraphicsObject_Sprite(ModelManager::Get("SpriteModel"), ShaderManager::Get("SpriteShader"), ImageManager::Get(imgKey), r);
Matrix Scale = Matrix(SCALE, 1.0f, 1.0f, 1.0f);
Matrix RotZ = Matrix(ROT_Z, 0.0f);
Matrix Trans = Matrix(TRANS, pGOSprite->origPosX, pGOSprite->origPosY, 0.0f);
centerX = pGOSprite->origPosX;
centerY = pGOSprite->origPosY;
Matrix world = Scale * RotZ * Trans;
pGOSprite->SetWorld(world);
delete r;
}
FergilnadSprite::~FergilnadSprite()
{
DebugMsg::out("Sprite destructor\n");
delete pGOSprite;
}
void FergilnadSprite::Render(Camera* cam)
{
pGOSprite->Render(cam);
}
void FergilnadSprite::SetAngle(float a)
{
angle = a;
Matrix world = Matrix(SCALE, scaleX * scalePX, scaleY * scalePY, 1.0f) * Matrix(ROT_Z, angle) * Matrix(TRANS, posX + centerX, posY + centerY, 0.0f);
pGOSprite->SetWorld(world);
}
void FergilnadSprite::SetCenter(float offsetx, float offsety)
{
centerX = offsetx;
centerY = offsety;
Matrix world = Matrix(SCALE, scaleX * scalePX, scaleY * scalePY, 1.0f) * Matrix(ROT_Z, angle) * Matrix(TRANS, posX + centerX, posY + centerY, 0.0f);
pGOSprite->SetWorld(world);
}
void FergilnadSprite::SetPosition(float x, float y)
{
posX = x;
posY = y;
Matrix world = Matrix(SCALE, scaleX * scalePX, scaleY * scalePY, 1.0f) * Matrix(ROT_Z, angle) * Matrix(TRANS, posX + centerX, posY + centerY, 0.0f);
pGOSprite->SetWorld(world);
}
void FergilnadSprite::SetScaleFactor(float scalex, float scaley)
{
scaleX = scalex;
scaleY = scaley;
Matrix world = Matrix(SCALE, scaleX * scalePX, scaleY * scalePY, 1.0f) * Matrix(ROT_Z, angle) * Matrix(TRANS, posX + centerX, posY + centerY, 0.0f);
pGOSprite->SetWorld(world);
}
void FergilnadSprite::SetScalePixel(float width, float height)
{
scalePX = width / pGOSprite->origWidth;
scalePY = height / pGOSprite->origHeight;
Matrix world = Matrix(SCALE, scaleX * scalePX, scaleY * scalePY, 1.0f) * Matrix(ROT_Z, angle) * Matrix(TRANS, posX + centerX, posY + centerY, 0.0f);
pGOSprite->SetWorld(world);
DebugMsg::out("scale pixel set\n");
}
float FergilnadSprite::GetAngle()
{
return angle;
}
float FergilnadSprite::GetWidth()
{
return pGOSprite->origWidth;
}
float FergilnadSprite::GetHeight()
{
return pGOSprite->origHeight;
} | 26.923077 | 150 | 0.688214 | [
"render"
] |
12e130115b4062e2064e7d75e7c7f78c35983933 | 74,615 | cc | C++ | src/python.cc | madhu-nvda/python_backend | 56727b5b78d5d04720eac718c5f3ef1b9d591a94 | [
"BSD-3-Clause"
] | null | null | null | src/python.cc | madhu-nvda/python_backend | 56727b5b78d5d04720eac718c5f3ef1b9d591a94 | [
"BSD-3-Clause"
] | null | null | null | src/python.cc | madhu-nvda/python_backend | 56727b5b78d5d04720eac718c5f3ef1b9d591a94 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020-2022, NVIDIA CORPORATION & AFFILIATES. 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.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 OWNER 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 <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/vfs.h>
#include <sys/wait.h>
#include <unistd.h>
#include <array>
#include <atomic>
#include <boost/functional/hash.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/thread/thread_time.hpp>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <functional>
#include <future>
#include <memory>
#include <numeric>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "infer_request.h"
#include "infer_response.h"
#include "ipc_message.h"
#include "message_queue.h"
#include "pb_env.h"
#include "pb_main_utils.h"
#include "pb_metric_reporter.h"
#include "pb_tensor.h"
#include "pb_utils.h"
#include "shm_manager.h"
#include "triton/backend/backend_common.h"
#include "triton/backend/backend_input_collector.h"
#include "triton/backend/backend_memory.h"
#include "triton/backend/backend_model.h"
#include "triton/backend/backend_model_instance.h"
#include "triton/common/triton_json.h"
#include "triton/core/tritonbackend.h"
#include "triton/core/tritonserver.h"
#define LOG_IF_EXCEPTION(X) \
do { \
try { \
(X); \
} \
catch (const PythonBackendException& pb_exception) { \
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, pb_exception.what()); \
} \
} while (false)
#define RESPOND_ALL_AND_RETURN_IF_ERROR(RESPONSES, RESPONSES_COUNT, X) \
do { \
TRITONSERVER_Error* raasnie_err__ = (X); \
if (raasnie_err__ != nullptr) { \
for (size_t ridx = 0; ridx < RESPONSES_COUNT; ++ridx) { \
if ((*RESPONSES)[ridx] != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
(*RESPONSES)[ridx], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
raasnie_err__), \
"failed to send error response"); \
(*RESPONSES)[ridx] = nullptr; \
} \
} \
TRITONSERVER_ErrorDelete(raasnie_err__); \
return; \
} \
} while (false)
#define RESPOND_ALL_AND_RETURN_IF_EXCEPTION(RESPONSES, RESPONSES_COUNT, X) \
do { \
try { \
(X); \
} \
catch (const PythonBackendException& exception) { \
TRITONSERVER_Error* raarie_err__ = TRITONSERVER_ErrorNew( \
TRITONSERVER_ERROR_INTERNAL, exception.what()); \
for (size_t ridx = 0; ridx < RESPONSES_COUNT; ++ridx) { \
if ((*RESPONSES)[ridx] != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
(*RESPONSES)[ridx], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
raarie_err__), \
"failed to send error response"); \
(*RESPONSES)[ridx] = nullptr; \
} \
} \
TRITONSERVER_ErrorDelete(raarie_err__); \
return; \
} \
} while (false)
#define RESPOND_AND_RETURN_IF_ERROR(REQUEST, X) \
do { \
TRITONSERVER_Error* rarie_err__ = (X); \
if (rarie_err__ != nullptr) { \
TRITONBACKEND_Response* rarie_response__ = nullptr; \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseNew(&rarie_response__, REQUEST), \
"failed to create response"); \
if (rarie_response__ != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
rarie_response__, TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
rarie_err__), \
"failed to send error response"); \
} \
return rarie_err__; \
} \
} while (false)
#define GUARDED_RESPOND_IF_ERROR(RESPONSES, IDX, X) \
do { \
if ((*RESPONSES)[IDX] != nullptr) { \
TRITONSERVER_Error* err__ = (X); \
if (err__ != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
(*RESPONSES)[IDX], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
err__), \
"failed to send error response"); \
(*RESPONSES)[IDX] = nullptr; \
TRITONSERVER_ErrorDelete(err__); \
} \
} \
} while (false)
#define GUARDED_RESPOND_IF_EXCEPTION(RESPONSES, IDX, X) \
do { \
if ((*RESPONSES)[IDX] != nullptr) { \
try { \
(X); \
} \
catch (const PythonBackendException& pb_exception) { \
TRITONSERVER_Error* err__ = TRITONSERVER_ErrorNew( \
TRITONSERVER_ERROR_INTERNAL, pb_exception.what()); \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
(*RESPONSES)[IDX], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
err__), \
"failed to send error response"); \
(*RESPONSES)[IDX] = nullptr; \
TRITONSERVER_ErrorDelete(err__); \
} \
} \
} while (false)
#define RETURN_IF_EXCEPTION(X) \
do { \
try { \
(X); \
} \
catch (const PythonBackendException& pb_exception) { \
TRITONSERVER_Error* rarie_err__ = TRITONSERVER_ErrorNew( \
TRITONSERVER_ERROR_INTERNAL, pb_exception.what()); \
return rarie_err__; \
} \
} while (false)
namespace triton { namespace backend { namespace python {
namespace bi = boost::interprocess;
struct BackendState {
std::string python_lib;
int64_t shm_default_byte_size;
int64_t shm_growth_byte_size;
int64_t stub_timeout_seconds;
int64_t shm_message_queue_size;
std::atomic<int> number_of_instance_inits;
std::string shared_memory_region_prefix;
std::unique_ptr<EnvironmentManager> env_manager;
};
class ModelState : public BackendModel {
public:
static TRITONSERVER_Error* Create(
TRITONBACKEND_Model* triton_model, ModelState** state);
// Get backend state
BackendState* StateForBackend() { return backend_state_; }
// Get the Python execution environment
std::string PythonExecutionEnv() { return python_execution_env_; }
// Force CPU only tensors
bool ForceCPUOnlyInputTensors() { return force_cpu_only_input_tensors_; }
private:
ModelState(TRITONBACKEND_Model* triton_model);
BackendState* backend_state_;
std::string python_execution_env_;
bool force_cpu_only_input_tensors_;
};
class ModelInstanceState : public BackendModelInstance {
ModelInstanceState(
ModelState* model_state, TRITONBACKEND_ModelInstance* model_instance);
TRITONBACKEND_Model* triton_model_;
bi::interprocess_mutex* health_mutex_;
std::unique_ptr<MessageQueue> stub_message_queue_;
std::unique_ptr<MessageQueue> parent_message_queue_;
off_t ipc_control_offset_;
std::string model_path_;
IPCControl* ipc_control_;
std::vector<std::future<void>> bls_futures_;
std::vector<TRITONSERVER_InferenceResponse*> bls_inference_responses_;
std::mutex bls_responses_mutex_;
std::unique_ptr<SharedMemory> shm_pool_;
std::string shm_region_name_;
off_t shm_reset_offset_;
std::vector<std::unique_ptr<InferResponse>> infer_responses_;
std::vector<std::unique_ptr<RequestExecutor>> request_executors_;
std::vector<std::future<void>> handles_;
// Stub process pid
pid_t stub_pid_;
// Parent process pid
pid_t parent_pid_;
bool initialized_;
// Path to python execution environment
std::string path_to_libpython_;
std::string path_to_activate_;
public:
static TRITONSERVER_Error* Create(
ModelState* model_state, TRITONBACKEND_ModelInstance* model_instance,
ModelInstanceState** model_instance_state);
~ModelInstanceState();
// Load Triton inputs to the appropriate Protobufs
TRITONSERVER_Error* GetInputTensor(
const uint32_t input_idx, Tensor* input_tensor_shm,
std::shared_ptr<PbTensor>& input_tensor, TRITONBACKEND_Request* request,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses);
void ProcessRequests(
TRITONBACKEND_Request** requests, const uint32_t request_count,
bool& restart, std::atomic<bool>& cleanup);
// Create the stub process.
TRITONSERVER_Error* SetupStubProcess();
TRITONSERVER_Error* SendMessageToStub(off_t message);
void CleanupBLSResponses();
void WaitForBLSRequestsToFinish();
// Checks whether the stub process is live
bool IsStubProcessAlive();
// Get a message from the stub process
TRITONSERVER_Error* ReceiveMessageFromStub(off_t& message);
// Get a message from the stub process
void SendMessageAndReceiveResponse(
off_t message, off_t& response, bool& restart,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses,
TRITONBACKEND_Request** requests, const uint32_t request_count);
// Responds to all the requests with an error message.
void RespondErrorToAllRequests(
const char* message,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses,
TRITONBACKEND_Request** requests, const uint32_t request_count);
// Kill stub process
void KillStubProcess();
// Start stub process
TRITONSERVER_Error* StartStubProcess();
// Reset the shared memory offset
void ResetSharedMemoryOffset();
void ExecuteBLSRequest(
std::unique_ptr<SharedMemory>& shm_pool, off_t message_offset,
std::atomic<bool>& cleanup);
};
ModelInstanceState::ModelInstanceState(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance)
: BackendModelInstance(model_state, triton_model_instance), stub_pid_(0),
initialized_(false)
{
}
TRITONSERVER_Error*
ModelInstanceState::Create(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance,
ModelInstanceState** state)
{
try {
*state = new ModelInstanceState(model_state, triton_model_instance);
}
catch (const BackendModelInstanceException& ex) {
RETURN_ERROR_IF_TRUE(
ex.err_ == nullptr, TRITONSERVER_ERROR_INTERNAL,
std::string("unexpected nullptr in BackendModelInstanceException"));
RETURN_IF_ERROR(ex.err_);
}
return nullptr;
}
void
ModelInstanceState::KillStubProcess()
{
kill(stub_pid_, SIGKILL);
int status;
waitpid(stub_pid_, &status, 0);
stub_pid_ = 0;
}
void
ModelInstanceState::WaitForBLSRequestsToFinish()
{
bls_futures_.clear();
}
void
ModelInstanceState::SendMessageAndReceiveResponse(
off_t message, off_t& response, bool& restart,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses,
TRITONBACKEND_Request** requests, const uint32_t request_count)
{
auto error = SendMessageToStub(message);
if (error != nullptr) {
restart = true;
RespondErrorToAllRequests(
TRITONSERVER_ErrorMessage(error), responses, requests, request_count);
return;
}
off_t response_message;
error = ReceiveMessageFromStub(response_message);
if (error != nullptr) {
restart = true;
RespondErrorToAllRequests(
TRITONSERVER_ErrorMessage(error), responses, requests, request_count);
return;
}
response = response_message;
}
TRITONSERVER_Error*
ModelInstanceState::SendMessageToStub(off_t message)
{
bool success = false;
while (!success) {
uint64_t timeout_miliseconds = 1000;
{
boost::posix_time::ptime timeout =
boost::get_system_time() +
boost::posix_time::milliseconds(timeout_miliseconds);
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_, timeout);
// Check if lock has been acquired.
if (lock) {
ipc_control_->stub_health = false;
} else {
// If it failed to obtain the lock, it means that the stub has been
// stuck or exited while holding the health mutex lock.
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, "Failed to obtain the health mutex.");
}
}
stub_message_queue_->Push(
message, timeout_miliseconds /* duration ms */, success);
if (!success && !IsStubProcessAlive()) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, "Stub process is not healthy.");
}
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelInstanceState::ReceiveMessageFromStub(off_t& message)
{
bool success = false;
while (!success) {
uint64_t timeout_miliseconds = 1000;
{
boost::posix_time::ptime timeout =
boost::get_system_time() +
boost::posix_time::milliseconds(timeout_miliseconds);
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_, timeout);
// Check if lock has been acquired.
if (lock) {
ipc_control_->stub_health = false;
} else {
// If it failed to obtain the lock, it means that the stub has been
// stuck or exited while holding the health mutex lock.
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, "Failed to obtain the health mutex.");
}
}
message = parent_message_queue_->Pop(
timeout_miliseconds /* duration ms */, success);
if (!success && !IsStubProcessAlive()) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, "Stub process is not healthy.");
}
}
return nullptr; // success
}
void
ModelInstanceState::RespondErrorToAllRequests(
const char* message,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses,
TRITONBACKEND_Request** requests, const uint32_t request_count)
{
for (uint32_t r = 0; r < request_count; ++r) {
if ((*responses)[r] == nullptr)
continue;
std::string err_message =
std::string(
"Failed to process the request(s) for model instance '" + Name() +
"', message: ") +
message;
TRITONSERVER_Error* err =
TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INTERNAL, err_message.c_str());
LOG_IF_ERROR(
TRITONBACKEND_ResponseSend(
(*responses)[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, err),
"failed sending response");
(*responses)[r] = nullptr;
TRITONSERVER_ErrorDelete(err);
}
}
void
ModelInstanceState::ResetSharedMemoryOffset()
{
shm_pool_->SetOffset(shm_reset_offset_);
}
void
ModelInstanceState::ExecuteBLSRequest(
std::unique_ptr<SharedMemory>& shm_pool, off_t message_offset,
std::atomic<bool>& cleanup)
{
ModelState* model_state = reinterpret_cast<ModelState*>(Model());
auto request_executor =
std::make_unique<RequestExecutor>(model_state->TritonServer());
std::unique_ptr<IPCMessage> ipc_message =
IPCMessage::LoadFromSharedMemory(shm_pool, message_offset);
bool is_response_batch_set = false;
ResponseBatch* response_batch;
TRITONSERVER_InferenceResponse* inference_response = nullptr;
try {
std::unique_ptr<IPCMessage> bls_response =
std::make_unique<IPCMessage>(shm_pool_, false /* inline_response */);
RequestBatch* request_batch;
shm_pool_->MapOffset((char**)&request_batch, ipc_message->Args());
bls_response->Command() = PYTHONSTUB_InferExecResponse;
ipc_message->RequestOffset() = bls_response->SharedMemoryOffset();
shm_pool_->Map(
(char**)&response_batch, sizeof(ResponseBatch), bls_response->Args());
response_batch->batch_size = 1;
response_batch->has_error = false;
response_batch->is_error_set = false;
response_batch->cleanup = false;
is_response_batch_set = true;
bool has_gpu_tensor = false;
PythonBackendException pb_exception(std::string{});
if (request_batch->batch_size == 1) {
std::unique_ptr<InferRequest> infer_request;
std::shared_ptr<std::mutex> cuda_ipc_mutex;
infer_request = InferRequest::LoadFromSharedMemory(
shm_pool_, request_batch->requests, cuda_ipc_mutex, cuda_ipc_mutex);
std::unique_ptr<InferResponse> infer_response;
// If the BLS inputs are in GPU an additional round trip between the
// stub process and the main process is required. The reason is that we
// need to first allocate the GPU memory from the memory pool and then
// ask the stub process to fill in those allocated buffers.
for (auto& input_tensor : infer_request->Inputs()) {
if (!input_tensor->IsCPU()) {
#ifdef TRITON_ENABLE_GPU
BackendMemory* backend_memory;
std::unique_ptr<BackendMemory> lbackend_memory;
has_gpu_tensor = true;
TRITONSERVER_Error* error = BackendMemory::Create(
Model()->TritonMemoryManager(),
{BackendMemory::AllocationType::GPU_POOL,
BackendMemory::AllocationType::GPU},
input_tensor->MemoryTypeId(), input_tensor->ByteSize(),
&backend_memory);
if (error != nullptr) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR, TRITONSERVER_ErrorMessage(error));
break;
}
lbackend_memory.reset(backend_memory);
input_tensor->SetBackendMemory(std::move(lbackend_memory), shm_pool_);
#endif // TRITON_ENABLE_GPU
}
}
// Wait for the extra round trip to complete. The stub process will fill
// in the data for the GPU tensors. If there is an error, the extra round
// trip must be still completed, otherwise the stub process will always be
// waiting for a message from the parent process.
if (has_gpu_tensor) {
bi::scoped_lock<bi::interprocess_mutex> lock{
*(ipc_message->ResponseMutex())};
ipc_message->ResponseCondition()->notify_all();
ipc_message->ResponseCondition()->wait(lock);
}
if (pb_exception.what() != nullptr) {
infer_response = request_executor->Infer(
infer_request, shm_pool_, &inference_response);
if (inference_response != nullptr) {
std::lock_guard<std::mutex> lock{bls_responses_mutex_};
bls_inference_responses_.push_back(inference_response);
}
Response* response;
shm_pool_->Map(
(char**)&response, sizeof(Response), response_batch->responses);
infer_response->SaveToSharedMemory(
shm_pool_, response, false /* copy_cpu */, true /* copy_gpu */);
} else {
throw pb_exception;
}
}
}
catch (const PythonBackendException& pb_exception) {
if (is_response_batch_set) {
response_batch->has_error = true;
off_t string_offset = 0;
LOG_IF_EXCEPTION(SaveStringToSharedMemory(
shm_pool_, string_offset, pb_exception.what()));
if (string_offset != 0) {
response_batch->is_error_set = true;
response_batch->error = string_offset;
}
} else {
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, pb_exception.what());
}
}
{
bi::scoped_lock<bi::interprocess_mutex> lock{
*(ipc_message->ResponseMutex())};
ipc_message->ResponseCondition()->notify_all();
}
request_executors_.emplace_back(std::move(request_executor));
}
void
ModelInstanceState::ProcessRequests(
TRITONBACKEND_Request** requests, const uint32_t request_count,
bool& restart, std::atomic<bool>& cleanup)
{
ModelState* model_state = reinterpret_cast<ModelState*>(Model());
int max_batch_size = model_state->MaxBatchSize();
std::string name = model_state->Name();
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("model ") + model_state->Name() + ", instance " + Name() +
", executing " + std::to_string(request_count) + " requests")
.c_str());
uint64_t exec_start_ns = 0;
SET_TIMESTAMP(exec_start_ns);
// For each request collect the total batch size for this inference
// execution. The batch-size, number of inputs, and size of each
// input has already been checked so don't need to do that here.
size_t total_batch_size = 0;
for (size_t i = 0; i < request_count; i++) {
// If we get a nullptr request then something is badly wrong. Fail
// and release all requests.
if (requests[i] == nullptr) {
RequestsRespondWithError(
requests, request_count,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"null request given to Python backend for '" + name + "'")
.c_str()));
return;
}
}
// We take the responsibility of the responses.
std::shared_ptr<std::vector<TRITONBACKEND_Response*>> responses(
new std::vector<TRITONBACKEND_Response*>());
responses->reserve(request_count);
PbMetricReporter reporter(
TritonModelInstance(), requests, request_count, responses);
reporter.SetExecStartNs(exec_start_ns);
for (size_t i = 0; i < request_count; i++) {
TRITONBACKEND_Response* response;
auto err = TRITONBACKEND_ResponseNew(&response, requests[i]);
if (err == nullptr) {
responses->emplace_back(response);
} else {
responses->emplace_back(nullptr);
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, "Fail to create response");
TRITONSERVER_ErrorDelete(err);
}
}
for (size_t i = 0; i < request_count; i++) {
if (max_batch_size > 0) {
// Retrieve the batch size from one of the inputs, if the model
// supports batching, the first dimension size is batch size
TRITONBACKEND_Input* input;
TRITONSERVER_Error* err =
TRITONBACKEND_RequestInputByIndex(requests[i], 0 /* index */, &input);
if (err == nullptr) {
const int64_t* shape;
err = TRITONBACKEND_InputProperties(
input, nullptr, nullptr, &shape, nullptr, nullptr, nullptr);
total_batch_size += shape[0];
}
if (err != nullptr) {
RESPOND_ALL_AND_RETURN_IF_ERROR(responses, request_count, err);
}
} else {
++total_batch_size;
}
}
// If there are no valid payloads then no need to run the inference.
if (total_batch_size == 0) {
return;
}
// Make sure the maximum batch size is not exceeded. The
// total_batch_size must be 1 for models that don't support batching
// (i.e. max_batch_size == 0). If max_batch_size is exceeded then
// scheduler has done something badly wrong so fail and release all
// requests.
if ((total_batch_size != 1) && (total_batch_size > (size_t)max_batch_size)) {
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"batch size " + std::to_string(total_batch_size) + " for '" +
name + "', max allowed is " + std::to_string(max_batch_size))
.c_str()));
}
std::unique_ptr<IPCMessage> ipc_message =
std::make_unique<IPCMessage>(shm_pool_, false /*inline_response*/);
ipc_message->Command() = PYTHONSTUB_CommandType::PYTHONSTUB_ExecuteRequest;
RequestBatch* request_batch;
off_t request_batch_offset;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
shm_pool_->Map(
(char**)&request_batch, sizeof(RequestBatch), request_batch_offset));
ipc_message->Args() = request_batch_offset;
request_batch->batch_size = request_count;
Request* requests_shm;
off_t requests_shm_offset;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
shm_pool_->Map(
(char**)&requests_shm, sizeof(Request) * request_count,
requests_shm_offset));
request_batch->requests = requests_shm_offset;
for (uint32_t r = 0; r < request_count; ++r) {
TRITONBACKEND_Request* request = requests[r];
Request* python_infer_request = &requests_shm[r];
uint32_t requested_input_count = 0;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
TRITONBACKEND_RequestInputCount(request, &requested_input_count));
uint32_t requested_output_count = 0;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
TRITONBACKEND_RequestOutputCount(request, &requested_output_count));
python_infer_request->requested_output_count = requested_output_count;
Tensor* input_tensors;
off_t input_tensors_offset;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
shm_pool_->Map(
(char**)&input_tensors, sizeof(Tensor) * requested_input_count,
input_tensors_offset));
python_infer_request->inputs = input_tensors_offset;
std::vector<std::shared_ptr<PbTensor>> pb_input_tensors;
for (size_t iidx = 0; iidx < requested_input_count; ++iidx) {
Tensor* input_tensor = &input_tensors[iidx];
std::shared_ptr<PbTensor> pb_input_tensor;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
GetInputTensor(
iidx, input_tensor, pb_input_tensor, request, responses));
pb_input_tensors.emplace_back(std::move(pb_input_tensor));
}
std::vector<std::string> requested_output_names;
// Append the list of requested outputs to the inference_request
for (size_t iidx = 0; iidx < requested_output_count; ++iidx) {
const char* requested_output_name;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
TRITONBACKEND_RequestOutputName(
request, iidx, &requested_output_name));
requested_output_names.emplace_back(requested_output_name);
}
// request id
const char* id;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count, TRITONBACKEND_RequestId(request, &id));
uint64_t correlation_id;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count,
TRITONBACKEND_RequestCorrelationId(request, &correlation_id));
uint32_t flags;
RESPOND_ALL_AND_RETURN_IF_ERROR(
responses, request_count, TRITONBACKEND_RequestFlags(request, &flags));
InferRequest infer_request(
id, correlation_id, pb_input_tensors, requested_output_names,
model_state->Name(), model_state->Version(), flags);
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
infer_request.SaveToSharedMemory(shm_pool_, python_infer_request));
}
uint64_t compute_start_ns = 0;
SET_TIMESTAMP(compute_start_ns);
reporter.SetComputeStartNs(compute_start_ns);
// This means that the stub process has exited and Python
// backend failed to restart the stub process.
if (stub_pid_ == 0) {
const char* error_message = "The stub process has exited unexpectedly.";
RespondErrorToAllRequests(
error_message, responses, requests, request_count);
return;
}
off_t response_message;
SendMessageAndReceiveResponse(
ipc_message->SharedMemoryOffset(), response_message, restart, responses,
requests, request_count);
if (restart) {
return;
}
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
ipc_message =
IPCMessage::LoadFromSharedMemory(shm_pool_, response_message));
// If the stub command is no longer PYTHONSTUB_InferExecRequest, it
// indicates that inference request exeuction has finished.
while (ipc_message->Command() ==
PYTHONSTUB_CommandType::PYTHONSTUB_InferExecRequest) {
off_t current_message = response_message;
// Launch the BLS request in a future.
bls_futures_.emplace_back(
std::async(std::launch::async, [this, current_message, &cleanup]() {
this->ExecuteBLSRequest(this->shm_pool_, current_message, cleanup);
}));
auto error = ReceiveMessageFromStub(response_message);
if (error != nullptr) {
restart = true;
RespondErrorToAllRequests(
TRITONSERVER_ErrorMessage(error), responses, requests, request_count);
return;
}
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
ipc_message =
IPCMessage::LoadFromSharedMemory(shm_pool_, response_message));
}
uint64_t compute_end_ns = 0;
SET_TIMESTAMP(compute_end_ns);
reporter.SetComputeEndNs(compute_end_ns);
// Parsing the request response
ResponseBatch* response_batch;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
shm_pool_->MapOffset((char**)&response_batch, ipc_message->Args()));
// If inference fails, release all the requests and send an error response.
// If inference fails at this stage, it usually indicates a bug in the model
// code
if (response_batch->has_error) {
if (response_batch->is_error_set) {
char* error_message;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
LoadStringFromSharedMemory(
shm_pool_, response_batch->error, error_message));
RespondErrorToAllRequests(
error_message, responses, requests, request_count);
} else {
const char* error_message =
"Failed to fetch the error in response batch.";
RespondErrorToAllRequests(
error_message, responses, requests, request_count);
}
return;
}
Response* responses_shm;
RESPOND_ALL_AND_RETURN_IF_EXCEPTION(
responses, request_count,
shm_pool_->MapOffset((char**)&responses_shm, response_batch->responses));
bool has_gpu_output = false;
// The vector that stores the tensor pairs for the tensors that the stub
// provides in GPU but the output buffer provided by Triton is in CPU.
std::vector<std::pair<std::shared_ptr<PbTensor>, std::pair<void*, uint32_t>>>
tensor_buffer_pairs;
for (uint32_t r = 0; r < request_count; ++r) {
TRITONBACKEND_Response* response = (*responses)[r];
TRITONBACKEND_Request* request = requests[r];
uint32_t requested_output_count = 0;
std::unique_ptr<InferResponse> infer_response;
try {
std::shared_ptr<std::mutex> cuda_ipc_mutex;
infer_response = InferResponse::LoadFromSharedMemory(
shm_pool_, response_batch->responses + sizeof(Response) * r,
cuda_ipc_mutex /* cuda_ipc_open_mutex */,
cuda_ipc_mutex /* cuda_ipc_close_mutex */);
if (infer_response->HasError()) {
if (infer_response->IsErrorMessageSet()) {
TRITONSERVER_Error* err = TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
infer_response->Error()->Message().c_str());
LOG_IF_ERROR(
TRITONBACKEND_ResponseSend(
(*responses)[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, err),
"failed sending response");
TRITONSERVER_ErrorDelete(err);
} else {
const char* err_string = "Failed to process response.";
TRITONSERVER_Error* err =
TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INTERNAL, err_string);
LOG_IF_ERROR(
TRITONBACKEND_ResponseSend(
(*responses)[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, err),
"failed sending response");
TRITONSERVER_ErrorDelete(err);
}
(*responses)[r] = nullptr;
// If has_error is true, we do not look at the response even if the
// response is set.
continue;
}
}
catch (const PythonBackendException& pb_exception) {
TRITONSERVER_Error* err = TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, pb_exception.what());
LOG_IF_ERROR(
TRITONBACKEND_ResponseSend(
(*responses)[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, err),
"failed sending response");
TRITONSERVER_ErrorDelete(err);
(*responses)[r] = nullptr;
continue;
}
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestOutputCount(request, &requested_output_count));
bool cuda_copy = false;
std::set<std::string> requested_output_names;
for (size_t j = 0; j < requested_output_count; ++j) {
const char* output_name;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestOutputName(request, j, &output_name));
requested_output_names.insert(output_name);
}
for (auto& output_tensor : infer_response->OutputTensors()) {
if (requested_output_names.find(output_tensor->Name()) ==
requested_output_names.end()) {
continue;
}
TRITONSERVER_MemoryType src_memory_type = output_tensor->MemoryType();
int64_t src_memory_type_id = output_tensor->MemoryTypeId();
TRITONSERVER_MemoryType actual_memory_type = src_memory_type;
int64_t actual_memory_type_id = src_memory_type_id;
if (actual_memory_type == TRITONSERVER_MEMORY_GPU)
has_gpu_output = true;
TRITONBACKEND_Output* response_output;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_ResponseOutput(
response, &response_output, output_tensor->Name().c_str(),
static_cast<TRITONSERVER_DataType>(output_tensor->TritonDtype()),
output_tensor->Dims().data(), output_tensor->Dims().size()));
void* buffer;
bool cuda_used = false;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_OutputBuffer(
response_output, &buffer, output_tensor->ByteSize(),
&actual_memory_type, &actual_memory_type_id));
if (src_memory_type == TRITONSERVER_MEMORY_GPU &&
actual_memory_type == TRITONSERVER_MEMORY_GPU) {
#ifdef TRITON_ENABLE_GPU
cudaSetDevice(output_tensor->MemoryTypeId());
cudaIpcMemHandle_t cuda_ipc_mem_handle;
cudaError_t err = cudaIpcGetMemHandle(&cuda_ipc_mem_handle, buffer);
output_tensor->SetCudaIpcMemHandle(&cuda_ipc_mem_handle);
output_tensor->SetMemoryType(actual_memory_type);
output_tensor->SetMemoryTypeId(actual_memory_type_id);
if (err != cudaSuccess) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"failed to get cuda ipc handle: " +
std::string(cudaGetErrorString(err)))
.c_str()));
} else {
output_tensor->SetDataPtr(buffer);
output_tensor->RawDataShm()->offset =
output_tensor->GetGPUPointerOffset();
}
#endif
}
if (src_memory_type == TRITONSERVER_MEMORY_GPU &&
(actual_memory_type == TRITONSERVER_MEMORY_CPU ||
actual_memory_type == TRITONSERVER_MEMORY_CPU_PINNED)) {
tensor_buffer_pairs.push_back({output_tensor, {buffer, r}});
// Set the memory type to CPU in shared memory. The stubs notices the
// change in the memory type and should copy the input tensors to CPU.
output_tensor->RawDataShm()->memory_type = TRITONSERVER_MEMORY_CPU;
output_tensor->RawDataShm()->memory_type_id = actual_memory_type_id;
}
if (src_memory_type != TRITONSERVER_MEMORY_GPU) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
CopyBuffer(
"Failed to copy the output tensor to buffer.", src_memory_type,
src_memory_type_id, actual_memory_type, actual_memory_type_id,
output_tensor->ByteSize(), output_tensor->GetDataPtr(), buffer,
CudaStream(), &cuda_used));
}
cuda_copy |= cuda_used;
}
#ifdef TRITON_ENABLE_GPU
if (cuda_copy) {
cudaStreamSynchronize(stream_);
}
#endif // TRITON_ENABLE_GPU
}
// If the output tensor is in GPU, there will be a second round trip
// required for filling the GPU buffers provided by the main process.
if (has_gpu_output) {
ipc_message->Command() = PYTHONSTUB_CommandType::PYTHONSTUB_LoadGPUBuffers;
SendMessageAndReceiveResponse(
ipc_message->SharedMemoryOffset(), response_message, restart, responses,
requests, 0);
bool cuda_copy = false;
for (auto& tensor_buffer_pair : tensor_buffer_pairs) {
bool cuda_used = false;
auto& tensor = tensor_buffer_pair.first;
// Reload the tensor from shared memory so that the memory data is
// updated.
std::shared_ptr<std::mutex> cuda_ipc_mutex;
std::shared_ptr<PbTensor> reloaded_tensor =
PbTensor::LoadFromSharedMemory(
shm_pool_, tensor->ShmOffset(),
cuda_ipc_mutex /* cuda_ipc_open_mutex */,
cuda_ipc_mutex /* cuda_ipc_close_mutex */);
auto& buffer = tensor_buffer_pair.second.first;
auto& response_index = tensor_buffer_pair.second.second;
GUARDED_RESPOND_IF_ERROR(
responses, response_index,
CopyBuffer(
"Failed to copy the output tensor to buffer.",
TRITONSERVER_MEMORY_CPU, 0, TRITONSERVER_MEMORY_CPU, 0,
reloaded_tensor->ByteSize(), reloaded_tensor->GetDataPtr(),
buffer, CudaStream(), &cuda_used));
cuda_copy |= cuda_used;
}
#ifdef TRITON_ENABLE_GPU
if (cuda_copy) {
cudaStreamSynchronize(stream_);
}
#endif // TRITON_ENABLE_GPU
}
for (uint32_t r = 0; r < request_count; ++r) {
// If error happens at this stage, we can only log it
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_ResponseSend(
(*responses)[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL, nullptr));
}
uint64_t exec_end_ns = 0;
SET_TIMESTAMP(exec_end_ns);
reporter.SetExecEndNs(exec_end_ns);
reporter.SetBatchStatistics(total_batch_size);
return;
}
void
ModelInstanceState::CleanupBLSResponses()
{
for (auto& bls_inference_response : bls_inference_responses_) {
LOG_IF_ERROR(
TRITONSERVER_InferenceResponseDelete(bls_inference_response),
" failed to release BLS inference response.");
}
bls_inference_responses_.clear();
request_executors_.clear();
}
bool
ModelInstanceState::IsStubProcessAlive()
{
boost::posix_time::ptime timeout =
boost::get_system_time() + boost::posix_time::seconds(1);
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_, timeout);
// Check if lock has been acquired.
if (lock) {
return ipc_control_->stub_health;
} else {
// If It failed to obtain the lock, it means that the stub has been
// stuck or exited while holding the health mutex lock.
return false;
}
}
TRITONSERVER_Error*
ModelInstanceState::StartStubProcess()
{
new (health_mutex_) bi::interprocess_mutex;
stub_message_queue_->ResetSemaphores();
parent_message_queue_->ResetSemaphores();
std::string kind = TRITONSERVER_InstanceGroupKindString(kind_);
ModelState* model_state = reinterpret_cast<ModelState*>(Model());
int64_t shm_growth_size =
model_state->StateForBackend()->shm_growth_byte_size;
int64_t shm_default_size =
model_state->StateForBackend()->shm_default_byte_size;
const char* model_path = model_state->RepositoryPath().c_str();
initialized_ = false;
pid_t pid = fork();
if (pid < 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, "Failed to fork the stub process.");
}
// Stub process
if (pid == 0) {
const char* stub_args[4];
stub_args[0] = "bash";
stub_args[1] = "-c";
stub_args[3] = nullptr; // Last argument must be nullptr
// Default Python backend stub
std::string python_backend_stub =
model_state->StateForBackend()->python_lib +
"/triton_python_backend_stub";
// Path to alternative Python backend stub
std::string model_python_backend_stub =
std::string(model_path) + "/triton_python_backend_stub";
if (FileExists(model_python_backend_stub)) {
python_backend_stub = model_python_backend_stub;
}
std::string bash_argument;
// This shared memory variable indicates whether the
// stub process should revert the LD_LIBRARY_PATH changes to avoid
// shared library issues in executables and libraries.
ipc_control_->uses_env = false;
if (model_state->PythonExecutionEnv() != "") {
std::stringstream ss;
ss << "source " << path_to_activate_
<< " && exec env LD_LIBRARY_PATH=" << path_to_libpython_
<< ":$LD_LIBRARY_PATH " << python_backend_stub << " " << model_path_
<< " " << shm_region_name_ << " " << shm_default_size << " "
<< shm_growth_size << " " << parent_pid_ << " "
<< model_state->StateForBackend()->python_lib << " "
<< ipc_control_offset_ << " " << Name();
ipc_control_->uses_env = true;
// Need to properly set the LD_LIBRARY_PATH so that Python environments
// using different python versions load properly.
bash_argument = ss.str();
} else {
std::stringstream ss;
ss << " exec " << python_backend_stub << " " << model_path_ << " "
<< shm_region_name_ << " " << shm_default_size << " "
<< shm_growth_size << " " << parent_pid_ << " "
<< model_state->StateForBackend()->python_lib << " "
<< ipc_control_offset_ << " " << Name();
bash_argument = ss.str();
}
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Starting Python backend stub: ") + bash_argument)
.c_str());
stub_args[2] = bash_argument.c_str();
int stub_status_code =
system((python_backend_stub + "> /dev/null 2>&1").c_str());
// If running stub process without any arguments returns any status code,
// other than 1, it can indicate a permission issue as a result of
// downloading the stub process from a cloud object storage service.
if (WEXITSTATUS(stub_status_code) != 1) {
// Give the execute permission for the triton_python_backend_stub to the
// owner.
int error = chmod(python_backend_stub.c_str(), S_IXUSR);
if (error != 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("Failed to give execute permission to "
"triton_python_backend_stub in ") +
python_backend_stub + " " + Name() +
" Error No.: " + std::to_string(error))
.c_str());
}
}
if (execvp("bash", (char**)stub_args) != 0) {
std::stringstream ss;
ss << "Failed to run python backend stub. Errno = " << errno << '\n'
<< "Python backend stub path: " << python_backend_stub << '\n'
<< "Shared Memory Region Name: " << shm_region_name_ << '\n'
<< "Shared Memory Default Byte Size: " << shm_default_size << '\n'
<< "Shared Memory Growth Byte Size: " << shm_growth_size << '\n';
std::string log_message = ss.str();
LOG_MESSAGE(TRITONSERVER_LOG_ERROR, log_message.c_str());
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("Failed to initialize model instance ") + Name())
.c_str());
}
} else {
stub_pid_ = pid;
triton::common::TritonJson::WriteBuffer buffer;
Model()->ModelConfig().Write(&buffer);
std::unordered_map<std::string, std::string> initialize_map = {
{"model_config", buffer.MutableContents()},
{"model_instance_kind", TRITONSERVER_InstanceGroupKindString(kind_)},
{"model_instance_name", name_},
{"model_instance_device_id", std::to_string(device_id_)},
{"model_repository", model_state->RepositoryPath()},
{"model_version", std::to_string(model_state->Version())},
{"model_name", model_state->Name()}};
std::unique_ptr<IPCMessage> initialize_message =
std::make_unique<IPCMessage>(shm_pool_, false /* inline_response */);
initialize_message->Command() = PYTHONSTUB_InitializeRequest;
// TODO: Fix restart during initialize
off_t initialize_map_offset;
RETURN_IF_EXCEPTION(SaveMapToSharedMemory(
shm_pool_, initialize_map_offset, initialize_map));
initialize_message->Args() = initialize_map_offset;
stub_message_queue_->Push(initialize_message->SharedMemoryOffset());
std::unique_ptr<IPCMessage> init_msg_response_mapped =
IPCMessage::LoadFromSharedMemory(
shm_pool_, parent_message_queue_->Pop());
if (init_msg_response_mapped->Command() != PYTHONSTUB_InitializeResponse) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string(
"Received unexpected resposne from Python backend stub: ") +
name_)
.c_str());
}
InitializeResponse* initialize_response;
RETURN_IF_EXCEPTION(shm_pool_->MapOffset(
(char**)&initialize_response, init_msg_response_mapped->Args()));
if (initialize_response->response_has_error) {
if (initialize_response->response_is_error_set) {
char* err_message;
RETURN_IF_EXCEPTION(LoadStringFromSharedMemory(
shm_pool_, initialize_response->response_error, err_message));
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INTERNAL, err_message);
} else {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("Initialize() failed for ") + model_state->Name())
.c_str());
}
}
initialized_ = true;
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelInstanceState::SetupStubProcess()
{
std::string kind = TRITONSERVER_InstanceGroupKindString(kind_);
ModelState* model_state = reinterpret_cast<ModelState*>(Model());
// Increase the stub process count to avoid shared memory region name
// collision
model_state->StateForBackend()->number_of_instance_inits++;
shm_region_name_ =
model_state->StateForBackend()->shared_memory_region_prefix +
std::to_string(model_state->StateForBackend()->number_of_instance_inits);
int64_t shm_growth_size =
model_state->StateForBackend()->shm_growth_byte_size;
int64_t shm_default_size =
model_state->StateForBackend()->shm_default_byte_size;
try {
shm_pool_ = std::make_unique<SharedMemory>(
shm_region_name_, shm_default_size, shm_growth_size,
true /* truncate */);
}
catch (const PythonBackendException& pb_exception) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, pb_exception.what());
}
IPCControl* ipc_control;
shm_pool_->Map((char**)&ipc_control, sizeof(IPCControl), ipc_control_offset_);
ipc_control_ = ipc_control;
bi::interprocess_mutex* health_mutex;
off_t health_mutex_offset;
RETURN_IF_EXCEPTION(shm_pool_->Map(
(char**)&health_mutex, sizeof(bi::interprocess_mutex),
health_mutex_offset));
ipc_control_->stub_health_mutex = health_mutex_offset;
health_mutex_ = health_mutex;
uint64_t model_version = model_state->Version();
const char* model_path = model_state->RepositoryPath().c_str();
std::stringstream ss;
std::string artifact_name;
RETURN_IF_ERROR(model_state->ModelConfig().MemberAsString(
"default_model_filename", &artifact_name));
ss << model_path << "/" << model_version << "/";
if (artifact_name.size() > 0) {
ss << artifact_name;
} else {
// Default artifact name.
ss << "model.py";
}
model_path_ = ss.str();
struct stat buffer;
// Check if model.py exists
if (stat(model_path_.c_str(), &buffer) != 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
("model.py does not exist in the model repository path: " + model_path_)
.c_str());
}
// Path to the extracted Python env
std::string python_execution_env = "";
if (model_state->PythonExecutionEnv() != "") {
try {
python_execution_env =
model_state->StateForBackend()->env_manager->ExtractIfNotExtracted(
model_state->PythonExecutionEnv());
}
catch (PythonBackendException& pb_exception) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL, pb_exception.what());
}
path_to_activate_ = python_execution_env + "/bin/activate";
path_to_libpython_ = python_execution_env + "/lib";
if (python_execution_env.length() > 0 && !FileExists(path_to_activate_)) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
(std::string("Path ") + path_to_activate_ +
" does not exist. The Python environment should contain an "
"'activate' script.")
.c_str());
}
}
parent_pid_ = getpid();
auto message_queue_size =
model_state->StateForBackend()->shm_message_queue_size;
RETURN_IF_EXCEPTION(
stub_message_queue_ =
std::make_unique<MessageQueue>(shm_pool_, message_queue_size));
RETURN_IF_EXCEPTION(
parent_message_queue_ =
std::make_unique<MessageQueue>(shm_pool_, message_queue_size));
ipc_control_->parent_message_queue = parent_message_queue_->ShmOffset();
ipc_control_->stub_message_queue = stub_message_queue_->ShmOffset();
// Offset that must be used for resetting the shared memory usage.
shm_reset_offset_ = shm_pool_->Offset();
RETURN_IF_ERROR(StartStubProcess());
return nullptr;
}
ModelInstanceState::~ModelInstanceState()
{
if (initialized_) {
{
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_);
ipc_control_->stub_health = false;
}
// Sleep 1 second so that the child process has a chance to change the
// health variable
sleep(1);
bool healthy = false;
bool force_kill = false;
{
bi::scoped_lock<bi::interprocess_mutex> lock(*health_mutex_);
healthy = ipc_control_->stub_health;
}
if (healthy) {
// Finalize command does not have any arguments.
std::unique_ptr<IPCMessage> ipc_message =
std::make_unique<IPCMessage>(shm_pool_, false /* inline_response */);
ipc_message->Command() = PYTHONSTUB_FinalizeRequest;
stub_message_queue_->Push(ipc_message->SharedMemoryOffset());
parent_message_queue_->Pop();
stub_message_queue_.reset();
parent_message_queue_.reset();
} else {
force_kill = true;
}
int status;
if (force_kill) {
kill(stub_pid_, SIGKILL);
}
waitpid(stub_pid_, &status, 0);
}
}
TRITONSERVER_Error*
ModelInstanceState::GetInputTensor(
const uint32_t input_idx, Tensor* input_tensor_shm,
std::shared_ptr<PbTensor>& input_tensor, TRITONBACKEND_Request* request,
std::shared_ptr<std::vector<TRITONBACKEND_Response*>>& responses)
{
const char* input_name;
// Load iidx'th input name
RETURN_IF_ERROR(
TRITONBACKEND_RequestInputName(request, input_idx, &input_name));
// Load iidx'th input
TRITONBACKEND_Input* in;
RETURN_IF_ERROR(TRITONBACKEND_RequestInput(request, input_name, &in));
// Load input properties
TRITONSERVER_DataType input_dtype;
const int64_t* input_shape;
uint32_t input_dims_count;
uint64_t input_byte_size;
uint32_t input_buffer_count;
RETURN_IF_ERROR(TRITONBACKEND_InputPropertiesForHostPolicy(
in, HostPolicyName().c_str(), &input_name, &input_dtype, &input_shape,
&input_dims_count, &input_byte_size, &input_buffer_count));
BackendInputCollector collector(
&request, 1, responses.get(), Model()->TritonMemoryManager(),
false /* pinned_enable */, CudaStream(), nullptr, nullptr, 0,
HostPolicyName().c_str());
ModelState* model_state = reinterpret_cast<ModelState*>(Model());
bool cpu_only_tensors = model_state->ForceCPUOnlyInputTensors();
if (input_dtype == TRITONSERVER_TYPE_BYTES) {
cpu_only_tensors = true;
}
#ifdef TRITON_ENABLE_GPU
CUDADriverAPI& cuda_driver_api = CUDADriverAPI::getInstance();
// If CUDA driver API is not available, the input tensors will be moved to
// CPU.
if (!cuda_driver_api.IsAvailable()) {
cpu_only_tensors = true;
}
#endif
TRITONSERVER_MemoryType src_memory_type;
int64_t src_memory_type_id;
size_t src_byte_size;
const void* src_ptr;
RETURN_IF_ERROR(TRITONBACKEND_InputBuffer(
in, 0 /* input buffer index */, &src_ptr, &src_byte_size,
&src_memory_type, &src_memory_type_id));
// If TRITON_ENABLE_GPU is false, we need to copy the tensors
// to the CPU.
#ifndef TRITON_ENABLE_GPU
cpu_only_tensors = true;
#endif // TRITON_ENABLE_GPU
if (cpu_only_tensors || src_memory_type != TRITONSERVER_MEMORY_GPU) {
input_tensor = std::make_unique<PbTensor>(
std::string(input_name),
std::vector<int64_t>(input_shape, input_shape + input_dims_count),
input_dtype, TRITONSERVER_MEMORY_CPU /* memory_type */,
0 /* memory_type_id */, nullptr /* buffer ptr*/, input_byte_size,
nullptr /* DLManagedTensor */);
RETURN_IF_EXCEPTION(input_tensor->SaveToSharedMemory(
shm_pool_, input_tensor_shm, false /* copy_cpu */,
true /* copy_gpu */));
char* input_buffer = reinterpret_cast<char*>(input_tensor->GetDataPtr());
collector.ProcessTensor(
input_name, input_buffer, input_byte_size,
TRITONSERVER_MEMORY_CPU /* memory_type */, 0 /* memory_type_id */);
} else {
#ifdef TRITON_ENABLE_GPU
// Retreiving GPU input tensors
const void* buffer = nullptr;
std::vector<std::pair<TRITONSERVER_MemoryType, int64_t>> alloc_perference;
alloc_perference = {{TRITONSERVER_MEMORY_GPU, src_memory_type_id}};
RETURN_IF_ERROR(collector.ProcessTensor(
input_name, nullptr, 0, alloc_perference,
reinterpret_cast<const char**>(&buffer), &input_byte_size,
&src_memory_type, &src_memory_type_id));
input_tensor = std::make_unique<PbTensor>(
std::string(input_name),
std::vector<int64_t>(input_shape, input_shape + input_dims_count),
input_dtype, src_memory_type, src_memory_type_id,
const_cast<void*>(buffer), input_byte_size,
nullptr /* DLManagedTensor */);
RETURN_IF_EXCEPTION(input_tensor->SaveToSharedMemory(
shm_pool_, input_tensor_shm, true /* copy_cpu */, true /* copy_gpu */));
#else
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"Python backend does not support GPU tensors.");
#endif // TRITON_ENABLE_GPU
}
return nullptr;
}
TRITONSERVER_Error*
ModelState::Create(TRITONBACKEND_Model* triton_model, ModelState** state)
{
try {
*state = new ModelState(triton_model);
}
catch (const BackendModelException& ex) {
RETURN_ERROR_IF_TRUE(
ex.err_ == nullptr, TRITONSERVER_ERROR_INTERNAL,
std::string("unexpected nullptr in BackendModelException"));
RETURN_IF_ERROR(ex.err_);
}
return nullptr; // success
}
ModelState::ModelState(TRITONBACKEND_Model* triton_model)
: BackendModel(triton_model)
{
TRITONBACKEND_Backend* backend;
THROW_IF_BACKEND_MODEL_ERROR(
TRITONBACKEND_ModelBackend(triton_model, &backend));
const char* path = nullptr;
TRITONBACKEND_ArtifactType artifact_type;
THROW_IF_BACKEND_MODEL_ERROR(
TRITONBACKEND_ModelRepository(triton_model, &artifact_type, &path));
python_execution_env_ = "";
force_cpu_only_input_tensors_ = true;
void* bstate;
THROW_IF_BACKEND_MODEL_ERROR(TRITONBACKEND_BackendState(backend, &bstate));
backend_state_ = reinterpret_cast<BackendState*>(bstate);
triton::common::TritonJson::Value params;
if (model_config_.Find("parameters", ¶ms)) {
// Skip the EXECUTION_ENV_PATH variable if it doesn't exist.
TRITONSERVER_Error* error =
GetParameterValue(params, "EXECUTION_ENV_PATH", &python_execution_env_);
if (error == nullptr) {
std::string relative_path_keyword = "$$TRITON_MODEL_DIRECTORY";
size_t relative_path_loc =
python_execution_env_.find(relative_path_keyword);
if (relative_path_loc != std::string::npos) {
python_execution_env_.replace(
relative_path_loc, relative_path_loc + relative_path_keyword.size(),
path);
}
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Using Python execution env ") + python_execution_env_)
.c_str());
} else {
// Delete the error
TRITONSERVER_ErrorDelete(error);
}
// Skip the FORCE_CPU_ONLY_INPUT_TENSORS variable if it doesn't exits.
std::string force_cpu_only_input_tensor;
error = nullptr;
error = GetParameterValue(
params, "FORCE_CPU_ONLY_INPUT_TENSORS", &force_cpu_only_input_tensor);
if (error == nullptr) {
if (force_cpu_only_input_tensor == "yes") {
force_cpu_only_input_tensors_ = true;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Forcing CPU only input tensors.")).c_str());
} else if (force_cpu_only_input_tensor == "no") {
force_cpu_only_input_tensors_ = false;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Input tensors can be both in CPU and GPU. "
"FORCE_CPU_ONLY_INPUT_TENSORS is off."))
.c_str());
} else {
throw triton::backend::BackendModelException(TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
(std::string("Incorrect value for FORCE_CPU_ONLY_INPUT_TENSORS: ") +
force_cpu_only_input_tensor + "'")
.c_str()));
}
} else {
// Delete the error
TRITONSERVER_ErrorDelete(error);
}
}
if (artifact_type != TRITONBACKEND_ARTIFACT_FILESYSTEM) {
throw triton::backend::BackendModelException(TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
(std::string("unsupported artifact type for model '") + Name() + "'")
.c_str()));
}
}
extern "C" {
TRITONSERVER_Error*
TRITONBACKEND_Initialize(TRITONBACKEND_Backend* backend)
{
const char* cname;
RETURN_IF_ERROR(TRITONBACKEND_BackendName(backend, &cname));
std::string name(cname);
// Check backend version to ensure compatibility
uint32_t api_version_major, api_version_minor;
RETURN_IF_ERROR(
TRITONBACKEND_ApiVersion(&api_version_major, &api_version_minor));
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("'") + name + "' TRITONBACKEND API version: " +
std::to_string(TRITONBACKEND_API_VERSION_MAJOR) + "." +
std::to_string(TRITONBACKEND_API_VERSION_MINOR))
.c_str());
if ((api_version_major != TRITONBACKEND_API_VERSION_MAJOR) ||
(api_version_minor < TRITONBACKEND_API_VERSION_MINOR)) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"Triton backend API version does not support this backend");
}
TRITONSERVER_Message* backend_config_message;
RETURN_IF_ERROR(
TRITONBACKEND_BackendConfig(backend, &backend_config_message));
const char* buffer;
size_t byte_size;
RETURN_IF_ERROR(TRITONSERVER_MessageSerializeToJson(
backend_config_message, &buffer, &byte_size));
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("backend configuration:\n") + buffer).c_str());
triton::common::TritonJson::Value backend_config;
if (byte_size != 0) {
RETURN_IF_ERROR(backend_config.Parse(buffer, byte_size));
}
std::unique_ptr<BackendState> backend_state(new BackendState());
triton::common::TritonJson::Value cmdline;
backend_state->shm_default_byte_size = 64 * 1024 * 1024; // 64 MBs
backend_state->shm_growth_byte_size = 64 * 1024 * 1024; // 64 MBs
backend_state->stub_timeout_seconds = 30;
backend_state->shm_message_queue_size = 1000;
backend_state->number_of_instance_inits = 0;
backend_state->shared_memory_region_prefix =
"triton_python_backend_shm_region_";
if (backend_config.Find("cmdline", &cmdline)) {
triton::common::TritonJson::Value shm_growth_size;
std::string shm_growth_byte_size;
if (cmdline.Find("shm-growth-byte-size", &shm_growth_size)) {
RETURN_IF_ERROR(shm_growth_size.AsString(&shm_growth_byte_size));
try {
backend_state->shm_growth_byte_size = std::stol(shm_growth_byte_size);
if (backend_state->shm_growth_byte_size <= 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("shm-growth-byte-size") +
" can't be smaller than or equal to zero.")
.c_str());
}
}
catch (const std::invalid_argument& ia) {
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, ia.what());
}
}
triton::common::TritonJson::Value shm_default_size;
std::string shm_default_byte_size;
if (cmdline.Find("shm-default-byte-size", &shm_default_size)) {
RETURN_IF_ERROR(shm_default_size.AsString(&shm_default_byte_size));
try {
backend_state->shm_default_byte_size = std::stol(shm_default_byte_size);
// Shared memory default byte size can't be less than 4 MBs.
if (backend_state->shm_default_byte_size < 4 * 1024 * 1024) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("shm-default-byte-size") +
" can't be smaller than 4 MiBs")
.c_str());
}
}
catch (const std::invalid_argument& ia) {
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, ia.what());
}
}
triton::common::TritonJson::Value shm_region_prefix;
std::string shm_region_prefix_str;
if (cmdline.Find("shm-region-prefix-name", &shm_region_prefix)) {
RETURN_IF_ERROR(shm_region_prefix.AsString(&shm_region_prefix_str));
// Shared memory default byte size can't be less than 4 MBs.
if (shm_region_prefix_str.size() == 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("shm-region-prefix-name") +
" must at least contain one character.")
.c_str());
}
backend_state->shared_memory_region_prefix = shm_region_prefix_str;
}
triton::common::TritonJson::Value shm_message_queue_size;
std::string shm_message_queue_size_str;
if (cmdline.Find("shm_message_queue_size", &shm_message_queue_size)) {
RETURN_IF_ERROR(
shm_message_queue_size.AsString(&shm_message_queue_size_str));
try {
backend_state->shm_message_queue_size =
std::stol(shm_message_queue_size_str);
}
catch (const std::invalid_argument& ia) {
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, ia.what());
}
}
triton::common::TritonJson::Value stub_timeout_seconds;
std::string stub_timeout_string_seconds;
if (cmdline.Find("stub-timeout-seconds", &stub_timeout_seconds)) {
RETURN_IF_ERROR(
stub_timeout_seconds.AsString(&stub_timeout_string_seconds));
try {
backend_state->stub_timeout_seconds =
std::stol(stub_timeout_string_seconds);
if (backend_state->stub_timeout_seconds <= 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
(std::string("stub-timeout-seconds") +
" can't be smaller than or equal to zero.")
.c_str());
}
}
catch (const std::invalid_argument& ia) {
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INVALID_ARG, ia.what());
}
}
}
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("Shared memory configuration is shm-default-byte-size=") +
std::to_string(backend_state->shm_default_byte_size) +
",shm-growth-byte-size=" +
std::to_string(backend_state->shm_growth_byte_size) +
",stub-timeout-seconds=" +
std::to_string(backend_state->stub_timeout_seconds))
.c_str());
// Use BackendArtifacts to determine the location of Python files
const char* location;
TRITONBACKEND_ArtifactType artifact_type;
RETURN_IF_ERROR(
TRITONBACKEND_BackendArtifacts(backend, &artifact_type, &location));
backend_state->python_lib = location;
backend_state->env_manager = std::make_unique<EnvironmentManager>();
RETURN_IF_ERROR(TRITONBACKEND_BackendSetState(
backend, reinterpret_cast<void*>(backend_state.get())));
backend_state.release();
return nullptr;
}
TRITONSERVER_Error*
TRITONBACKEND_Finalize(TRITONBACKEND_Backend* backend)
{
LOG_MESSAGE(TRITONSERVER_LOG_VERBOSE, "TRITONBACKEND_Finalize: Start");
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_BackendState(backend, &vstate));
auto backend_state = reinterpret_cast<BackendState*>(vstate);
delete backend_state;
LOG_MESSAGE(TRITONSERVER_LOG_VERBOSE, "TRITONBACKEND_Finalize: End");
return nullptr; // success
}
TRITONSERVER_Error*
TRITONBACKEND_ModelInitialize(TRITONBACKEND_Model* model)
{
const char* cname;
RETURN_IF_ERROR(TRITONBACKEND_ModelName(model, &cname));
std::string name(cname);
uint64_t version;
RETURN_IF_ERROR(TRITONBACKEND_ModelVersion(model, &version));
TRITONSERVER_LogMessage(
TRITONSERVER_LOG_VERBOSE, __FILE__, __LINE__,
(std::string("TRITONBACKEND_ModelInitialize: ") + name + " (version " +
std::to_string(version) + ")")
.c_str());
TRITONBACKEND_Backend* backend;
RETURN_IF_ERROR(TRITONBACKEND_ModelBackend(model, &backend));
ModelState* model_state;
RETURN_IF_ERROR(ModelState::Create(model, &model_state));
RETURN_IF_ERROR(
TRITONBACKEND_ModelSetState(model, reinterpret_cast<void*>(model_state)));
return nullptr;
}
TRITONSERVER_Error*
TRITONBACKEND_ModelFinalize(TRITONBACKEND_Model* model)
{
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelState(model, &vstate));
ModelState* model_state = reinterpret_cast<ModelState*>(vstate);
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
"TRITONBACKEND_ModelFinalize: delete model state");
delete model_state;
return nullptr;
}
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceInitialize(TRITONBACKEND_ModelInstance* instance)
{
const char* cname;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceName(instance, &cname));
std::string name(cname);
int32_t device_id;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceDeviceId(instance, &device_id));
TRITONSERVER_InstanceGroupKind kind;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceKind(instance, &kind));
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("TRITONBACKEND_ModelInstanceInitialize: ") + name + " (" +
TRITONSERVER_InstanceGroupKindString(kind) + " device " +
std::to_string(device_id) + ")")
.c_str());
TRITONBACKEND_Model* model;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceModel(instance, &model));
void* vmodelstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelState(model, &vmodelstate));
ModelState* model_state = reinterpret_cast<ModelState*>(vmodelstate);
ModelInstanceState* instance_state;
RETURN_IF_ERROR(
ModelInstanceState::Create(model_state, instance, &instance_state));
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceSetState(
instance, reinterpret_cast<void*>(instance_state)));
RETURN_IF_ERROR(instance_state->SetupStubProcess());
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("TRITONBACKEND_ModelInstanceInitialize: instance "
"initialization successful ") +
name + " (device " + std::to_string(device_id) + ")")
.c_str());
return nullptr;
}
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceExecute(
TRITONBACKEND_ModelInstance* instance, TRITONBACKEND_Request** requests,
const uint32_t request_count)
{
ModelInstanceState* instance_state;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceState(
instance, reinterpret_cast<void**>(&instance_state)));
// If restart is equal to true, it indicates that the stub process is
// unhealthy and needs a restart.
bool restart = false;
std::atomic<bool> cleanup{false};
instance_state->ProcessRequests(requests, request_count, restart, cleanup);
// Wait for all the pending BLS requests to be completed.
instance_state->WaitForBLSRequestsToFinish();
instance_state->CleanupBLSResponses();
for (uint32_t r = 0; r < request_count; ++r) {
TRITONBACKEND_Request* request = requests[r];
LOG_IF_ERROR(
TRITONBACKEND_RequestRelease(request, TRITONSERVER_REQUEST_RELEASE_ALL),
"failed releasing request");
}
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
(std::string("TRITONBACKEND_ModelInstanceExecute: model instance name ") +
instance_state->Name() + " released " + std::to_string(request_count) +
" requests")
.c_str());
if (restart) {
LOG_MESSAGE(
TRITONSERVER_LOG_ERROR,
"Stub process is unhealthy and it will be restarted.");
instance_state->KillStubProcess();
LOG_IF_ERROR(
instance_state->StartStubProcess(),
"Failed to restart the stub process.");
}
// We should return the shared memory offset before returning from this
// function. Otherwise there will be shared memory leaks if there is an
// error when processing the requests
instance_state->ResetSharedMemoryOffset();
return nullptr;
}
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceFinalize(TRITONBACKEND_ModelInstance* instance)
{
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceState(instance, &vstate));
ModelInstanceState* instance_state =
reinterpret_cast<ModelInstanceState*>(vstate);
LOG_MESSAGE(
TRITONSERVER_LOG_VERBOSE,
"TRITONBACKEND_ModelInstanceFinalize: delete instance state");
delete instance_state;
return nullptr;
}
} // extern "C"
}}} // namespace triton::backend::python
| 37.233034 | 80 | 0.651437 | [
"object",
"shape",
"vector",
"model"
] |
12e9299a2ca04de05405ad4f8d7fb530b06d26b6 | 781 | hpp | C++ | source/FAST/Visualization/Plotting/Plotter.hpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | source/FAST/Visualization/Plotting/Plotter.hpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | source/FAST/Visualization/Plotting/Plotter.hpp | andreped/FAST | 361819190ea0ae5a2f068e7bd808a1c70af5a171 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <FAST/ProcessObject.hpp>
#include <FAST/Data/Color.hpp>
#include <FAST/Data/SimpleDataObject.hpp>
#include <deque>
#include <QObject>
class QTimer;
class JKQTPlotter;
namespace fast{
// Abstract Plot object
class FAST_EXPORT Plotter : public QObject, public ProcessObject {
Q_OBJECT
public:
/**
* @brief How often to update plot
*
* Set how many times per second the plot should update.
* This setting impacts performance.
*
* @param frequency
*/
virtual void setUpdateFrequency(float frequency);
virtual JKQTPlotter* getPlotterWidget();
protected:
JKQTPlotter* m_plotterWidget;
QTimer* m_timer = nullptr;
public Q_SLOTS:
virtual void processQueue() = 0;
Q_SIGNALS:
void newData();
};
}
| 20.552632 | 66 | 0.700384 | [
"object"
] |
12ece8729fb1f290664931cd7990f69327a154ca | 20,919 | cxx | C++ | xp_comm_proj/stm3/msms/ComputeSES.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/stm3/msms/ComputeSES.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/stm3/msms/ComputeSES.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | //
// Computed the Solvent Excluded Surface with the msms program
// (see: http://www.scripps.edu/pub/olson-web/people/sanner/html/msms_home.html)
// The input are a list of atoms coordinates and a list of atoms radii
// The output is the computed surface.
//
// The msms executable is pointed by the MSMSSERVER environment variable
//
#include "ComputeSES_gen.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <io.h>
#include <fcntl.h>
int mkstemp(char *s)
{
char *s1 = mktemp(s);
return open(s1, _O_CREAT | _O_EXCL | _O_WRONLY);
}
#endif
#include <avs/gd_def.h>
#define STARTING_SIZE 1024
#define INCREMENT_SIZE 1024
#define LINE_LENGHT 1024
#include "../lib/stm3.h"
#include "../base/mol_type.h"
/*
** Windows version of system() library call
** Does not create a DOS window.
** Works only if the first token in cmd is an executable file
** and not a DOS internal command (like DIR) and does not accepts
** redirections.
*/
#ifdef WIN32
#include <stdio.h>
#include <string.h>
#include <process.h>
#define MAX_ARGS 20
int system(char *cmd)
{
char *token, *p;
int ntokens;
char seps[] = " \t\n";
char *argv[MAX_ARGS+1];
int i;
/*
** Check if the path is quoted to mask blanks
*/
if(cmd[0] == '\"')
{
for(i=1; cmd[i] != '\"' && cmd[i]; i++);
p = (cmd[i] == '\"') ? cmd + i + 1 : cmd + i;
cmd[i] = '\0';
argv[0] = cmd+1;
ntokens = 1;
}
else
{
p = cmd;
ntokens = 0;
}
/*
** Tokenize the non quoted part of the string
*/
token = strtok(p, seps);
while(token != NULL)
{
if(ntokens >= MAX_ARGS) return -1;
argv[ntokens] = token;
ntokens++;
token = strtok(NULL, seps);
}
argv[ntokens] = NULL;
/*
** Execute the command
*/
_flushall();
return _spawnvp(_P_WAIT, argv[0], argv);
}
#endif
int
STM3_MSMS_ComputeSES::ComputeSES(OMevent_mask event_mask, int seq_num)
{
// xyz_lst (OMXfloat_array read req notify)
int xyz_lst_size;
float *xyz_lst_arr;
// color (OMXint read notify)
// fld (Field write)
// filename (OMXstr read req notify)
// fld (Mesh write)
char line[LINE_LENGHT];
FILE *fp;
int i;
// reset the status message
status = "";
// If only the kind of coloring ha changed, don't reexecute MSMS
if(color.changed(seq_num) && last_atoms_idx.ret_array_size() > 0)
{
// access the saved data
int *last_atoms_idx_arr = (int *)last_atoms_idx.ret_array_ptr(OM_GET_ARRAY_RD);
float *last_normals_arr = (float *)last_normals.ret_array_ptr(OM_GET_ARRAY_RD);
int n_points = last_atoms_idx.ret_array_size();
if(last_atoms_idx_arr && last_normals_arr)
{
// if requested color the vertex by the closest sphere number
if((int)color == ATOM_TYPE)
{
fld.nnode_data = 2;
fld.node_data[0].id = GD_COLOR_DATA_ID;
fld.node_data[0].veclen = 3;
fld.node_data[0].labels = "Nearest atom color";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 0;
}
int *atom_z_arr = (int *)atom_z.ret_array_ptr(OM_GET_ARRAY_RD);
if(!atom_z_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing atom_z array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
ARRfree(fld_data1);
return 0;
}
for(i=0; i < n_points; ++i)
{
fld_data1[3*i+0] = atom_properties[atom_z_arr[last_atoms_idx_arr[i]]].color[0];
fld_data1[3*i+1] = atom_properties[atom_z_arr[last_atoms_idx_arr[i]]].color[1];
fld_data1[3*i+2] = atom_properties[atom_z_arr[last_atoms_idx_arr[i]]].color[2];
}
ARRfree(fld_data1);
ARRfree(atom_z_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, last_normals_arr, n_points*3, OM_SET_ARRAY_COPY);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 0;
}
}
else if((int)color == ATOM_CHARGE)
{
fld.nnode_data = 2;
fld.node_data[0].id.set_obj_ref(OMnull_obj, 0);
fld.node_data[0].veclen = 1;
fld.node_data[0].labels = "Charge";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 0;
}
float *charge_arr = (float *)charge.ret_array_ptr(OM_GET_ARRAY_RD);
if(!charge_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing charge array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
ARRfree(fld_data1);
return 0;
}
for(i=0; i < n_points; ++i)
{
fld_data1[i] = charge_arr[last_atoms_idx_arr[i]];
}
ARRfree(fld_data1);
ARRfree(charge_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, last_normals_arr, n_points*3, OM_SET_ARRAY_COPY);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 0;
}
}
else if((int)color == ATOM_Z)
{
fld.nnode_data = 2;
fld.node_data[0].id.set_obj_ref(OMnull_obj, 0);
fld.node_data[0].veclen = 1;
fld.node_data[0].labels = "Z";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 0;
}
int *atom_z_arr = (int *)atom_z.ret_array_ptr(OM_GET_ARRAY_RD);
if(!atom_z_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing atom_z array.");
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
ARRfree(fld_data1);
return 0;
}
for(i=0; i < n_points; ++i)
{
fld_data1[i] = atom_z_arr[last_atoms_idx_arr[i]];
}
ARRfree(fld_data1);
ARRfree(atom_z_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, last_normals_arr, n_points*3, OM_SET_ARRAY_COPY);
if(!fld_data0)
{
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
return 0;
}
}
else
{
fld.nnode_data = 1;
fld.node_data[0].veclen = 3;
fld.node_data[0].labels = "Normals";
fld.node_data[0].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[0].values.set_array(DTYPE_FLOAT, last_normals_arr, n_points*3, OM_SET_ARRAY_COPY);
if(!fld_data0)
{
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
return 0;
}
}
ARRfree(last_atoms_idx_arr);
ARRfree(last_normals_arr);
return 1;
}
else
{
if(last_atoms_idx_arr) ARRfree(last_atoms_idx_arr);
if(last_normals_arr) ARRfree(last_normals_arr);
}
}
// read the input data
xyz_lst_arr = (float *)xyz_lst.ret_array_ptr(OM_GET_ARRAY_RD, &xyz_lst_size);
if(!xyz_lst_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reading XYZ input.");
return 0;
}
if(xyz_lst_size < 3)
{
ARRfree(xyz_lst_arr);
return 0;
}
int *atom_z_arr = (int *)atom_z.ret_array_ptr(OM_GET_ARRAY_RD);
if(!atom_z_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reading Atom Z input.");
ARRfree(xyz_lst_arr);
return 0;
}
// build the input file
char input_file[1024];
char *t = getenv("TMP");
if(!t) t = getenv("TEMP");
if(!t) t = "/tmp";
sprintf(input_file, "%s/stm3msmsXXXXXX", t);
int fd = mkstemp(input_file);
if(fd < 0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error creating input file.");
return 0;
}
fp = fdopen(fd, "w");
for(i=0; i < xyz_lst_size/3; ++i)
{
float radius = atom_properties[atom_z_arr[i]].rvdw;
fprintf(fp, "%f %f %f %f\n", xyz_lst_arr[i*3+0], xyz_lst_arr[i*3+1], xyz_lst_arr[i*3+2], radius);
}
fclose(fp);
ARRfree(xyz_lst_arr);
ARRfree(atom_z_arr);
// invoke the MSMS command
char *msms_cmd = getenv("MSMSSERVER");
if(!msms_cmd)
{
remove(input_file);
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Cannot execute msms. Environment variable MSMSSERVER not defined");
status = "MSMSSERVER not defined";
return 0;
}
sprintf(line, "%s -if %s -of %s -no_header -probe_radius %f -density %f", msms_cmd, input_file, input_file, (float)probe_radius, (float)density);
printf("\n\n");
int sts = system(line);
remove(input_file);
if(sts)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Cannot execute msms. Status returned %d", sts);
status = "Cannot execute msms";
return 0;
}
// prepare the output filenames
int len = strlen(input_file);
char *vert_filename = new char[len+6];
char *face_filename = new char[len+6];
strcpy(vert_filename, input_file);
strcpy(face_filename, input_file);
strcpy(vert_filename+len, ".vert");
strcpy(face_filename+len, ".face");
// open the vertex coordinates file
fp = fopen(vert_filename, "r");
if(fp == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Cannot open %s", vert_filename);
delete [] vert_filename;
delete [] face_filename;
return 0;
}
// initialize the extensible coordinates array
int allocated_points = STARTING_SIZE;
int n_points = 0;
float *coords_buffer = (float *) ARRalloc(NULL, DTYPE_FLOAT, allocated_points*3, NULL);
if(coords_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error allocating coords array.");
delete [] vert_filename;
delete [] face_filename;
fclose(fp);
return 0;
}
// initialize the vertex normals array
float *normals_buffer = (float *) ARRalloc(NULL, DTYPE_FLOAT, allocated_points*3, NULL);
if(normals_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error allocating normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
fclose(fp);
return 0;
}
// initialize the atom names
int *atoms_buffer = (int *) ARRalloc(NULL, DTYPE_INT, allocated_points, NULL);
if(atoms_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error allocating atoms array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
fclose(fp);
return 0;
}
// read the vert file
while(fgets(line, sizeof(line)-2, fp))
{
if(n_points >= allocated_points)
{
allocated_points += INCREMENT_SIZE;
coords_buffer = (float *)ARRrealloc(coords_buffer, DTYPE_FLOAT, allocated_points*3, NULL);
if(coords_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reallocating coords array.");
delete [] vert_filename;
delete [] face_filename;
fclose(fp);
return 0;
}
normals_buffer = (float *)ARRrealloc(normals_buffer, DTYPE_FLOAT, allocated_points*3, NULL);
if(normals_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reallocating normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
fclose(fp);
return 0;
}
atoms_buffer = (int *)ARRrealloc(atoms_buffer, DTYPE_INT, allocated_points, NULL);
if(atoms_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reallocating atoms array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
fclose(fp);
return 0;
}
}
int dummy, atom;
sscanf(line, "%f%f%f%f%f%f%d%d", &coords_buffer[n_points*3+0], &coords_buffer[n_points*3+1], &coords_buffer[n_points*3+2],
&normals_buffer[n_points*3+0], &normals_buffer[n_points*3+1], &normals_buffer[n_points*3+2],
&dummy, &atom);
atoms_buffer[n_points] = atom - 1;
++n_points;
}
fclose(fp);
// Save the atom indices
last_atoms_idx.set_array_size(n_points);
int *last_atoms_idx_arr = (int *)last_atoms_idx.ret_array_ptr(OM_GET_ARRAY_WR);
if(last_atoms_idx_arr)
{
memcpy(last_atoms_idx_arr, atoms_buffer, n_points*sizeof(int));
ARRfree(last_atoms_idx_arr);
}
else
{
last_atoms_idx.set_array_size(0);
}
// Save the normals
last_normals.set_array_size(n_points*3);
float *last_normals_arr = (float *)last_normals.ret_array_ptr(OM_GET_ARRAY_WR);
if(last_normals_arr)
{
memcpy(last_normals_arr, normals_buffer, 3*n_points*sizeof(float));
ARRfree(last_normals_arr);
}
// set nnodes
fld.nnodes = n_points;
float *fld_coordinates = (float *)fld.coordinates.values.set_array(DTYPE_FLOAT, coords_buffer, n_points*3, OM_SET_ARRAY_FREE);
if(!fld_coordinates)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing coords array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
return 0;
}
// if requested color the vertex by the closest sphere number
if((int)color == ATOM_TYPE)
{
fld.nnode_data = 2;
fld.node_data[0].id = GD_COLOR_DATA_ID;
fld.node_data[0].veclen = 3;
fld.node_data[0].labels = "Nearest atom color";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(atoms_buffer);
return 0;
}
int *atom_z_arr = (int *)atom_z.ret_array_ptr(OM_GET_ARRAY_RD);
if(!atom_z_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing atom_z array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(atoms_buffer);
ARRfree(fld_data1);
return 0;
}
for(i=0; i < n_points; ++i)
{
fld_data1[3*i+0] = atom_properties[atom_z_arr[atoms_buffer[i]]].color[0];
fld_data1[3*i+1] = atom_properties[atom_z_arr[atoms_buffer[i]]].color[1];
fld_data1[3*i+2] = atom_properties[atom_z_arr[atoms_buffer[i]]].color[2];
}
ARRfree(fld_data1);
ARRfree(atom_z_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, last_normals_arr, n_points*3, OM_SET_ARRAY_COPY);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(atoms_buffer);
return 0;
}
}
else if((int)color == ATOM_CHARGE)
{
fld.nnode_data = 2;
fld.node_data[0].id.set_obj_ref(OMnull_obj, 0);
fld.node_data[0].veclen = 1;
fld.node_data[0].labels = "Charge";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(atoms_buffer);
return 0;
}
float *charge_arr = (float *)charge.ret_array_ptr(OM_GET_ARRAY_RD);
if(!charge_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing charge array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(fld_data1);
ARRfree(atoms_buffer);
return 0;
}
for(int i=0; i < n_points; ++i)
{
fld_data1[i] = charge_arr[atoms_buffer[i]];
}
ARRfree(atoms_buffer);
ARRfree(fld_data1);
ARRfree(charge_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, normals_buffer, n_points*3, OM_SET_ARRAY_FREE);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
return 0;
}
}
else if((int)color == ATOM_Z)
{
fld.nnode_data = 2;
fld.node_data[0].id.set_obj_ref(OMnull_obj, 0);
fld.node_data[0].veclen = 1;
fld.node_data[0].labels = "Z";
float *fld_data1 = (float *)fld.node_data[0].values.ret_array_ptr(OM_GET_ARRAY_WR);
if(!fld_data1)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(atoms_buffer);
return 0;
}
atom_z_arr = (int *)atom_z.ret_array_ptr(OM_GET_ARRAY_RD);
if(!atom_z_arr)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing atom_z array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
ARRfree(fld_data1);
ARRfree(atoms_buffer);
return 0;
}
for(int i=0; i < n_points; ++i)
{
fld_data1[i] = atom_z_arr[atoms_buffer[i]];
}
ARRfree(atoms_buffer);
ARRfree(fld_data1);
ARRfree(atom_z_arr);
fld.node_data[1].veclen = 3;
fld.node_data[1].labels = "Normals";
fld.node_data[1].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[1].values.set_array(DTYPE_FLOAT, normals_buffer, n_points*3, OM_SET_ARRAY_FREE);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
return 0;
}
}
else
{
fld.nnode_data = 1;
fld.node_data[0].veclen = 3;
fld.node_data[0].labels = "Normals";
fld.node_data[0].id = GD_NORMAL_DATA_ID;
float *fld_data0 = (float *)fld.node_data[0].values.set_array(DTYPE_FLOAT, normals_buffer, n_points*3, OM_SET_ARRAY_FREE);
if(!fld_data0)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing normals array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(coords_buffer);
ARRfree(normals_buffer);
return 0;
}
ARRfree(atoms_buffer);
}
// open the face connectivity file
fp = fopen(face_filename, "r");
if(fp == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Cannot open %s", face_filename);
delete [] vert_filename;
delete [] face_filename;
return 0;
}
// initialize the extensible connectivity array
int *conn_buffer;
int allocated_cells = STARTING_SIZE;
int n_cells = 0;
conn_buffer = (int *) ARRalloc(NULL, DTYPE_INT, allocated_cells*3, NULL);
if(conn_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error allocating conn array.");
delete [] vert_filename;
delete [] face_filename;
fclose(fp);
return 0;
}
while(fgets(line, sizeof(line)-2, fp))
{
if(n_cells >= allocated_cells)
{
allocated_cells += INCREMENT_SIZE;
conn_buffer = (int *)ARRrealloc(conn_buffer, DTYPE_INT, allocated_cells*3, NULL);
if(conn_buffer == NULL)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error reallocating conn array.");
delete [] vert_filename;
delete [] face_filename;
fclose(fp);
return 0;
}
}
sscanf(line, "%d%d%d", &conn_buffer[n_cells*3+0], &conn_buffer[n_cells*3+1], &conn_buffer[n_cells*3+2]);
--conn_buffer[n_cells*3+0];
--conn_buffer[n_cells*3+1];
--conn_buffer[n_cells*3+2];
++n_cells;
}
fclose(fp);
fld.cell_set[0].ncells = n_cells;
int *fld_node_connect_list = (int *)fld.cell_set[0].node_connect_list.set_array(DTYPE_INT, conn_buffer, n_cells*3, OM_SET_ARRAY_FREE);
if(!fld_node_connect_list)
{
ERRverror("ReadMSMS", ERR_NO_HEADER | ERR_ERROR, "Error accessing conn array.");
delete [] vert_filename;
delete [] face_filename;
ARRfree(conn_buffer);
return 0;
}
// return 1 for success
remove(vert_filename);
remove(face_filename);
delete [] vert_filename;
delete [] face_filename;
return 1;
}
| 28.774415 | 146 | 0.679048 | [
"mesh"
] |
12ee5d5fcfe2051286dacddf179601c9b8d61a6d | 3,029 | hpp | C++ | include/curl.hpp | mamba-org/powerloader | 19c6304b9f7fbdb5312877568575524df4c5f9d3 | [
"BSD-3-Clause"
] | 4 | 2021-12-01T15:31:48.000Z | 2021-12-14T18:27:19.000Z | include/curl.hpp | mamba-org/powerloader | 19c6304b9f7fbdb5312877568575524df4c5f9d3 | [
"BSD-3-Clause"
] | 25 | 2021-12-06T18:36:05.000Z | 2022-02-23T08:03:57.000Z | include/curl.hpp | mamba-org/powerloader | 19c6304b9f7fbdb5312877568575524df4c5f9d3 | [
"BSD-3-Clause"
] | 3 | 2021-12-06T10:44:26.000Z | 2022-02-18T16:11:23.000Z | #ifndef PW_CURL_HPP
#define PW_CURL_HPP
#include <filesystem>
#include <functional>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <spdlog/fmt/fmt.h>
#include <nlohmann/json.hpp>
#include <tl/expected.hpp>
#include "utils.hpp"
#include "enums.hpp"
namespace powerloader
{
extern "C"
{
#include <curl/curl.h>
}
class curl_error : public std::runtime_error
{
public:
curl_error(const std::string& what = "download error", bool serious = false);
bool is_serious() const;
private:
bool m_serious;
};
struct Response
{
std::map<std::string, std::string> header;
mutable std::stringstream content;
curl_off_t avg_speed;
curl_off_t downloaded_size;
long http_status;
std::string effective_url;
bool ok() const;
nlohmann::json json() const;
};
// TODO: rename this, try to not expose it
CURL* get_handle();
class CURLHandle
{
public:
using end_callback_type = std::function<CbReturnCode(const Response&)>;
CURLHandle();
CURLHandle(const std::string& url);
~CURLHandle();
CURLHandle& url(const std::string& url);
CURLHandle& accept_encoding();
CURLHandle& user_agent(const std::string& user_agent);
Response perform();
void finalize_transfer();
// TODO: should be private?
void finalize_transfer(Response& response);
template <class T>
tl::expected<T, CURLcode> getinfo(CURLINFO option);
// TODO: why do we need to expose these three methods
CURL* handle();
operator CURL*();
CURL* ptr() const;
CURLHandle& add_header(const std::string& header);
CURLHandle& add_headers(const std::vector<std::string>& headers);
CURLHandle& reset_headers();
template <class T>
CURLHandle& setopt(CURLoption opt, const T& val);
void set_default_callbacks();
CURLHandle& set_end_callback(const end_callback_type& func);
CURLHandle& upload(std::ifstream& stream);
CURLHandle& upload(std::istringstream& stream);
private:
CURL* m_handle;
curl_slist* p_headers = nullptr;
char errorbuffer[CURL_ERROR_SIZE];
std::unique_ptr<Response> response;
end_callback_type end_callback;
};
// TODO: restrict the possible implementations in the cpp file
template <class T>
inline CURLHandle& CURLHandle::setopt(CURLoption opt, const T& val)
{
CURLcode ok;
if constexpr (std::is_same<T, std::string>())
{
ok = curl_easy_setopt(m_handle, opt, val.c_str());
}
else
{
ok = curl_easy_setopt(m_handle, opt, val);
}
if (ok != CURLE_OK)
{
throw curl_error(
fmt::format("curl: curl_easy_setopt failed {}", curl_easy_strerror(ok)));
}
return *this;
}
}
#endif
| 24.827869 | 89 | 0.608452 | [
"vector"
] |
12f0e3ffb8f4ba68221f246754579ac7ee3ba3e1 | 703 | cc | C++ | 119. Triangle/TEST.cc | corkiwang1122/LeetCode | 39b1680b58173e6ec23a475605c3450ce8f78a81 | [
"MIT"
] | 3,690 | 2015-01-03T03:40:23.000Z | 2022-03-31T08:10:19.000Z | 119. Triangle/TEST.cc | Windfall94/LeetCode | 1756256d7e619164076bbf358c8f7ca68cd8bd79 | [
"MIT"
] | 21 | 2015-01-25T16:39:43.000Z | 2021-02-26T05:28:22.000Z | 119. Triangle/TEST.cc | Windfall94/LeetCode | 1756256d7e619164076bbf358c8f7ca68cd8bd79 | [
"MIT"
] | 1,290 | 2015-01-09T01:28:20.000Z | 2022-03-28T12:20:39.000Z | #define CATCH_CONFIG_MAIN
#include "../Catch/single_include/catch.hpp"
#include "solution.h"
using std::vector;
TEST_CASE("Triangle", "[minimumTotal]")
{
Solution s;
SECTION( "example" )
{
vector<vector<int>> vec{{2},{3,4},{6,5,7},{4,1,8,3}};
REQUIRE( s.minimumTotal(vec) == 11 );
}
SECTION( "complicated" )
{
vector<vector<int>> vec{{-7},{-2,1},{-5,-5,9},{-4,-5,4,4},{-6,-6,2,-1,-5},{3,7,8,-3,7,-9},{-9,-1,-9,6,9,0,7},{-7,0,-6,-8,7,1,-4,9},{-3,2,-6,-9,-7,-6,-9,4,0},{-8,-6,-3,-9,-2,-6,7,-5,0,7},{-9,-1,-2,4,-2,4,4,-1,2,-5,5},{1,1,-6,1,-2,-4,4,-2,6,-6,0,6},{-3,-3,-6,-2,-6,-2,7,-9,-5,-7,-5,5,1}};
REQUIRE( s.minimumTotal(vec) == -63 );
}
}
| 33.47619 | 294 | 0.489331 | [
"vector"
] |
12f701ff87731fa0335127fc00c8efeafeea2ce3 | 3,024 | cpp | C++ | vm/native/java_lang_Object.cpp | omapzoom/platform-dalvik | 415add46dbc6d1957d405d7dc7ace8a1fd91f339 | [
"Apache-2.0"
] | 1,306 | 2015-09-01T05:06:16.000Z | 2022-03-10T07:13:10.000Z | dalvik/vm/native/java_lang_Object.cpp | cnrat/DexHunter | b8f46563c7f3aeb79cf40db09e1d231649f1a29a | [
"Apache-2.0"
] | 11 | 2015-09-02T09:06:42.000Z | 2020-12-26T04:59:34.000Z | dalvik/vm/native/java_lang_Object.cpp | cnrat/DexHunter | b8f46563c7f3aeb79cf40db09e1d231649f1a29a | [
"Apache-2.0"
] | 598 | 2015-09-01T05:06:18.000Z | 2022-03-27T07:59:49.000Z | /*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.
*/
/*
* java.lang.Object
*/
#include "Dalvik.h"
#include "native/InternalNativePriv.h"
/*
* private Object internalClone()
*
* Implements most of Object.clone().
*/
static void Dalvik_java_lang_Object_internalClone(const u4* args,
JValue* pResult)
{
Object* thisPtr = (Object*) args[0];
Object* clone = dvmCloneObject(thisPtr, ALLOC_DONT_TRACK);
RETURN_PTR(clone);
}
/*
* public int hashCode()
*/
static void Dalvik_java_lang_Object_hashCode(const u4* args, JValue* pResult)
{
Object* thisPtr = (Object*) args[0];
RETURN_INT(dvmIdentityHashCode(thisPtr));
}
/*
* public Class getClass()
*/
static void Dalvik_java_lang_Object_getClass(const u4* args, JValue* pResult)
{
Object* thisPtr = (Object*) args[0];
RETURN_PTR(thisPtr->clazz);
}
/*
* public void notify()
*
* NOTE: we declare this as a full DalvikBridgeFunc, rather than a
* DalvikNativeFunc, because we really want to avoid the "self" lookup.
*/
static void Dalvik_java_lang_Object_notify(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
Object* thisPtr = (Object*) args[0];
dvmObjectNotify(self, thisPtr);
RETURN_VOID();
}
/*
* public void notifyAll()
*/
static void Dalvik_java_lang_Object_notifyAll(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
Object* thisPtr = (Object*) args[0];
dvmObjectNotifyAll(self, thisPtr);
RETURN_VOID();
}
/*
* public void wait(long ms, int ns) throws InterruptedException
*/
static void Dalvik_java_lang_Object_wait(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
Object* thisPtr = (Object*) args[0];
dvmObjectWait(self, thisPtr, GET_ARG_LONG(args,1), (s4)args[3], true);
RETURN_VOID();
}
const DalvikNativeMethod dvm_java_lang_Object[] = {
{ "internalClone", "(Ljava/lang/Cloneable;)Ljava/lang/Object;",
Dalvik_java_lang_Object_internalClone },
{ "hashCode", "()I",
Dalvik_java_lang_Object_hashCode },
{ "notify", "()V",
(DalvikNativeFunc) Dalvik_java_lang_Object_notify },
{ "notifyAll", "()V",
(DalvikNativeFunc) Dalvik_java_lang_Object_notifyAll },
{ "wait", "(JI)V",
(DalvikNativeFunc) Dalvik_java_lang_Object_wait },
{ "getClass", "()Ljava/lang/Class;",
Dalvik_java_lang_Object_getClass },
{ NULL, NULL, NULL },
};
| 27.243243 | 78 | 0.686508 | [
"object"
] |
12f82edaab41b14788ff3dfbc8cb8aac5518d95e | 4,261 | cpp | C++ | service/type-analysis/WholeProgramState.cpp | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | service/type-analysis/WholeProgramState.cpp | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | service/type-analysis/WholeProgramState.cpp | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "WholeProgramState.h"
#include "BaseIRAnalyzer.h"
#include "Resolver.h"
#include "Walkers.h"
using namespace type_analyzer;
namespace {
bool analyze_gets_helper(const WholeProgramState* whole_program_state,
const IRInstruction* insn,
DexTypeEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto field = resolve_field(insn->get_field());
if (field == nullptr) {
return false;
}
auto type = whole_program_state->get_field_type(field);
if (type.is_top()) {
return false;
}
env->set(ir_analyzer::RESULT_REGISTER, type);
return true;
}
} // namespace
namespace type_analyzer {
WholeProgramState::WholeProgramState(const Scope& scope,
const global::GlobalTypeAnalyzer&) {
walk::fields(scope, [&](DexField* field) { m_known_fields.emplace(field); });
walk::code(scope, [&](DexMethod* method, const IRCode&) {
if (method->get_code()) {
// TODO: Consider if we should add constraints for known methods and
// fields.
m_known_methods.emplace(method);
}
});
// TODO: collect types.
}
void WholeProgramState::collect_field_types(
const IRInstruction* insn,
const DexTypeEnvironment& env,
const DexType* clinit_cls,
ConcurrentMap<const DexField*, std::vector<DexTypeDomain>>* field_tmp) {
if (!is_sput(insn->opcode()) && !is_iput(insn->opcode())) {
return;
}
auto field = resolve_field(insn->get_field());
if (!field || !m_known_fields.count(field)) {
return;
}
if (is_sput(insn->opcode()) && field->get_class() == clinit_cls) {
return;
}
auto type = env.get(insn->src(0));
field_tmp->update(field,
[type](const DexField*,
std::vector<DexTypeDomain>& s,
bool /* exists */) { s.emplace_back(type); });
}
void WholeProgramState::collect_return_types(
const IRInstruction* insn,
const DexTypeEnvironment& env,
const DexMethod* method,
ConcurrentMap<const DexMethod*, std::vector<DexTypeDomain>>* method_tmp) {
auto op = insn->opcode();
if (!is_return(op)) {
return;
}
if (op == OPCODE_RETURN_VOID) {
// We must set the binding to Top here to record the fact that this method
// does indeed return -- even though `void` is not actually a return type,
// this tells us that the code following any invoke of this method is
// reachable.
method_tmp->update(
method,
[](const DexMethod*, std::vector<DexTypeDomain>& s, bool /* exists */) {
s.emplace_back(DexTypeDomain::top());
});
return;
}
auto type = env.get(insn->src(0));
method_tmp->update(method,
[type](const DexMethod*,
std::vector<DexTypeDomain>& s,
bool /* exists */) { s.emplace_back(type); });
}
bool WholeProgramAwareAnalyzer::analyze_sget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
DexTypeEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_iget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
DexTypeEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_invoke(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
DexTypeEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto op = insn->opcode();
if (op != OPCODE_INVOKE_DIRECT && op != OPCODE_INVOKE_STATIC &&
op != OPCODE_INVOKE_VIRTUAL) {
return false;
}
auto method = resolve_method(insn->get_method(), opcode_to_search(insn));
if (method == nullptr) {
return false;
}
auto type = whole_program_state->get_return_type(method);
if (type.is_top()) {
return false;
}
env->set(ir_analyzer::RESULT_REGISTER, type);
return true;
}
} // namespace type_analyzer
| 29.590278 | 80 | 0.652898 | [
"vector"
] |
4209c25f64fd50f498728848bc0d9b35d4350705 | 1,193 | cpp | C++ | dil/dil-lifetimes.cpp | pre-graduate/dil | 881003a95ed6724fb500307fdcf15364b0afcd51 | [
"Apache-2.0"
] | 1 | 2015-12-12T10:50:24.000Z | 2015-12-12T10:50:24.000Z | dil/dil-lifetimes.cpp | pre-graduate/dil | 881003a95ed6724fb500307fdcf15364b0afcd51 | [
"Apache-2.0"
] | 1 | 2015-12-11T17:06:54.000Z | 2015-12-12T10:43:51.000Z | dil/dil-lifetimes.cpp | william-taylor/dependency-injection-container | 881003a95ed6724fb500307fdcf15364b0afcd51 | [
"Apache-2.0"
] | null | null | null | #include "dil-lifetimes.h"
#include "dil-entry.h"
void dil::local_lifetime::release(entry * entry)
{
const auto deleteClosure = entry->getDeleteClosure();
for (auto& ptr : allocated_objects)
{
deleteClosure(ptr);
}
}
dil::raw_pointer dil::local_lifetime::acquire(entry * entry)
{
const auto createClosure = entry->getCreateClosure();
if(createClosure != nullptr)
{
const auto newObject = createClosure();
allocated_objects.push_back(newObject);
return newObject;
}
return nullptr;
}
dil::global_lifetime::global_lifetime() :
object(nullptr)
{
}
void dil::global_lifetime::release(entry * entry)
{
if (object != nullptr)
{
const auto deleteClosure = entry->getDeleteClosure();
if(deleteClosure != nullptr)
{
deleteClosure(object);
object = nullptr;
}
}
}
dil::raw_pointer dil::global_lifetime::acquire(dil::entry * entry)
{
if (object == nullptr)
{
const auto createClosure = entry->getCreateClosure();
if(createClosure != nullptr)
{
object = createClosure();
}
}
return object;
}
| 19.241935 | 66 | 0.609388 | [
"object"
] |
420b6373d0aec6f8af54e27ce8c5cb795feac211 | 1,219 | cpp | C++ | torch/csrc/jit/api/object.cpp | Hacky-DH/pytorch | 80dc4be615854570aa39a7e36495897d8a040ecc | [
"Intel"
] | 60,067 | 2017-01-18T17:21:31.000Z | 2022-03-31T21:37:45.000Z | torch/csrc/jit/api/object.cpp | Hacky-DH/pytorch | 80dc4be615854570aa39a7e36495897d8a040ecc | [
"Intel"
] | 66,955 | 2017-01-18T17:21:38.000Z | 2022-03-31T23:56:11.000Z | torch/csrc/jit/api/object.cpp | Hacky-DH/pytorch | 80dc4be615854570aa39a7e36495897d8a040ecc | [
"Intel"
] | 19,210 | 2017-01-18T17:45:04.000Z | 2022-03-31T23:51:56.000Z | #include <torch/csrc/jit/api/object.h>
#include <ATen/core/jit_type.h>
#include <torch/csrc/jit/api/compilation_unit.h>
#include <torch/csrc/jit/frontend/resolver.h>
#include <torch/csrc/jit/frontend/sugared_value.h>
namespace torch {
namespace jit {
Object::Object(
std::shared_ptr<CompilationUnit> cu,
const c10::ClassTypePtr& type)
: Object(c10::ivalue::Object::create(
c10::StrongTypePtr(std::move(cu), type),
type->numAttributes())) {}
ObjectPtr Object::_ivalue() const {
TORCH_INTERNAL_ASSERT(_ivalue_);
return _ivalue_;
}
c10::optional<Method> Object::find_method(const std::string& basename) const {
for (Function* fn : type()->methods()) {
if (fn->name() == basename) {
return Method(_ivalue(), fn);
}
}
return c10::nullopt;
}
void Object::define(const std::string& src, const ResolverPtr& resolver) {
const auto self = SimpleSelf(type());
_ivalue()->compilation_unit()->define(
*type()->name(), src, resolver ? resolver : nativeResolver(), &self);
}
Object Object::copy() const {
return Object(_ivalue()->copy());
}
Object Object::deepcopy() const {
return Object(_ivalue()->deepcopy());
}
} // namespace jit
} // namespace torch
| 25.395833 | 78 | 0.674323 | [
"object"
] |
420e5ea0bafd749d1f98c4897f05301b501ba4b8 | 1,280 | cpp | C++ | util/tosha3/tosha3.cpp | Warchant/ed25519-sha3 | b25f5f25b999ae7e86fe779db628c486c5bae24a | [
"Apache-2.0"
] | 24 | 2018-02-08T05:28:44.000Z | 2022-01-16T07:43:47.000Z | util/tosha3/tosha3.cpp | Warchant/ed25519-sha3 | b25f5f25b999ae7e86fe779db628c486c5bae24a | [
"Apache-2.0"
] | 6 | 2018-03-23T20:31:57.000Z | 2019-09-29T09:47:25.000Z | util/tosha3/tosha3.cpp | Warchant/ed25519-sha3 | b25f5f25b999ae7e86fe779db628c486c5bae24a | [
"Apache-2.0"
] | 19 | 2018-02-05T15:54:24.000Z | 2022-01-29T20:08:32.000Z | #include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <ed25519/ed25519.h>
#define STR2(x) #x
#define STR(x) STR2(x)
#include "helpers.hpp"
int main() {
std::ifstream f(STR(TESTDATAIN_PATH));
std::ofstream out(STR(TESTDATAOUT_PATH));
if (!f.is_open()) {
throw std::runtime_error(":(");
}
auto cases = parseTestCases(f);
f.close();
bool hasfailed = false;
for (const auto &c : cases) {
std::string hpriv = c.privkey;
auto sk = make<private_key_t>(hex2bytes(hpriv));
public_key_t pk{};
ed25519_derive_public_key(&sk, &pk);
std::string pub = make_str(&pk, ed25519_pubkey_SIZE);
std::string hpub = bytes2hex((unsigned char *) pub.data(), pub.size());
std::string hmsg = c.message;
std::string hsig = sign(hmsg, hpub, hpriv);
out << hpriv;
out << hpub;
out << ":";
out << hpub;
out << ":";
out << hmsg;
out << ":";
out << hsig;
out << hmsg;
out << ":" << std::endl;
if (!verify(hmsg, hpub, hsig)) {
hasfailed = true;
std::cerr << "sig is invalid" << std::endl;
std::exit(0);
}
}
if (!hasfailed) {
std::cout << "all signatures valid" << std::endl;
}
out.close();
}
| 20.31746 | 75 | 0.576563 | [
"vector"
] |
420e63653b73772bf1d897c9be6e33bf56aea787 | 5,945 | cc | C++ | source/src/io_device.cc | tmadlener/SIO | c68c770649592c03957746e1522256300e31fcab | [
"BSD-3-Clause"
] | 17 | 2016-09-12T15:39:23.000Z | 2021-07-27T00:25:25.000Z | source/src/io_device.cc | tmadlener/SIO | c68c770649592c03957746e1522256300e31fcab | [
"BSD-3-Clause"
] | 88 | 2016-10-03T18:49:06.000Z | 2022-03-23T18:19:28.000Z | source/src/io_device.cc | tmadlener/SIO | c68c770649592c03957746e1522256300e31fcab | [
"BSD-3-Clause"
] | 44 | 2016-09-12T15:42:26.000Z | 2021-12-02T12:33:05.000Z | // -- sio headers
#include <sio/io_device.h>
#include <sio/api.h>
namespace sio {
read_device::read_device( buffer_span buf ) :
_buffer(std::move(buf)) {
/* nop */
}
//--------------------------------------------------------------------------
void read_device::set_buffer( const buffer_span &buf ) {
_buffer = buf ;
}
//--------------------------------------------------------------------------
void read_device::set_buffer( buffer_span &&buf ) {
_buffer = buf ;
}
//--------------------------------------------------------------------------
read_device::cursor_type read_device::position() const {
return _cursor ;
}
//--------------------------------------------------------------------------
void read_device::seek( cursor_type pos ) {
if( pos > _buffer.size() ) {
SIO_THROW( sio::error_code::out_of_range, "Can't seek device cursor: out of range!" ) ;
}
_cursor = pos ;
}
//--------------------------------------------------------------------------
void read_device::pointer_to( ptr_type *ptr ) {
// Read. Keep a record of the "match" quantity read from the buffer and
// the location in memory which will need relocating.
// Placeholder value for 'pointer to'
unsigned int match = 0 ;
data( match ) ;
// Ignore match = 0x00000000. This is basically a null pointer which can
// never be relocated, so don't fill the multimap with a lot of useless
// information.
if( match != 0x00000000 ) {
sio::pointer_to_map::value_type entry = { reinterpret_cast<void *>(match), ptr } ;
_pointer_to.insert( entry ) ;
}
*ptr = static_cast<sio::ptr_type>( match ) ;
}
//--------------------------------------------------------------------------
void read_device::pointed_at( ptr_type *ptr ) {
// Read. Keep a record of the "match" quantity read from the buffer and
// the location in memory which will need relocating.
unsigned int match = 0 ;
data( match ) ;
// Ignore match = SIO_ptag. This is basically a pointer target which was
// never relocated when the record was written. i.e. nothing points to it!
// Don't clutter the maps with information that can never be used.
if( match != 0xffffffff ) {
pointed_at_map::value_type entry = { reinterpret_cast<void *>( match ), ptr } ;
_pointed_at.insert( entry ) ;
}
}
//--------------------------------------------------------------------------
void read_device::pointer_relocation() {
sio::api::read_relocation( _pointed_at, _pointer_to ) ;
_pointer_to.clear() ;
_pointed_at.clear() ;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
write_device::write_device( buffer&& buf ) :
_buffer( std::move( buf ) ) {
/* nop */
}
//--------------------------------------------------------------------------
void write_device::set_buffer( buffer&& buf ) {
_buffer = std::move( buf ) ;
}
//--------------------------------------------------------------------------
buffer write_device::take_buffer() {
return std::move( _buffer ) ;
}
//--------------------------------------------------------------------------
write_device::cursor_type write_device::position() const {
return _cursor ;
}
//--------------------------------------------------------------------------
void write_device::seek( cursor_type pos ) {
if( pos > _buffer.size() ) {
SIO_THROW( sio::error_code::out_of_range, "Can't seek device cursor: out of range!" ) ;
}
_cursor = pos ;
}
//--------------------------------------------------------------------------
void write_device::pointer_to( ptr_type *ptr ) {
// Write. Keep a record of the "match" quantity (i.e. the value of the
// pointer (which may be different lengths on different machines!)) and
// the current offset in the output buffer. Put a placeholder in the
// output buffer (it will be overwritten at the "output relocation" stage).
//
// Placeholder value for 'pointer to'
unsigned int SIO_pntr = 0x00000000 ;
// ptr is really a pointer-to-a-pointer. This routine is most interested
// in the value of *xfer when treated as a pointer. C++ tends to object
// to this as being 'not type safe'. To keep the compiler happy (and purists
// miserable), do one 'reinterpret_cast' immediately to make later code
// easier to read.
// Indirect ptr (actually **ptr)
void *ifer = reinterpret_cast<void *>(*ptr) ;
// Ignore NULL pointers. These are always recorded in the buffer with a
// zero match word (and are treated specially when read back). There's no
// point in putting useless information in the maps.
if( nullptr != ifer ) {
sio::pointer_to_map::value_type entry = { ifer, reinterpret_cast<void *>( _buffer.ptr(_cursor) - _buffer.data() ) } ;
_pointer_to.insert( entry ) ;
}
data( SIO_pntr ) ;
}
//--------------------------------------------------------------------------
void write_device::pointed_at( ptr_type *ptr ) {
// Write. Save the memory location of this object along with the offset
// in the output buffer where the generated match quantity must go. Put
// a placeholder in the output buffer (it will be overwritten at the "output
// relocation" stage).
unsigned int SIO_ptag = 0xffffffff ;
sio::pointed_at_map::value_type entry = { ptr, reinterpret_cast<void *>( _buffer.ptr(_cursor) - _buffer.data() ) } ;
_pointed_at.insert( entry ) ;
data( SIO_ptag ) ;
}
//--------------------------------------------------------------------------
void write_device::pointer_relocation() {
sio::api::write_relocation( _buffer.data(), _pointed_at, _pointer_to ) ;
_pointer_to.clear() ;
_pointed_at.clear() ;
}
}
| 36.030303 | 123 | 0.514718 | [
"object"
] |
420fe25f7c48f5302d174b8c8479ff7d830ff9c8 | 11,562 | hpp | C++ | ngsPopGen/ngsStat.hpp | peterdfields/angsd-wrapper | 199abf0b513a763114511f08dfce742305f41a91 | [
"MIT"
] | 6 | 2015-07-25T02:05:07.000Z | 2021-05-27T08:37:01.000Z | ngsPopGen/ngsStat.hpp | peterdfields/angsd-wrapper | 199abf0b513a763114511f08dfce742305f41a91 | [
"MIT"
] | 60 | 2015-01-10T20:46:25.000Z | 2018-09-19T22:32:02.000Z | ngsPopGen/ngsStat.hpp | peterdfields/angsd-wrapper | 199abf0b513a763114511f08dfce742305f41a91 | [
"MIT"
] | 8 | 2015-04-12T09:37:58.000Z | 2017-04-25T19:30:39.000Z |
/// TEMPLATES
// a general matrix style structure
template <typename T>
struct matrix{
int x;
int y;
T** data;
};
// a general array style structure
template <typename T>
struct array{
int x;
T* data;
};
template <typename T>
T *collapse(std::vector<T> &v){
T *tmp = new T[v.size()];
for(int i=0;i<v.size();i++)
tmp[i] = v[i];
return tmp;
}
//function to cleanup our generic matrix structure
template <typename T>
void cleanup(matrix<T> &m){//using a reference to avoid copying the data
for(int i=0;i<m.x;i++)
delete [] m.data[i];
delete [] m.data;
}
array<int> getStart(int nsites, int firstbase, int block_size) {
// note that firstbase and nsites are 1-based
int len = nsites-firstbase+1;
int nwin = len/block_size;
if ( (len % block_size)!=0) { nwin=nwin+1; }
array<int> start;
start.x=nwin;
int *tStart= new int [nwin];
for (int i=0; i<nwin; i++) {
tStart[i]=(i)*block_size;
}
// if you dont start from beginning
if (firstbase>1) {
for (int i=0; i<nwin; i++) {
tStart[i]=tStart[i]+firstbase-1; // -1 because firstbase is 1-based
}
}
start.data=tStart;
return start;
}
array<int> getEnd(int nsites, int firstbase, int block_size) {
// note that firstbase and nsites are 1-based
int len = nsites-firstbase+1;
int nwin = len/block_size;
if ( (len % block_size)!=0) { nwin=nwin+1; }
array<int> end;
end.x=nwin;
int *tEnd= new int [nwin];
for (int i=0; i<nwin; i++) {
tEnd[i]=(i)*block_size+block_size-1;
}
tEnd[nwin-1]=nsites-1; // nsites is 1 based
// if you dont start from beginning
if (firstbase>0) {
for (int i=0; i<nwin; i++) {
tEnd[i]=tEnd[i]+firstbase-1;
}
}
end.data=tEnd;
return end;
}
// get the filesize of a file
size_t fsize(const char* fname){
struct stat st ;
stat(fname,&st);
return st.st_size;
}
// find out if a file exists
int fexists(const char* str) {
struct stat buffer ;
return (stat(str, &buffer )==0 );
}
// a nice wrapper for getting files
FILE *getFILE(const char*fname,const char* mode) {
int writeFile = 0;
for(size_t i=0;i<strlen(mode);i++)
if(mode[i]=='w')
writeFile = 1;
if(writeFile&&fexists(fname)){//DRAGON
fprintf(stderr,"\t-> File exists: %s exiting...\n",fname);
exit(0);
}
FILE *fp = fopen(fname, mode);
if(fp==NULL){
fprintf(stderr,"\t->Error opening FILE handle for file:%s exiting\n",fname);
fclose(fp);
exit(0);
}
return fp;
}
// read a file of posterior probabilities into a matrix but only for a specific subsets of positions (0-based notation)
matrix<double> readFileSub(char *fname, int nInd, int start, int end, int isfold) {
FILE *fp = getFILE(fname,"r");
size_t filesize =fsize(fname);
if (isfold==0) {
if((filesize %(sizeof(double)*(2*nInd+1)) )) {
fprintf(stderr,"\n\t-> Possible error,binaryfiles might be broken\n");
exit(-1);
}
} else {
if((filesize %(sizeof(double)*(nInd+1)) )) {
fprintf(stderr,"\n\t-> Possible error,binaryfiles might be broken\n");
exit(-1);
}
}
int nsites = end-start+1;
double **data = new double*[nsites];
if (isfold) {
fseek(fp, sizeof(double)*(nInd+1)*start, SEEK_SET);
} else {
fseek(fp, sizeof(double)*(2*nInd+1)*start, SEEK_SET);
}
if (isfold) {
for(int i=0; i<nsites; i++) {
double *tmp = new double[nInd+1];
fread(tmp,sizeof(double),nInd+1,fp);
data[i]= tmp;
}
} else {
for(int i=0; i<nsites; i++) {
double *tmp = new double[2*nInd+1];
fread(tmp,sizeof(double),2*nInd+1,fp);
data[i]= tmp;
}
}
fclose(fp);
matrix<double> ret;
ret.x = nsites;
if (isfold) {
ret.y = nInd+1;
} else {
ret.y = 2*nInd+1;
}
ret.data = data;
return ret;
}
// write an array of doubles into a file
void writearray(array<double> &m,FILE *fp) {
for(int i=0;i<m.x;i++)
fprintf(fp,"%f\t",m.data[i]);
fprintf(fp,"\n");
}
// write an array of ints into a file
void writearrayInt(array<int> &m,FILE *fp) {
for(int i=0;i<m.x;i++)
fprintf(fp,"%d\t",m.data[i]);
fprintf(fp,"\n");
}
// write a matrix of doubles into a file
void writematrix(matrix<double> &m,FILE *fp) {
for(int i=0;i<m.x;i++){
for(int j=0;j<m.y;j++)
fprintf(fp,"%f\t",m.data[i][j]);
fprintf(fp,"\n");
}
}
// write a matrix of ints into a file
void writematrixInt(matrix<int> &m,FILE *fp) {
for(int i=0;i<m.x;i++){
for(int j=0;j<m.y;j++)
fprintf(fp,"%d\t",m.data[i][j]);
fprintf(fp,"\n");
}
}
// to append names
char *append(const char* a,const char *b){
char *c =(char *) malloc((strlen(a)+strlen(b)+1)*sizeof(char));
strcpy(c,a);
strncat(c,b,strlen(b));
return c;
}
// print help
void info() {
fprintf(stdout, "\nInput:\n-npop: how many pops (1 or 2)\n-postfiles: .sfs files with posterior probabilities of sample allele frequencies for each population (with or without running sfstools)\n-outfile: name of the output file\n-nind: number of individuals for each population\n-nsites: total number of sites; in case you want to analyze a subset of sites this is the upper limit\n-verbose: level of verbosity, if 0 suppress all messages\n-block_size: to be memory efficient, set this number as the number of sites you want to analyze at each chunk\n-firstbase: in case you want to analyze a subset of your sites this is the lower limit\n-isfold: boolean, is your data folded or not?\n-islog: boolean, are postfiles in log (from -realSFS 1 only, required if 2D-SFS is given)? If you use sfstools then set -islog 1\n-iswin: if 1 then print the value computed for each non-overlapping window defined by block_size\n\n");
}
// normalize SFS and exp it if log (if from -realSFS 1)
void normSFS(matrix<double> &sfs, int islog) {
int nsites = sfs.x;
int ncol = sfs.y;
double somma = 0.0;
for (int j=0; j<nsites; j++) {
// get the sum of values (do exp if they are in log scale)
somma = 0;
for(int i=0; i<ncol; i++) {
if (islog) {
somma = somma + exp(sfs.data[j][i]);
} else {
somma = somma + sfs.data[j][i];
}
}
// divide each value for the sum
for(int i=0; i<ncol; i++) {
if (islog) {
sfs.data[j][i] = exp(sfs.data[j][i]) / somma;
} else {
sfs.data[j][i] = sfs.data[j][i] / somma;
}
}
}
}
// compute summary stats for each block in case of 1 pop and print the results
void computeStats(matrix<double> &post1, int verbose, FILE *outpost, int iswin, int isfold, int start) {
int nind=0; // sample size
if (isfold) {
nind=(post1.y-1);
} else {
nind=(post1.y-1)/2;
}
int nsites=post1.x;
// init
array<double> segsites;
segsites.x=nsites;
double *tmp1 = new double [nsites];
for (int i=0; i<nsites; i++) {
tmp1[i]=0.0;
}
segsites.data=tmp1;
array<double> hetero;
hetero.x=nsites;
double *tmp2 = new double [nsites];
for (int i=0; i<nsites; i++) {
tmp2[i]=0.0;
}
hetero.data=tmp2;
double temp=0.0;
// to convert from 0 base to 1 base
int start0=start+1;
double sum_segsites = 0.0, sum_hetero = 0.0;
for (int s=0; s<nsites; s++) {
start++;
segsites.data[s] = 1.0 - post1.data[s][0];
if (verbose==2) fprintf(stderr, "\n%f %f", post1.data[s][0], segsites.data[s]);
if (isfold==0) segsites.data[s] = segsites.data[s] - post1.data[s][post1.y-1];
if (verbose==2) fprintf(stderr, " %f %f", post1.data[s][post1.y-1], segsites.data[s]);
temp=0.0;
for (int j=0; j<post1.y; j++) { temp = temp+ 2.0*(j/(nind*2.0))*((nind*2.0-j)/(nind*2.0))*post1.data[s][j]; }
hetero.data[s]=temp;
if (iswin==0) fprintf(outpost, "%d\t%d\t%f\t%f\n", start, start, segsites.data[s], hetero.data[s]);
sum_segsites=sum_segsites+segsites.data[s];
sum_hetero=sum_hetero+hetero.data[s];
} // end cycle s
// compute sum across all sites
if (iswin==1) fprintf(outpost, "%d\t%d\t%f\t%f\n", start0, start, sum_segsites, sum_hetero);
delete [] segsites.data;
delete [] hetero.data;
}
// compute summary stats for each block in case of 2 pops and print the results
void computeStats2Pops(matrix<double> &post1, int verbose, FILE *outpost, int iswin, int isfold, int start, matrix<double> &post2) {
int nind1=0,nind2=0; // sample sizes
if (isfold) {
nind1=(post1.y-1);
nind2=(post2.y-1);
} else {
nind1=(post1.y-1)/2;
nind2=(post2.y-1)/2;
}
int nsites=post1.x;
// init
array<double> segsites1;
segsites1.x=nsites;
array<double> hetero1;
hetero1.x=nsites;
array<double> segsites2;
segsites2.x=nsites;
array<double> hetero2;
hetero2.x=nsites;
array<double> fixed;
fixed.x=nsites;
array<double> dxy;
dxy.x=nsites;
double *tmp1= new double [nsites];
for (int i=0; i<nsites; i++) { tmp1[i]=0.0; }
segsites1.data=tmp1;
double *tmp2= new double [nsites];
for (int i=0; i<nsites; i++) { tmp2[i]=0.0; }
hetero1.data=tmp2;
double *tmp3= new double [nsites];
for (int i=0; i<nsites; i++) { tmp3[i]=0.0; }
segsites2.data=tmp3;
double *tmp4= new double [nsites];
for (int i=0; i<nsites; i++) { tmp4[i]=0.0; }
hetero2.data=tmp4;
double *tmp5= new double [nsites];
for (int i=0; i<nsites; i++) { tmp5[i]=0.0; }
fixed.data=tmp5;
double *tmp6= new double [nsites];
for (int i=0; i<nsites; i++) { tmp6[i]=0.0; }
dxy.data=tmp6;
double temp=0.0;
// to convert from 0 base to 1 base
int start0=start+1;
double sum_segsites1=0.0, sum_hetero1=0.0;
double sum_segsites2=0.0, sum_hetero2=0.0;
double sum_fixed=0.0;
double sum_dxy=0.0;
for (int s=0; s<nsites; s++) {
start++;
segsites1.data[s]= 1.0 - post1.data[s][0];
if (isfold==0) segsites1.data[s]=segsites1.data[s] - post1.data[s][post1.y-1];
temp=0.0;
for (int j=0; j<post1.y; j++) { temp=temp + 2.0*(j/(nind1*2.0))*((nind1*2.0-j)/(nind1*2.0))*post1.data[s][j]; }
hetero1.data[s]=temp;
sum_segsites1=sum_segsites1+segsites1.data[s];
sum_hetero1=sum_hetero1+hetero1.data[s];
segsites2.data[s]= 1.0 - post2.data[s][0];
if (isfold==0) segsites2.data[s]=segsites2.data[s] - post2.data[s][post2.y-1];
temp=0.0;
for (int j=0; j<post2.y; j++) { temp=temp + 2.0*(j/(nind2*2.0))*((nind2*2.0-j)/(nind2*2.0))*post2.data[s][j]; }
hetero2.data[s]=temp;
sum_segsites2=sum_segsites2+segsites2.data[s];
sum_hetero2=sum_hetero2+hetero2.data[s];
if (isfold) {
fixed.data[s]=-999.9;
} else {
fixed.data[s]=post1.data[s][0]*post2.data[s][post2.y-1] + post2.data[s][0]*post1.data[s][post1.y-1];
}
sum_fixed = sum_fixed + fixed.data[s];
if (isfold) {
dxy.data[s]=-999.9;
} else {
dxy.data[s]=0.0;
for (int i=0; i<post1.y; i++) {
for (int j=0; j<post2.y; j++) {
dxy.data[s] = dxy.data[s] + ( ( (i/(nind1*2.0))*(((nind2*2.0)-j)/(nind2*2.0)) + (((nind1*2.0)-i)/(nind1*2.0))*(j/(nind2*2.0)) ) * post1.data[s][i] * post2.data[s][j] ) ;
}
}
}
sum_dxy = sum_dxy + dxy.data[s];
if (iswin==0) fprintf(outpost, "%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\n", start, start, segsites1.data[s], hetero1.data[s], segsites2.data[s], hetero2.data[s], fixed.data[s], dxy.data[s]);
} // end cycle s
// compute sum across all sites
if (iswin==1) fprintf(outpost, "%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\n", start0, start, sum_segsites1, sum_hetero1, sum_segsites2, sum_hetero2, sum_fixed, sum_dxy);
delete [] segsites1.data;
delete [] hetero1.data;
delete [] segsites2.data;
delete [] hetero2.data;
delete [] fixed.data;
delete [] dxy.data;
}
| 27.793269 | 922 | 0.612005 | [
"vector"
] |
421c4388bc9362c81ea9299e2e20e856a39dc414 | 3,577 | cpp | C++ | day07/src/main.cpp | lento234/advent2021 | 1abe10f97a008bea22ece05724b8cd826222fc80 | [
"MIT"
] | 6 | 2021-12-01T23:41:35.000Z | 2021-12-16T23:17:37.000Z | day07/src/main.cpp | lento234/advent2021 | 1abe10f97a008bea22ece05724b8cd826222fc80 | [
"MIT"
] | null | null | null | day07/src/main.cpp | lento234/advent2021 | 1abe10f97a008bea22ece05724b8cd826222fc80 | [
"MIT"
] | 1 | 2021-12-03T22:14:26.000Z | 2021-12-03T22:14:26.000Z | // Advent of Code: Day 07
// Lento Manickathan
#include <algorithm>
#include <chrono>
#include <fmt/ranges.h>
#include <numeric>
#include <string>
#include <vector>
#include <utils/parser.h>
#include <utils/timer.h>
/*
static int64_t problem1_naive(utils::Text<std::string>& input)
{
std::vector<int64_t> positions = utils::split_numbers<int64_t>(input[0], ',');
int64_t least_cost = std::numeric_limits<int64_t>::max();
for (auto& i_pos : positions)
{
int64_t cost = 0;
for (auto& j_pos : positions)
cost += std::abs(i_pos - j_pos);
// Determine least cost
least_cost = std::min(least_cost, cost);
}
// Answer
int64_t answer = least_cost;
return answer;
}
*/
// Best on median: https://en.wikipedia.org/wiki/Median#Optimality_property
static int64_t problem1(utils::Text<std::string>& input)
{
std::vector<int64_t> positions = utils::split_numbers<int64_t>(input[0], ',');
std::sort(positions.begin(), positions.end());
int64_t best_pos = positions[positions.size() / 2]; // median
// Answer
int64_t answer = 0;
for (auto& pos : positions)
answer += std::abs(pos - best_pos);
return answer;
}
// static int64_t problem2_naive(utils::Text<std::string>& input)
// {
// std::vector<int64_t> positions = utils::split_numbers<int64_t>(input[0], ',');
// int64_t least_cost = std::numeric_limits<int64_t>::max();
// for (auto& i_pos : positions)
// {
// int64_t cost = 0;
// for (auto& j_pos : positions)
// {
// int64_t i_cost = std::abs(i_pos - j_pos);
// for (int64_t i = 1; i <= i_cost; ++i)
// cost += i;
// }
// // Determine least cost
// least_cost = std::min(least_cost, cost);
// }
// // Answer
// int64_t answer = least_cost;
// return answer;
// }
// Source : https://www.reddit.com/r/adventofcode/comments/rar7ty/comment/hnk6gz0
static int64_t problem2(utils::Text<std::string>& input)
{
std::vector<int64_t> positions = utils::split_numbers<int64_t>(input[0], ',');
int64_t mean_pos = std::accumulate(positions.begin(), positions.end(), 0) / positions.size();
// Answer
int64_t l = 0, r = 0, d_l, d_r;
for (auto& pos : positions)
{
d_l = std::abs(pos - mean_pos);
d_r = std::abs(pos - mean_pos + 1);
// https://en.wikipedia.org/wiki/Triangular_number
l += d_l * (d_l + 1) / 2;
r += d_r * (d_r + 1) / 2;
}
// Answer
int64_t answer = std::min(l, r);
return answer;
}
int main()
{
auto timeit = utils::Timer();
constexpr uint8_t day = 07;
// Header info
fmt::print("\n🎄 Advent of Code: Day {} 🎄\n", day);
fmt::print("---------------------------\n\n");
// Test input
auto test_input = utils::Text<std::string>("test_input.txt");
int64_t test_answer1 = problem1(test_input);
fmt::print(">> [Test] Problem 1: answer = {} [{}]\n",
test_answer1,
utils::pass_or_fail<int64_t>(test_answer1, 37));
int64_t test_answer2 = problem2(test_input);
fmt::print(">> [Test] Problem 2: answer = {} [{}]\n\n",
test_answer2,
utils::pass_or_fail<int64_t>(test_answer2, 170)); // typo in the original question?
// Read input
auto input = utils::Text<std::string>("input.txt");
// Problem 1
fmt::print(">> Problem 1: answer = {}\n", problem1(input));
// Problem 2
fmt::print(">> Problem 2: answer = {}\n", problem2(input));
}
| 26.894737 | 98 | 0.580375 | [
"vector"
] |
4227017655fa15d83ca9a3b1da6947e4fe5ff5a6 | 3,750 | cc | C++ | usr_local/src/sparrowhawk/src/lib/regexp.cc | parnurzeal/tts-tutorial | db11aed2adc5101cc6d06d1138f74d5f5afe666f | [
"Apache-2.0"
] | 30 | 2016-09-23T06:38:08.000Z | 2022-02-14T02:02:14.000Z | usr_local/src/sparrowhawk/src/lib/regexp.cc | xbsdsongnan/docker-festival | 1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6 | [
"Apache-2.0"
] | 1 | 2017-07-03T06:27:44.000Z | 2017-07-03T06:27:44.000Z | usr_local/src/sparrowhawk/src/lib/regexp.cc | xbsdsongnan/docker-festival | 1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6 | [
"Apache-2.0"
] | 13 | 2016-11-06T05:52:23.000Z | 2020-08-26T18:38:00.000Z | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2015 and onwards Google, Inc.
#include <sparrowhawk/regexp.h>
#include <memory>
#include <sparrowhawk/logger.h>
namespace speech {
namespace sparrowhawk {
Regexp::Regexp() {
re_ = nullptr;
nsubexp_ = -1;
}
Regexp::~Regexp() {
Clear();
}
void Regexp::Clear() {
delete re_;
re_ = nullptr;
nsubexp_ = -1;
}
int Regexp::nsubexp() const {
return nsubexp_;
}
bool Regexp::ok() const {
return re_ != nullptr && re_->ok();
}
bool Regexp::Compile(const string &pattern) {
Clear();
RE2::Options options;
options.set_longest_match(true);
options.set_log_errors(false);
re_ = new RE2(pattern, options);
if (re_ == nullptr) {
LoggerError("Error in allocating regexp \"%s\"", pattern.c_str());
return false;
}
if (!re_->ok()) {
LoggerError("Error in allocating regexp \"%s\": %s",
pattern.c_str(),
re_->error().c_str());
Clear();
return false;
}
nsubexp_ = re_->NumberOfCapturingGroups();
return true;
}
bool Regexp::CheckMatch(const string &input) const {
if (ok()) {
return RE2::PartialMatch(input, *re_);
} else {
return false;
}
}
bool Regexp::CheckFullMatch(const string &input) const {
if (ok()) {
return RE2::FullMatch(input, *re_);
} else {
return false;
}
}
bool Regexp::CheckMatch(const string &input, const string &pattern) {
return RE2::PartialMatch(input, pattern);
}
int Regexp::GetAllMatches(const string &input,
vector<RegMatch> *matches) const {
if (!ok()) {
return 0;
}
int nmatches = 0;
int offset = 0;
int end_pos = input.size();
matches->clear();
re2::StringPiece input_piece(input);
std::unique_ptr<re2::StringPiece[]> matched_pieces(new re2::StringPiece[1 + nsubexp_]);
bool result = re_->Match(input_piece,
offset,
end_pos,
RE2::UNANCHORED,
matched_pieces.get(),
1 + nsubexp_);
RegMatch re_info;
while (result) {
nmatches++;
re_info.sub_str.clear();
re_info.sub_start.clear();
re_info.sub_end.clear();
re_info.full_str = "";
re_info.n_sub = nsubexp_;
int match_offset = matched_pieces[0].data() - input.c_str();
int match_length = matched_pieces[0].length();
re_info.start_char = match_offset;
re_info.end_char = match_offset + match_length;
re_info.len = match_length;
re_info.full_str = matched_pieces[0].as_string();
for (int i = 1; i <= nsubexp_; ++i) {
re_info.sub_str.push_back(matched_pieces[i].as_string());
int sub_match_start = matched_pieces[i].data() - input.c_str();
re_info.sub_start.push_back(sub_match_start);
re_info.sub_end.push_back(sub_match_start + matched_pieces[i].length());
}
matches->push_back(re_info);
offset = re_info.end_char;
result = re_->Match(input_piece,
offset,
end_pos,
RE2::UNANCHORED,
matched_pieces.get(),
1 + nsubexp_);
}
return nmatches;
}
} // namespace sparrowhawk
} // namespace speech
| 26.408451 | 89 | 0.621867 | [
"vector"
] |
423fef5e337e134e7a21ea9407215abbdeb5b147 | 215,723 | cpp | C++ | src/ui/debug/debug_ui.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 3 | 2020-03-05T23:56:14.000Z | 2021-02-17T19:06:50.000Z | src/ui/debug/debug_ui.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-07T01:23:47.000Z | 2021-03-07T01:23:47.000Z | src/ui/debug/debug_ui.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-03T07:54:16.000Z | 2021-03-03T07:54:16.000Z | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version 3.9.0 Dec 31 2020)
// http://www.wxformbuilder.org/
//
// PLEASE DO *NOT* EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "ui/debug/calibration_display_widget.h"
#include "ui/debug/decision_planner_display_widget.h"
#include "ui/debug/evaluation_display_widget.h"
#include "ui/debug/exploration_widget.h"
#include "ui/debug/global_metric_display_widget.h"
#include "ui/debug/global_topo_display_widget.h"
#include "ui/debug/goal_planner_display_widget.h"
#include "ui/debug/local_metric_display_widget.h"
#include "ui/debug/local_topo_display_widget.h"
#include "ui/debug/metric_planner_display_widget.h"
#include "ui/debug/planner_scripting_widget.h"
#include "ui/debug/relocalization_display_widget.h"
#include "ui/debug/tracker_display_widget.h"
#include "ui/debug/vision_display_widget.h"
#include "debug_ui.h"
///////////////////////////////////////////////////////////////////////////
using namespace vulcan::ui;
DebugFrame::DebugFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style)
: UIMainFrame(parent, id, title, pos, size, style)
{
this->SetSizeHints(wxDefaultSize, wxDefaultSize);
wxBoxSizer* debugFrameSizer;
debugFrameSizer = new wxBoxSizer(wxHORIZONTAL);
frameNotebook = new wxAuiNotebook(this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxAUI_NB_SCROLL_BUTTONS | wxAUI_NB_TAB_MOVE | wxAUI_NB_TAB_SPLIT);
localMetricPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* localMetricPanelSizer;
localMetricPanelSizer = new wxBoxSizer(wxHORIZONTAL);
wxFlexGridSizer* localMetricWidgetSizer;
localMetricWidgetSizer = new wxFlexGridSizer(2, 1, 0, 0);
localMetricWidgetSizer->AddGrowableCol(0);
localMetricWidgetSizer->AddGrowableRow(0);
localMetricWidgetSizer->SetFlexibleDirection(wxBOTH);
localMetricWidgetSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
localMetricWidget =
new LocalMetricDisplayWidget(localMetricPanel, ID_LOCAL_METRIC_WIDGET, wxDefaultPosition, wxDefaultSize);
localMetricWidget->SetSize(wxSize(800, 600));
localMetricWidget->SetMinSize(wxSize(0, 0));
localMetricWidgetSizer->Add(localMetricWidget, 0, wxALIGN_CENTER | wxEXPAND, 0);
wxFlexGridSizer* localMetricInfoSizer;
localMetricInfoSizer = new wxFlexGridSizer(3, 6, 0, 0);
localMetricInfoSizer->SetFlexibleDirection(wxBOTH);
localMetricInfoSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
poseLabel = new wxStaticText(localMetricPanel, wxID_ANY, wxT("Pose:"), wxDefaultPosition, wxDefaultSize, 0);
poseLabel->Wrap(-1);
poseLabel->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(poseLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
poseDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(00.00, 00.00, 0.00)"), wxDefaultPosition, wxDefaultSize, 0);
poseDisplay->Wrap(-1);
poseDisplay->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(poseDisplay, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
measuredVelLabel =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("Velocity:"), wxDefaultPosition, wxDefaultSize, 0);
measuredVelLabel->Wrap(-1);
measuredVelLabel->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(measuredVelLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
velocityDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(+0.00, +0.00)"), wxDefaultPosition, wxDefaultSize, 0);
velocityDisplay->Wrap(-1);
velocityDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(velocityDisplay, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
imuLabel = new wxStaticText(localMetricPanel, wxID_ANY, wxT("IMU: Accel:"), wxDefaultPosition, wxDefaultSize, 0);
imuLabel->Wrap(-1);
imuLabel->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(imuLabel, 0, wxALIGN_CENTER | wxALIGN_RIGHT | wxALL, 5);
imuAccelDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(0.00, 0.00, 0.00)"), wxDefaultPosition, wxDefaultSize, 0);
imuAccelDisplay->Wrap(-1);
imuAccelDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(imuAccelDisplay, 0, wxALL, 5);
commandLabel = new wxStaticText(localMetricPanel, wxID_ANY, wxT("Command:"), wxDefaultPosition, wxDefaultSize, 0);
commandLabel->Wrap(-1);
commandLabel->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(commandLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
commandDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(0.00, 0.00)"), wxDefaultPosition, wxDefaultSize, 0);
commandDisplay->Wrap(-1);
commandDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(commandDisplay, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
leftWheelLabel =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("Wheels: Left:"), wxDefaultPosition, wxDefaultSize, 0);
leftWheelLabel->Wrap(-1);
leftWheelLabel->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(leftWheelLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
leftWheelDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(+0.00, +0.00)"), wxDefaultPosition, wxDefaultSize, 0);
leftWheelDisplay->Wrap(-1);
leftWheelDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(leftWheelDisplay, 0, wxALL, 5);
imuVelocityLabel =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("Velocity:"), wxDefaultPosition, wxDefaultSize, 0);
imuVelocityLabel->Wrap(-1);
imuVelocityLabel->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(imuVelocityLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
imuVelocityDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(0.00, 0.00, 0.00)"), wxDefaultPosition, wxDefaultSize, 0);
imuVelocityDisplay->Wrap(-1);
imuVelocityDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(imuVelocityDisplay, 0, wxALL, 5);
m_staticline2 = new wxStaticLine(localMetricPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL);
localMetricInfoSizer->Add(m_staticline2, 0, wxEXPAND | wxALL, 5);
m_staticline3 = new wxStaticLine(localMetricPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL);
localMetricInfoSizer->Add(m_staticline3, 0, wxEXPAND | wxALL, 5);
rightWheelLabel = new wxStaticText(localMetricPanel, wxID_ANY, wxT("Right:"), wxDefaultPosition, wxDefaultSize, 0);
rightWheelLabel->Wrap(-1);
rightWheelLabel->SetFont(wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(rightWheelLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
rightWheelDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(+0.00, +0.00)"), wxDefaultPosition, wxDefaultSize, 0);
rightWheelDisplay->Wrap(-1);
rightWheelDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(rightWheelDisplay, 0, wxALL, 5);
imuOrientationLabel =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("Orientation:"), wxDefaultPosition, wxDefaultSize, 0);
imuOrientationLabel->Wrap(-1);
imuOrientationLabel->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Sans")));
localMetricInfoSizer->Add(imuOrientationLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
imuOrientationDisplay =
new wxStaticText(localMetricPanel, wxID_ANY, wxT("(0.00, 0.00, 0.00)"), wxDefaultPosition, wxDefaultSize, 0);
imuOrientationDisplay->Wrap(-1);
imuOrientationDisplay->SetFont(
wxFont(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Fixed")));
localMetricInfoSizer->Add(imuOrientationDisplay, 0, wxALL, 5);
localMetricWidgetSizer->Add(localMetricInfoSizer, 1, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
localMetricPanelSizer->Add(localMetricWidgetSizer, 1, wxALL | wxEXPAND, 5);
localMetricScrollWindow =
new wxScrolledWindow(localMetricPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
localMetricScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* localMetricOptionsSizer;
localMetricOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
localMetricOptionsSizer->SetFlexibleDirection(wxBOTH);
localMetricOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxString localMetricModeBoxChoices[] = {wxT("SLAM"),
wxT("SLAM + Glass"),
wxT("Localization Only"),
wxT("High Resolution")};
int localMetricModeBoxNChoices = sizeof(localMetricModeBoxChoices) / sizeof(wxString);
localMetricModeBox = new wxRadioBox(localMetricScrollWindow,
ID_LOCAL_METRIC_MODE_BOX,
wxT("Local Metric Mode"),
wxDefaultPosition,
wxDefaultSize,
localMetricModeBoxNChoices,
localMetricModeBoxChoices,
1,
wxRA_SPECIFY_COLS);
localMetricModeBox->SetSelection(0);
localMetricOptionsSizer->Add(localMetricModeBox, 0, wxALL | wxEXPAND, 5);
centerOnRobotCheckBox = new wxCheckBox(localMetricScrollWindow,
ID_CENTER_ON_ROBOT,
wxT("Center On Robot"),
wxDefaultPosition,
wxDefaultSize,
0);
centerOnRobotCheckBox->SetValue(true);
localMetricOptionsSizer->Add(centerOnRobotCheckBox, 0, wxALL, 5);
wxString metricGridToShowRadioChoices[] = {wxT("LPM"), wxT("Glass"), wxT("None")};
int metricGridToShowRadioNChoices = sizeof(metricGridToShowRadioChoices) / sizeof(wxString);
metricGridToShowRadio = new wxRadioBox(localMetricScrollWindow,
ID_METRIC_GRID_TO_SHOW_RADIO,
wxT("Grid to Show"),
wxDefaultPosition,
wxDefaultSize,
metricGridToShowRadioNChoices,
metricGridToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
metricGridToShowRadio->SetSelection(0);
localMetricOptionsSizer->Add(metricGridToShowRadio, 1, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* laserDisplayOptionsSizer;
laserDisplayOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localMetricScrollWindow, wxID_ANY, wxT("Laser Display Options")),
wxVERTICAL);
wxString laserToShowRadioChoices[] = {wxT("Raw Laser"), wxT("Mapping Laser"), wxT("Reflected Laser"), wxT("None")};
int laserToShowRadioNChoices = sizeof(laserToShowRadioChoices) / sizeof(wxString);
laserToShowRadio = new wxRadioBox(laserDisplayOptionsSizer->GetStaticBox(),
ID_LASER_TO_SHOW_RADIO,
wxT("Laser To Show:"),
wxDefaultPosition,
wxDefaultSize,
laserToShowRadioNChoices,
laserToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
laserToShowRadio->SetSelection(0);
laserDisplayOptionsSizer->Add(laserToShowRadio, 0, wxALL | wxEXPAND, 5);
scanLineCheckBox = new wxCheckBox(laserDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_LASER_LINES_BOX,
wxT("Show Laser Rays"),
wxDefaultPosition,
wxDefaultSize,
0);
laserDisplayOptionsSizer->Add(scanLineCheckBox, 0, wxALL, 5);
showExtractedLinesCheckBox = new wxCheckBox(laserDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_EXTRACTED_LINES_BOX,
wxT("Show Extracted Lines"),
wxDefaultPosition,
wxDefaultSize,
0);
laserDisplayOptionsSizer->Add(showExtractedLinesCheckBox, 0, wxALL, 5);
showIntensityPlotsCheckBox = new wxCheckBox(laserDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_INTENSITY_PLOTS_BOX,
wxT("Show intensity Plots"),
wxDefaultPosition,
wxDefaultSize,
0);
laserDisplayOptionsSizer->Add(showIntensityPlotsCheckBox, 0, wxALL | wxEXPAND, 5);
localMetricOptionsSizer->Add(laserDisplayOptionsSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* localizationOptionsSizer;
localizationOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localMetricScrollWindow, wxID_ANY, wxT("Localization Display Options")),
wxVERTICAL);
showPoseTraceCheckBox = new wxCheckBox(localizationOptionsSizer->GetStaticBox(),
ID_SHOW_POSE_TRACE,
wxT("Show Pose Trace"),
wxDefaultPosition,
wxDefaultSize,
0);
showPoseTraceCheckBox->SetValue(true);
localizationOptionsSizer->Add(showPoseTraceCheckBox, 0, wxALL, 5);
showMotionTraceCheckBox = new wxCheckBox(localizationOptionsSizer->GetStaticBox(),
ID_SHOW_MOTION_TRACE_BOX,
wxT("Show Motion Trace"),
wxDefaultPosition,
wxDefaultSize,
0);
showMotionTraceCheckBox->SetValue(true);
localizationOptionsSizer->Add(showMotionTraceCheckBox, 0, wxALL, 5);
showUncertaintyEllipseCheckBox = new wxCheckBox(localizationOptionsSizer->GetStaticBox(),
ID_SHOW_UNCERTAINTY_ELLIPSE,
wxT("Show Error Ellipse"),
wxDefaultPosition,
wxDefaultSize,
0);
showUncertaintyEllipseCheckBox->SetValue(true);
localizationOptionsSizer->Add(showUncertaintyEllipseCheckBox, 0, wxALL, 5);
showParticlesCheckBox = new wxCheckBox(localizationOptionsSizer->GetStaticBox(),
ID_SHOW_PARTICLES,
wxT("Show Particles"),
wxDefaultPosition,
wxDefaultSize,
0);
showParticlesCheckBox->SetValue(true);
localizationOptionsSizer->Add(showParticlesCheckBox, 0, wxALL, 5);
wxBoxSizer* cleanButtonsSizer;
cleanButtonsSizer = new wxBoxSizer(wxHORIZONTAL);
clearPosesButton = new wxButton(localizationOptionsSizer->GetStaticBox(),
ID_CLEAR_POSES_BUTTON,
wxT("Clear Poses"),
wxDefaultPosition,
wxDefaultSize,
0);
cleanButtonsSizer->Add(clearPosesButton, 0, wxALIGN_CENTER | wxALL, 5);
clearMotionButton = new wxButton(localizationOptionsSizer->GetStaticBox(),
ID_CLEAR_MOTION_BUTTON,
wxT("Clear Motion"),
wxDefaultPosition,
wxDefaultSize,
0);
cleanButtonsSizer->Add(clearMotionButton, 0, wxALL, 5);
localizationOptionsSizer->Add(cleanButtonsSizer, 1, wxEXPAND, 5);
localMetricOptionsSizer->Add(localizationOptionsSizer, 1, wxALIGN_RIGHT | wxEXPAND, 5);
wxStaticBoxSizer* glassMapOptionsSizer;
glassMapOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localMetricScrollWindow, wxID_ANY, wxT("Glass Map Options")), wxVERTICAL);
showGlassIntensityCheckBox = new wxCheckBox(glassMapOptionsSizer->GetStaticBox(),
ID_SHOW_GLASS_INTENSITY_BOX,
wxT("Show Glass Intensity"),
wxDefaultPosition,
wxDefaultSize,
0);
glassMapOptionsSizer->Add(showGlassIntensityCheckBox, 0, wxALL, 5);
showGlassWallsCheckBox = new wxCheckBox(glassMapOptionsSizer->GetStaticBox(),
ID_SHOW_GLASS_WALLS_BOX,
wxT("Show Glass Walls"),
wxDefaultPosition,
wxDefaultSize,
0);
glassMapOptionsSizer->Add(showGlassWallsCheckBox, 0, wxALL, 5);
showGlassAnglesCheckBox = new wxCheckBox(glassMapOptionsSizer->GetStaticBox(),
ID_SHOW_GLASS_ANGLES_BOX,
wxT("Show Glass Angles"),
wxDefaultPosition,
wxDefaultSize,
0);
glassMapOptionsSizer->Add(showGlassAnglesCheckBox, 0, wxALL, 5);
wxString glassAnglesToShowRadioChoices[] = {wxT("Normal"), wxT("Range")};
int glassAnglesToShowRadioNChoices = sizeof(glassAnglesToShowRadioChoices) / sizeof(wxString);
glassAnglesToShowRadio = new wxRadioBox(glassMapOptionsSizer->GetStaticBox(),
ID_GLASS_ANGLES_TO_SHOW_RADIO,
wxT("Angles to Show"),
wxDefaultPosition,
wxDefaultSize,
glassAnglesToShowRadioNChoices,
glassAnglesToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
glassAnglesToShowRadio->SetSelection(0);
glassMapOptionsSizer->Add(glassAnglesToShowRadio, 0, wxALL | wxEXPAND, 5);
wxFlexGridSizer* glassSidersSizer;
glassSidersSizer = new wxFlexGridSizer(2, 2, 0, 0);
glassSidersSizer->AddGrowableCol(1);
glassSidersSizer->SetFlexibleDirection(wxHORIZONTAL);
glassSidersSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
flattenThreshLabel = new wxStaticText(glassMapOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Flatten:"),
wxDefaultPosition,
wxDefaultSize,
0);
flattenThreshLabel->Wrap(-1);
glassSidersSizer->Add(flattenThreshLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
glassFlattenThreshSlider = new wxSlider(glassMapOptionsSizer->GetStaticBox(),
wxID_ANY,
2,
1,
25,
wxDefaultPosition,
wxDefaultSize,
wxSL_AUTOTICKS | wxSL_HORIZONTAL | wxSL_LABELS);
glassSidersSizer->Add(glassFlattenThreshSlider, 1, wxALL | wxEXPAND, 5);
highlyVisibleGlassThreshLabel = new wxStaticText(glassMapOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Highly-visible:"),
wxDefaultPosition,
wxDefaultSize,
0);
highlyVisibleGlassThreshLabel->Wrap(-1);
glassSidersSizer->Add(highlyVisibleGlassThreshLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
glassHighlyVisibleThreshSlider = new wxSlider(glassMapOptionsSizer->GetStaticBox(),
wxID_ANY,
10,
5,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_AUTOTICKS | wxSL_HORIZONTAL | wxSL_LABELS);
glassSidersSizer->Add(glassHighlyVisibleThreshSlider, 1, wxALL | wxEXPAND, 5);
glassMapOptionsSizer->Add(glassSidersSizer, 1, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
runFlattenMapButton = new wxButton(glassMapOptionsSizer->GetStaticBox(),
ID_RUN_FLATTEN_MAP_BUTTON,
wxT("Run Flatten Map"),
wxDefaultPosition,
wxDefaultSize,
0);
glassMapOptionsSizer->Add(runFlattenMapButton, 0, wxALL | wxEXPAND, 5);
runDynamicFilterButton = new wxButton(glassMapOptionsSizer->GetStaticBox(),
ID_RUN_DYNAMIC_FILTER_BUTTON,
wxT("Run Dynamic Filter"),
wxDefaultPosition,
wxDefaultSize,
0);
glassMapOptionsSizer->Add(runDynamicFilterButton, 0, wxALL | wxEXPAND, 5);
localMetricOptionsSizer->Add(glassMapOptionsSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* rotateSizer;
rotateSizer =
new wxStaticBoxSizer(new wxStaticBox(localMetricScrollWindow, wxID_ANY, wxT("Rotation Test (Degrees)")),
wxHORIZONTAL);
rotateLPMText =
new wxTextCtrl(rotateSizer->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
#ifdef __WXGTK__
if (!rotateLPMText->HasFlag(wxTE_MULTILINE)) {
rotateLPMText->SetMaxLength(5);
}
#else
rotateLPMText->SetMaxLength(5);
#endif
rotateSizer->Add(rotateLPMText, 0, wxALIGN_CENTER | wxALL, 5);
rotateLPMButton = new wxButton(rotateSizer->GetStaticBox(),
ID_ROTATE_LPM_BUTTON,
wxT("Rotate"),
wxDefaultPosition,
wxDefaultSize,
0);
rotateSizer->Add(rotateLPMButton, 0, wxALL, 5);
localMetricOptionsSizer->Add(rotateSizer, 1, wxEXPAND, 5);
saveCurrentLPMButton = new wxButton(localMetricScrollWindow,
ID_SAVE_CURRENT_LPM_BUTTON,
wxT("Save Current LPM"),
wxDefaultPosition,
wxDefaultSize,
0);
saveCurrentLPMButton->SetToolTip(
wxT("Save the current LPM being displayed as \"current.lpm\" in the current working directory."));
localMetricOptionsSizer->Add(saveCurrentLPMButton, 0, wxALL | wxEXPAND, 5);
saveGlassMapButton = new wxButton(localMetricScrollWindow,
ID_SAVE_GLASS_MAP_BUTTON,
wxT("Save Glass Map"),
wxDefaultPosition,
wxDefaultSize,
0);
saveGlassMapButton->SetToolTip(wxT("Tell local_metric_hssh to save the current glass map as \"current_glass.map\" "
"in the working directory of local_metric_hssh."));
localMetricOptionsSizer->Add(saveGlassMapButton, 0, wxALL | wxEXPAND, 5);
loadGlassMapButton = new wxButton(localMetricScrollWindow,
ID_LOAD_GLASS_MAP_BUTTON,
wxT("Load Glass Map"),
wxDefaultPosition,
wxDefaultSize,
0);
localMetricOptionsSizer->Add(loadGlassMapButton, 0, wxALL | wxEXPAND, 5);
savePosesButton = new wxButton(localMetricScrollWindow,
ID_SAVE_POSES_BUTTON,
wxT("Save Glass Poses"),
wxDefaultPosition,
wxDefaultSize,
0);
savePosesButton->SetToolTip(wxT(
"Tell local_metric_hssh to save all poses from which the map is updated. Needed for glass mapping evaluation."));
localMetricOptionsSizer->Add(savePosesButton, 0, wxALL | wxEXPAND, 5);
saveScansButton = new wxButton(localMetricScrollWindow,
ID_SAVE_SCANS_BUTTON,
wxT("Save Glass Scans"),
wxDefaultPosition,
wxDefaultSize,
0);
saveScansButton->SetToolTip(wxT("Tell local_metric_hssh to save every scan it uses to update the map. Needed for "
"helping with the glass mapping evaluation."));
localMetricOptionsSizer->Add(saveScansButton, 0, wxALL | wxEXPAND, 5);
localMetricScrollWindow->SetSizer(localMetricOptionsSizer);
localMetricScrollWindow->Layout();
localMetricOptionsSizer->Fit(localMetricScrollWindow);
localMetricPanelSizer->Add(localMetricScrollWindow, 0, wxALL | wxEXPAND, 5);
localMetricPanel->SetSizer(localMetricPanelSizer);
localMetricPanel->Layout();
localMetricPanelSizer->Fit(localMetricPanel);
frameNotebook->AddPage(localMetricPanel, wxT("Local Metric"), false, wxNullBitmap);
metricPlannerPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* metricPlannerSizer;
metricPlannerSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* metricPlannerWidgetSizer;
metricPlannerWidgetSizer = new wxBoxSizer(wxVERTICAL);
metricPlannerWidget =
new MetricPlannerDisplayWidget(metricPlannerPanel, ID_METRIC_PLANNER_WIDGET, wxDefaultPosition, wxDefaultSize);
metricPlannerWidget->SetSize(wxSize(800, 600));
metricPlannerWidget->SetMinSize(wxSize(0, 0));
metricPlannerWidgetSizer->Add(metricPlannerWidget, 1, wxALIGN_CENTER | wxEXPAND, 0);
metricPlannerSizer->Add(metricPlannerWidgetSizer, 1, wxALL | wxEXPAND, 5);
metricPlannerScrollWindow =
new wxScrolledWindow(metricPlannerPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
metricPlannerScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* metricPlannerOptionsSizer;
metricPlannerOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
metricPlannerOptionsSizer->SetFlexibleDirection(wxBOTH);
metricPlannerOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxStaticBoxSizer* mainDisplayOptionsSizer;
mainDisplayOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("Main Display Options")),
wxVERTICAL);
wxFlexGridSizer* displayOptionsGridSizer;
displayOptionsGridSizer = new wxFlexGridSizer(0, 2, 0, 0);
displayOptionsGridSizer->SetFlexibleDirection(wxBOTH);
displayOptionsGridSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
showRobotCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_ROBOT_POSE_CHECKBOX,
wxT("Robot"),
wxDefaultPosition,
wxDefaultSize,
0);
showRobotCheckBox->SetValue(true);
displayOptionsGridSizer->Add(showRobotCheckBox, 0, wxALL, 5);
showTrackedObjectsCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_TRACKED_OBJECTS_CHECKBOX,
wxT("Tracked Objects"),
wxDefaultPosition,
wxDefaultSize,
0);
showTrackedObjectsCheckBox->SetValue(true);
displayOptionsGridSizer->Add(showTrackedObjectsCheckBox, 0, wxALL, 5);
showDestinationPoseCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_DESTINATION_POSE_CHECKBOX,
wxT("Destination"),
wxDefaultPosition,
wxDefaultSize,
0);
showDestinationPoseCheckBox->SetValue(true);
displayOptionsGridSizer->Add(showDestinationPoseCheckBox, 0, wxALL, 5);
showObjectsMotionCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_OBJECTS_MOTION_CHECKBOX,
wxT("Estimated Objects Motion"),
wxDefaultPosition,
wxDefaultSize,
0);
showObjectsMotionCheckBox->SetValue(true);
displayOptionsGridSizer->Add(showObjectsMotionCheckBox, 0, wxALL, 5);
showOptimalPathCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_OPTIMAL_PATH_CHECKBOX,
wxT("Optimal Path"),
wxDefaultPosition,
wxDefaultSize,
0);
displayOptionsGridSizer->Add(showOptimalPathCheckBox, 0, wxALL | wxEXPAND, 5);
showVisibilityAnalysisCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_VISIBILITY_ANALYSIS_CHECKBOX,
wxT("Visibility Analysis"),
wxDefaultPosition,
wxDefaultSize,
0);
displayOptionsGridSizer->Add(showVisibilityAnalysisCheckBox, 0, wxALL, 5);
showSituationsCheckBox = new wxCheckBox(mainDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_SITUATIONS_CHECKBOX,
wxT("Situations"),
wxDefaultPosition,
wxDefaultSize,
0);
displayOptionsGridSizer->Add(showSituationsCheckBox, 0, wxALL | wxEXPAND, 5);
mainDisplayOptionsSizer->Add(displayOptionsGridSizer, 1, wxEXPAND, 5);
metricPlannerOptionsSizer->Add(mainDisplayOptionsSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* destinationPoseSizer;
destinationPoseSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("Destination Pose")), wxHORIZONTAL);
selectDestinationPoseButton = new wxButton(destinationPoseSizer->GetStaticBox(),
ID_SELECT_DESTINATION_POSE_BUTTON,
wxT("Select"),
wxDefaultPosition,
wxDefaultSize,
0);
destinationPoseSizer->Add(selectDestinationPoseButton, 0, wxALIGN_CENTER | wxALL, 5);
sendDestinationPoseButton = new wxButton(destinationPoseSizer->GetStaticBox(),
ID_SEND_DESTINATION_POSE_BUTTON,
wxT("Send"),
wxDefaultPosition,
wxDefaultSize,
0);
destinationPoseSizer->Add(sendDestinationPoseButton, 0, wxALIGN_CENTER | wxALL, 5);
cancelDestinationPoseButton = new wxButton(destinationPoseSizer->GetStaticBox(),
ID_CANCEL_DESTINATION_POSE_BUTTON,
wxT("Cancel"),
wxDefaultPosition,
wxDefaultSize,
0);
destinationPoseSizer->Add(cancelDestinationPoseButton, 0, wxALIGN_CENTER | wxALL, 5);
metricPlannerOptionsSizer->Add(destinationPoseSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* metricScriptOptionsSizer;
metricScriptOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("Script Options")), wxVERTICAL);
wxGridSizer* metricScriptSelectionSizer;
metricScriptSelectionSizer = new wxGridSizer(0, 2, 0, 0);
metricScriptFileText = new wxTextCtrl(metricScriptOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Enter script name"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(metricScriptFileText, 1, wxALL | wxEXPAND, 5);
metricLoadScriptButton = new wxButton(metricScriptOptionsSizer->GetStaticBox(),
ID_METRIC_LOAD_SCRIPT_BUTTON,
wxT("Load Script"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(metricLoadScriptButton, 0, wxALL | wxEXPAND, 5);
sendWaypointsButton = new wxButton(metricScriptOptionsSizer->GetStaticBox(),
ID_SEND_WAYPOINTS_BUTTON,
wxT("Send"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(sendWaypointsButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
skipWaypointButton = new wxButton(metricScriptOptionsSizer->GetStaticBox(),
ID_SKIP_WAYPOINT_BUTTON,
wxT("Skip"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(skipWaypointButton, 0, wxALL | wxEXPAND, 5);
cancelFollowingButton = new wxButton(metricScriptOptionsSizer->GetStaticBox(),
ID_CANCEL_FOLLOWING_BUTTON,
wxT("Stop/Cancel"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(cancelFollowingButton, 0, wxALL | wxEXPAND, 5);
loopWaypointsButton = new wxButton(metricScriptOptionsSizer->GetStaticBox(),
ID_LOOP_WAYPOINTS_BUTTON,
wxT("Loop"),
wxDefaultPosition,
wxDefaultSize,
0);
metricScriptSelectionSizer->Add(loopWaypointsButton, 0, wxALL | wxEXPAND, 5);
metricScriptOptionsSizer->Add(metricScriptSelectionSizer, 1, wxEXPAND, 5);
metricPlannerOptionsSizer->Add(metricScriptOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* mpepcOptionsSizer;
mpepcOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("MPEPC Options")), wxVERTICAL);
wxGridBagSizer* mpepcGridBag;
mpepcGridBag = new wxGridBagSizer(0, 0);
mpepcGridBag->SetFlexibleDirection(wxBOTH);
mpepcGridBag->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxString selectMapTypeRadioBoxChoices[] = {wxT("LPM"),
wxT("Obstacle Distance"),
wxT("Cost Map"),
wxT("Navigation Function"),
wxT("Flow Grid"),
wxT("None")};
int selectMapTypeRadioBoxNChoices = sizeof(selectMapTypeRadioBoxChoices) / sizeof(wxString);
selectMapTypeRadioBox = new wxRadioBox(mpepcOptionsSizer->GetStaticBox(),
ID_SELECT_MAP_TYPE_RADIOBOX,
wxT("Map Type"),
wxDefaultPosition,
wxDefaultSize,
selectMapTypeRadioBoxNChoices,
selectMapTypeRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
selectMapTypeRadioBox->SetSelection(0);
mpepcGridBag->Add(selectMapTypeRadioBox, wxGBPosition(0, 0), wxGBSpan(1, 1), wxALL | wxEXPAND, 5);
wxString selectTrjGroupRadioBoxChoices[] =
{wxT("Current"), wxT("Optimal"), wxT("History"), wxT("None"), wxT("Last 3 Sec"), wxT("Last 5 Sec")};
int selectTrjGroupRadioBoxNChoices = sizeof(selectTrjGroupRadioBoxChoices) / sizeof(wxString);
selectTrjGroupRadioBox = new wxRadioBox(mpepcOptionsSizer->GetStaticBox(),
ID_SELECT_TRJ_GROUP_RADIOBOX,
wxT("Trajectory Type"),
wxDefaultPosition,
wxDefaultSize,
selectTrjGroupRadioBoxNChoices,
selectTrjGroupRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
selectTrjGroupRadioBox->SetSelection(0);
mpepcGridBag->Add(selectTrjGroupRadioBox, wxGBPosition(0, 1), wxGBSpan(1, 2), wxALL | wxEXPAND, 5);
trjCostChoiceLabel = new wxStaticText(mpepcOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Cost Type Displayed:"),
wxDefaultPosition,
wxDefaultSize,
0);
trjCostChoiceLabel->Wrap(-1);
mpepcGridBag->Add(trjCostChoiceLabel,
wxGBPosition(1, 0),
wxGBSpan(1, 1),
wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL,
5);
wxArrayString trajectoryCostChoiceChoices;
trajectoryCostChoice = new wxChoice(mpepcOptionsSizer->GetStaticBox(),
ID_SELECT_TRJ_COST_CHOICE,
wxDefaultPosition,
wxDefaultSize,
trajectoryCostChoiceChoices,
0);
trajectoryCostChoice->SetSelection(0);
mpepcGridBag->Add(trajectoryCostChoice, wxGBPosition(1, 1), wxGBSpan(1, 2), wxALL | wxEXPAND, 5);
wxString trjDisplayModeRadioBoxChoices[] = {wxT("All"), wxT("Last N"), wxT("Single")};
int trjDisplayModeRadioBoxNChoices = sizeof(trjDisplayModeRadioBoxChoices) / sizeof(wxString);
trjDisplayModeRadioBox = new wxRadioBox(mpepcOptionsSizer->GetStaticBox(),
ID_SELECT_TRJ_DISPLAY_MODE_RADIOBOX,
wxT("Trajectories Displayed"),
wxDefaultPosition,
wxDefaultSize,
trjDisplayModeRadioBoxNChoices,
trjDisplayModeRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
trjDisplayModeRadioBox->SetSelection(0);
mpepcGridBag->Add(trjDisplayModeRadioBox, wxGBPosition(2, 0), wxGBSpan(3, 1), wxALL, 5);
trajectoryCountLabel = new wxStaticText(mpepcOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Total Count (Current): 0"),
wxDefaultPosition,
wxDefaultSize,
0);
trajectoryCountLabel->Wrap(-1);
mpepcGridBag->Add(trajectoryCountLabel, wxGBPosition(2, 1), wxGBSpan(1, 2), wxALIGN_LEFT | wxALL, 5);
numTrajectoriesText = new wxTextCtrl(mpepcOptionsSizer->GetStaticBox(),
ID_CHANGE_TRJ_NUM_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
wxTE_PROCESS_ENTER | wxTE_RIGHT);
#ifdef __WXGTK__
if (!numTrajectoriesText->HasFlag(wxTE_MULTILINE)) {
numTrajectoriesText->SetMaxLength(5);
}
#else
numTrajectoriesText->SetMaxLength(5);
#endif
mpepcGridBag->Add(numTrajectoriesText, wxGBPosition(3, 1), wxGBSpan(1, 2), wxALIGN_CENTER | wxALL | wxEXPAND, 5);
decreaseTrajectoriesButton = new wxButton(mpepcOptionsSizer->GetStaticBox(),
ID_DECREASE_TRJ_NUM_BUTTON,
wxT("<"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
mpepcGridBag->Add(decreaseTrajectoriesButton, wxGBPosition(4, 1), wxGBSpan(1, 1), wxALL, 5);
increaseTrajectoriesButton = new wxButton(mpepcOptionsSizer->GetStaticBox(),
ID_INCREASE_TRJ_NUM_BUTTON,
wxT(">"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
mpepcGridBag->Add(increaseTrajectoriesButton, wxGBPosition(4, 2), wxGBSpan(1, 1), wxALIGN_RIGHT | wxALL, 5);
wxStaticBoxSizer* trajectoryDisplayOptionsSizer;
trajectoryDisplayOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(mpepcOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Display Options")),
wxVERTICAL);
showMotionTargetCheckBox = new wxCheckBox(trajectoryDisplayOptionsSizer->GetStaticBox(),
ID_SHOW_MOTION_TARGETS_CHECKBOX,
wxT("Motion Targets"),
wxDefaultPosition,
wxDefaultSize,
0);
trajectoryDisplayOptionsSizer->Add(showMotionTargetCheckBox, 0, wxALL, 5);
overlayRobotPosesCheckBox = new wxCheckBox(trajectoryDisplayOptionsSizer->GetStaticBox(),
ID_OVERLAY_ROBOT_POSES_CHECKBOX,
wxT("Overlay Pose"),
wxDefaultPosition,
wxDefaultSize,
0);
trajectoryDisplayOptionsSizer->Add(overlayRobotPosesCheckBox, 0, wxALL, 5);
mpepcGridBag->Add(trajectoryDisplayOptionsSizer, wxGBPosition(5, 0), wxGBSpan(2, 1), wxALL | wxEXPAND, 5);
evaluatedCostLabel = new wxStaticText(mpepcOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Evaluated Cost (Single)"),
wxDefaultPosition,
wxDefaultSize,
0);
evaluatedCostLabel->Wrap(-1);
mpepcGridBag->Add(evaluatedCostLabel,
wxGBPosition(5, 1),
wxGBSpan(1, 2),
wxALIGN_BOTTOM | wxALIGN_CENTER | wxALL,
5);
evaluatedCostText =
new wxStaticText(mpepcOptionsSizer->GetStaticBox(), wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0);
evaluatedCostText->Wrap(-1);
mpepcGridBag->Add(evaluatedCostText, wxGBPosition(6, 1), wxGBSpan(1, 2), wxALIGN_CENTER | wxALIGN_TOP | wxALL, 5);
mpepcOptionsSizer->Add(mpepcGridBag, 1, wxALIGN_RIGHT | wxEXPAND, 5);
metricPlannerOptionsSizer->Add(mpepcOptionsSizer, 1, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* simulationTargetOptionsSizer;
simulationTargetOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("Simultation Target Options")),
wxVERTICAL);
wxFlexGridSizer* motionTargetCoordsSizer;
motionTargetCoordsSizer = new wxFlexGridSizer(0, 0, 0, 0);
motionTargetCoordsSizer->SetFlexibleDirection(wxBOTH);
motionTargetCoordsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
motionTargetRLabel = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT(" r:"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetRLabel->Wrap(-1);
motionTargetCoordsSizer->Add(motionTargetRLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetRText = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_R_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetRText->SetMaxSize(wxSize(80, -1));
motionTargetCoordsSizer->Add(motionTargetRText, 0, wxALL, 5);
motionTargetThetaLabel = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("θ: "),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetThetaLabel->Wrap(-1);
motionTargetCoordsSizer->Add(motionTargetThetaLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetThetaText = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_THETA_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetThetaText->SetMaxSize(wxSize(80, -1));
motionTargetCoordsSizer->Add(motionTargetThetaText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
motionTargetDeltaLabel = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("δ: "),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetDeltaLabel->Wrap(-1);
motionTargetCoordsSizer->Add(motionTargetDeltaLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetDeltaText = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_DELTA_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetDeltaText->SetMaxSize(wxSize(80, -1));
motionTargetCoordsSizer->Add(motionTargetDeltaText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
simulationTargetOptionsSizer->Add(motionTargetCoordsSizer, 0, wxEXPAND, 5);
wxFlexGridSizer* motionTargetGainsSizer;
motionTargetGainsSizer = new wxFlexGridSizer(0, 0, 0, 0);
motionTargetGainsSizer->SetFlexibleDirection(wxBOTH);
motionTargetGainsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
motionTargetGainLabel = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT(" v:"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetGainLabel->Wrap(-1);
motionTargetGainsSizer->Add(motionTargetGainLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetGainText = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_GAIN_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetGainText->SetMaxSize(wxSize(80, -1));
motionTargetGainsSizer->Add(motionTargetGainText, 0, wxALL, 5);
motionTargetK1Label = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("k1:"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetK1Label->Wrap(-1);
motionTargetGainsSizer->Add(motionTargetK1Label, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetK1Text = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_K1_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetK1Text->SetMaxSize(wxSize(80, -1));
motionTargetGainsSizer->Add(motionTargetK1Text, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
motionTargetK2Label = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("k2:"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetK2Label->Wrap(-1);
motionTargetGainsSizer->Add(motionTargetK2Label, 0, wxALIGN_CENTER_VERTICAL | wxALL, 0);
motionTargetK2Text = new wxTextCtrl(simulationTargetOptionsSizer->GetStaticBox(),
ID_MOTION_TARGET_K2_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetK2Text->SetMaxSize(wxSize(80, -1));
motionTargetGainsSizer->Add(motionTargetK2Text, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
simulationTargetOptionsSizer->Add(motionTargetGainsSizer, 0, wxEXPAND, 5);
motionTargetCostText = new wxStaticText(simulationTargetOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Evaluated Expected Cost: 0"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetCostText->Wrap(-1);
simulationTargetOptionsSizer->Add(motionTargetCostText, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
wxStaticBoxSizer* motionTargetSizer;
motionTargetSizer = new wxStaticBoxSizer(
new wxStaticBox(simulationTargetOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Evaluate Motion Target")),
wxHORIZONTAL);
selectMotionTargetButton = new wxButton(motionTargetSizer->GetStaticBox(),
ID_SELECT_MOTION_TARGET_BUTTON,
wxT("Select"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetSizer->Add(selectMotionTargetButton, 0, wxALIGN_CENTER | wxALL, 5);
evaluateMotionTargetButton = new wxButton(motionTargetSizer->GetStaticBox(),
ID_EVALUATE_MOTION_TARGET_BUTTON,
wxT("Evaluate"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetSizer->Add(evaluateMotionTargetButton, 0, wxALIGN_CENTER | wxALL, 5);
clearMotionTargetButton = new wxButton(motionTargetSizer->GetStaticBox(),
ID_CLEAR_MOTION_TARGET_BUTTON,
wxT("Clear"),
wxDefaultPosition,
wxDefaultSize,
0);
motionTargetSizer->Add(clearMotionTargetButton, 0, wxALIGN_CENTER | wxALL, 5);
simulationTargetOptionsSizer->Add(motionTargetSizer, 1, wxEXPAND, 5);
metricPlannerOptionsSizer->Add(simulationTargetOptionsSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* pathFollowingOptionsSizer;
pathFollowingOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(metricPlannerScrollWindow, wxID_ANY, wxT("Path Following Options")),
wxVERTICAL);
wxFlexGridSizer* pathFollowingDisplayOptionsSizer;
pathFollowingDisplayOptionsSizer = new wxFlexGridSizer(3, 2, 0, 0);
pathFollowingDisplayOptionsSizer->SetFlexibleDirection(wxBOTH);
pathFollowingDisplayOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
showWaypointsCheckBox = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_SHOW_WAYPOINTS_BOX,
wxT("Show Waypoints"),
wxDefaultPosition,
wxDefaultSize,
0);
showWaypointsCheckBox->SetValue(true);
pathFollowingDisplayOptionsSizer->Add(showWaypointsCheckBox, 0, wxALL, 5);
useRRTStarCheckBOx = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_USE_RRT_STAR_BOX,
wxT("Use RRT*"),
wxDefaultPosition,
wxDefaultSize,
0);
pathFollowingDisplayOptionsSizer->Add(useRRTStarCheckBOx, 0, wxALL, 5);
stopAtWaypointsCheckBox = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_STOP_AT_WAYPOINTS_BOX,
wxT("Stop at Waypoint"),
wxDefaultPosition,
wxDefaultSize,
0);
stopAtWaypointsCheckBox->SetValue(true);
pathFollowingDisplayOptionsSizer->Add(stopAtWaypointsCheckBox, 0, wxALL, 5);
showGraphCheckBox = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_SHOW_GRAPH_BOX,
wxT("Show Graph"),
wxDefaultPosition,
wxDefaultSize,
0);
pathFollowingDisplayOptionsSizer->Add(showGraphCheckBox, 0, wxALL, 5);
SimpleFollowingCheckBox = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_SIMPLE_FOLLOWING_BOX,
wxT("Simple Following"),
wxDefaultPosition,
wxDefaultSize,
0);
pathFollowingDisplayOptionsSizer->Add(SimpleFollowingCheckBox, 0, wxALL, 5);
ignoreObjectSpeedCheckBox = new wxCheckBox(pathFollowingOptionsSizer->GetStaticBox(),
ID_IGNORE_OBJECT_SPEED_BOX,
wxT("Ignore Object Speed"),
wxDefaultPosition,
wxDefaultSize,
0);
pathFollowingDisplayOptionsSizer->Add(ignoreObjectSpeedCheckBox, 0, wxALL, 5);
pathFollowingOptionsSizer->Add(pathFollowingDisplayOptionsSizer, 0, wxALL, 5);
wxFlexGridSizer* pathPlanningOptionsSizer;
pathPlanningOptionsSizer = new wxFlexGridSizer(2, 3, 0, 0);
pathPlanningOptionsSizer->SetFlexibleDirection(wxBOTH);
pathPlanningOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_NONE);
updatePlanTimeText = new wxTextCtrl(pathFollowingOptionsSizer->GetStaticBox(),
ID_UPDATE_PLAN_TIME_TEXT,
wxT("500"),
wxDefaultPosition,
wxSize(-1, -1),
wxTE_RIGHT);
pathPlanningOptionsSizer->Add(updatePlanTimeText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
updateWaypointsButton = new wxButton(pathFollowingOptionsSizer->GetStaticBox(),
ID_UPDATE_WAYPOINTS_BUTTON,
wxT("Update (ms)"),
wxDefaultPosition,
wxDefaultSize,
0);
pathPlanningOptionsSizer->Add(updateWaypointsButton, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
pathFollowingOptionsSizer->Add(pathPlanningOptionsSizer, 1, wxALL | wxEXPAND, 5);
metricPlannerOptionsSizer->Add(pathFollowingOptionsSizer, 0, wxALL | wxEXPAND, 5);
metricPlannerScrollWindow->SetSizer(metricPlannerOptionsSizer);
metricPlannerScrollWindow->Layout();
metricPlannerOptionsSizer->Fit(metricPlannerScrollWindow);
metricPlannerSizer->Add(metricPlannerScrollWindow, 0, wxEXPAND | wxALL, 5);
metricPlannerPanel->SetSizer(metricPlannerSizer);
metricPlannerPanel->Layout();
metricPlannerSizer->Fit(metricPlannerPanel);
frameNotebook->AddPage(metricPlannerPanel, wxT("Metric Planner"), false, wxNullBitmap);
trackerPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* trackerPanelSizer;
trackerPanelSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* trackerWidgetSizer;
trackerWidgetSizer = new wxBoxSizer(wxVERTICAL);
trackerWidget = new TrackerDisplayWidget(trackerPanel, ID_TRACKER_WIDGET, wxDefaultPosition, wxDefaultSize);
trackerWidgetSizer->Add(trackerWidget, 1, wxALL | wxEXPAND, 5);
trackerPanelSizer->Add(trackerWidgetSizer, 1, wxEXPAND, 5);
trackerPanelScrollWindow =
new wxScrolledWindow(trackerPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
trackerPanelScrollWindow->SetScrollRate(0, 5);
wxBoxSizer* trackerPanelScrollSizer;
trackerPanelScrollSizer = new wxBoxSizer(wxVERTICAL);
trackerFollowRobotCheckbox = new wxCheckBox(trackerPanelScrollWindow,
ID_TRACKER_FOLLOW_ROBOT_BOX,
wxT("Follow Robot"),
wxDefaultPosition,
wxDefaultSize,
0);
trackerFollowRobotCheckbox->SetValue(true);
trackerPanelScrollSizer->Add(trackerFollowRobotCheckbox, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* laserObjectOptionsSizer;
laserObjectOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(trackerPanelScrollWindow, wxID_ANY, wxT("Laser Object Options")),
wxVERTICAL);
showLaserObjectsCheckbox = new wxCheckBox(laserObjectOptionsSizer->GetStaticBox(),
ID_SHOW_LASER_OBJECTS_BOX,
wxT("Show Laser Objects"),
wxDefaultPosition,
wxDefaultSize,
0);
showLaserObjectsCheckbox->SetValue(true);
laserObjectOptionsSizer->Add(showLaserObjectsCheckbox, 0, wxALL | wxEXPAND, 5);
showLaserObjectPointsCheckbox = new wxCheckBox(laserObjectOptionsSizer->GetStaticBox(),
ID_SHOW_LASER_OBJECT_POINTS_BOX,
wxT("Show Laser Points"),
wxDefaultPosition,
wxDefaultSize,
0);
showLaserObjectPointsCheckbox->SetValue(true);
laserObjectOptionsSizer->Add(showLaserObjectPointsCheckbox, 0, wxALL | wxEXPAND, 5);
showLaserUncertaintyCheckbox = new wxCheckBox(laserObjectOptionsSizer->GetStaticBox(),
ID_SHOW_LASER_UNCERTAINTY_BOX,
wxT("Show Laser Uncertainty"),
wxDefaultPosition,
wxDefaultSize,
0);
laserObjectOptionsSizer->Add(showLaserUncertaintyCheckbox, 0, wxALL, 5);
wxString laserObjBoundaryRadioChoices[] = {wxT("Best"), wxT("Rectangle"), wxT("One Circle"), wxT("Two Circles")};
int laserObjBoundaryRadioNChoices = sizeof(laserObjBoundaryRadioChoices) / sizeof(wxString);
laserObjBoundaryRadio = new wxRadioBox(laserObjectOptionsSizer->GetStaticBox(),
ID_LASER_OBJ_BOUNDARY_RADIO,
wxT("Boundary:"),
wxDefaultPosition,
wxDefaultSize,
laserObjBoundaryRadioNChoices,
laserObjBoundaryRadioChoices,
1,
wxRA_SPECIFY_COLS);
laserObjBoundaryRadio->SetSelection(0);
laserObjectOptionsSizer->Add(laserObjBoundaryRadio, 0, wxALL | wxEXPAND, 5);
trackerPanelScrollSizer->Add(laserObjectOptionsSizer, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* trackedObjectOptionsSizer;
trackedObjectOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(trackerPanelScrollWindow, wxID_ANY, wxT("Tracked Object Options")),
wxVERTICAL);
showTrackedObjectsCheckbox = new wxCheckBox(trackedObjectOptionsSizer->GetStaticBox(),
ID_SHOW_TRACKED_OBJECTS_BOX,
wxT("Show Tracked Objects"),
wxDefaultPosition,
wxDefaultSize,
0);
showTrackedObjectsCheckbox->SetValue(true);
trackedObjectOptionsSizer->Add(showTrackedObjectsCheckbox, 0, wxALL | wxEXPAND, 5);
showTrackedAcclerationCheckbox = new wxCheckBox(trackedObjectOptionsSizer->GetStaticBox(),
ID_SHOW_TRACKED_ACCELERATION_BOX,
wxT("Show Acceleration"),
wxDefaultPosition,
wxDefaultSize,
0);
showTrackedAcclerationCheckbox->SetValue(true);
trackedObjectOptionsSizer->Add(showTrackedAcclerationCheckbox, 0, wxALL, 5);
wxString rigidObjectStateRadioChoices[] = {wxT("Fast"), wxT("Slow")};
int rigidObjectStateRadioNChoices = sizeof(rigidObjectStateRadioChoices) / sizeof(wxString);
rigidObjectStateRadio = new wxRadioBox(trackedObjectOptionsSizer->GetStaticBox(),
ID_RIGID_OBJECT_STATE_RADIO,
wxT("Rigid Object State"),
wxDefaultPosition,
wxDefaultSize,
rigidObjectStateRadioNChoices,
rigidObjectStateRadioChoices,
1,
wxRA_SPECIFY_COLS);
rigidObjectStateRadio->SetSelection(0);
trackedObjectOptionsSizer->Add(rigidObjectStateRadio, 0, wxALL | wxEXPAND, 5);
wxString trackingUncertaintyRadioChoices[] = {wxT("Position"), wxT("Velocity"), wxT("Acceleration"), wxT("None")};
int trackingUncertaintyRadioNChoices = sizeof(trackingUncertaintyRadioChoices) / sizeof(wxString);
trackingUncertaintyRadio = new wxRadioBox(trackedObjectOptionsSizer->GetStaticBox(),
ID_TRACKING_UNCERTAINTY_RADIO,
wxT("Uncertainty to Show"),
wxDefaultPosition,
wxDefaultSize,
trackingUncertaintyRadioNChoices,
trackingUncertaintyRadioChoices,
1,
wxRA_SPECIFY_COLS);
trackingUncertaintyRadio->SetSelection(0);
trackedObjectOptionsSizer->Add(trackingUncertaintyRadio, 0, wxALL | wxEXPAND, 5);
showRecentObjectTrajectoryCheckbox = new wxCheckBox(trackedObjectOptionsSizer->GetStaticBox(),
ID_SHOW_RECENT_OBJECT_TRAJECTORY_BOX,
wxT("Show Recent Trajectory"),
wxDefaultPosition,
wxDefaultSize,
0);
trackedObjectOptionsSizer->Add(showRecentObjectTrajectoryCheckbox, 0, wxALL | wxEXPAND, 5);
trackerPanelScrollSizer->Add(trackedObjectOptionsSizer, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* objectGoalsOptionsSizer;
objectGoalsOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(trackerPanelScrollWindow, wxID_ANY, wxT("Object Goals Options")),
wxVERTICAL);
wxString objectGoalsToShowRadioChoices[] = {wxT("Best"), wxT("All"), wxT("None")};
int objectGoalsToShowRadioNChoices = sizeof(objectGoalsToShowRadioChoices) / sizeof(wxString);
objectGoalsToShowRadio = new wxRadioBox(objectGoalsOptionsSizer->GetStaticBox(),
ID_OBJECT_GOALS_TO_SHOW_RADIO,
wxT("Goals to Show"),
wxDefaultPosition,
wxDefaultSize,
objectGoalsToShowRadioNChoices,
objectGoalsToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
objectGoalsToShowRadio->SetSelection(2);
objectGoalsOptionsSizer->Add(objectGoalsToShowRadio, 0, wxALL | wxEXPAND, 5);
evaluateObjectGoalsButton = new wxToggleButton(objectGoalsOptionsSizer->GetStaticBox(),
ID_EVALUATE_OBJECT_GOALS_BUTTON,
wxT("Evaluate"),
wxDefaultPosition,
wxDefaultSize,
0);
objectGoalsOptionsSizer->Add(evaluateObjectGoalsButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
trackerPanelScrollSizer->Add(objectGoalsOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* motionPredictionOptionsSizer;
motionPredictionOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(trackerPanelScrollWindow, wxID_ANY, wxT("Motion Prediction Options")),
wxVERTICAL);
wxString motionPredictionsToShowRadioChoices[] = {wxT("Best"), wxT("All"), wxT("None")};
int motionPredictionsToShowRadioNChoices = sizeof(motionPredictionsToShowRadioChoices) / sizeof(wxString);
motionPredictionsToShowRadio = new wxRadioBox(motionPredictionOptionsSizer->GetStaticBox(),
ID_MOTION_PREDICTIONS_TO_SHOW_RADIO,
wxT("Prediction to Show"),
wxDefaultPosition,
wxDefaultSize,
motionPredictionsToShowRadioNChoices,
motionPredictionsToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
motionPredictionsToShowRadio->SetSelection(2);
motionPredictionOptionsSizer->Add(motionPredictionsToShowRadio, 0, wxALL | wxEXPAND, 5);
wxBoxSizer* predictionDurationSizer;
predictionDurationSizer = new wxBoxSizer(wxHORIZONTAL);
predictionDurationLabel = new wxStaticText(motionPredictionOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Duration (ms):"),
wxDefaultPosition,
wxDefaultSize,
0);
predictionDurationLabel->Wrap(-1);
predictionDurationSizer->Add(predictionDurationLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
predictionDurationText = new wxTextCtrl(motionPredictionOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("5000"),
wxDefaultPosition,
wxDefaultSize,
0);
predictionDurationSizer->Add(predictionDurationText,
0,
wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT | wxALL | wxEXPAND,
5);
motionPredictionOptionsSizer->Add(predictionDurationSizer, 1, wxEXPAND, 5);
trackerPanelScrollSizer->Add(motionPredictionOptionsSizer, 0, wxEXPAND, 5);
trackerPanelScrollWindow->SetSizer(trackerPanelScrollSizer);
trackerPanelScrollWindow->Layout();
trackerPanelScrollSizer->Fit(trackerPanelScrollWindow);
trackerPanelSizer->Add(trackerPanelScrollWindow, 0, wxALL | wxEXPAND, 5);
trackerPanel->SetSizer(trackerPanelSizer);
trackerPanel->Layout();
trackerPanelSizer->Fit(trackerPanel);
frameNotebook->AddPage(trackerPanel, wxT("Tracker"), false, wxNullBitmap);
localTopologyPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* localTopologySizer;
localTopologySizer = new wxBoxSizer(wxHORIZONTAL);
wxFlexGridSizer* localTopoWidgetSizer;
localTopoWidgetSizer = new wxFlexGridSizer(1, 1, 0, 0);
localTopoWidgetSizer->AddGrowableCol(0);
localTopoWidgetSizer->AddGrowableRow(0);
localTopoWidgetSizer->SetFlexibleDirection(wxBOTH);
localTopoWidgetSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
localTopoWidget =
new LocalTopoDisplayWidget(localTopologyPanel, ID_LOCAL_TOPO_WIDGET, wxDefaultPosition, wxDefaultSize);
localTopoWidget->SetMinSize(wxSize(0, 0));
localTopoWidgetSizer->Add(localTopoWidget, 1, wxALIGN_CENTER | wxEXPAND, 0);
localTopologySizer->Add(localTopoWidgetSizer, 1, wxALL | wxEXPAND, 5);
localTopoScrollWindow =
new wxScrolledWindow(localTopologyPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
localTopoScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* localTopoOptionsSizer;
localTopoOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
localTopoOptionsSizer->SetFlexibleDirection(wxBOTH);
localTopoOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxString localTopoModeRadioChoices[] = {wxT("Event Detection"), wxT("Labeling Only")};
int localTopoModeRadioNChoices = sizeof(localTopoModeRadioChoices) / sizeof(wxString);
localTopoModeRadio = new wxRadioBox(localTopoScrollWindow,
ID_LOCAL_TOPO_MODE_RADIO,
wxT("Local Topo Mode:"),
wxDefaultPosition,
wxDefaultSize,
localTopoModeRadioNChoices,
localTopoModeRadioChoices,
1,
wxRA_SPECIFY_COLS);
localTopoModeRadio->SetSelection(0);
localTopoOptionsSizer->Add(localTopoModeRadio, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* placeGridOptionsSizer;
placeGridOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Grid Options")), wxVERTICAL);
showVoronoiGridCheckbox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_SHOW_VORONOI_GRID_BOX,
wxT("Show Voronoi Grid"),
wxDefaultPosition,
wxDefaultSize,
0);
showVoronoiGridCheckbox->SetValue(true);
placeGridOptionsSizer->Add(showVoronoiGridCheckbox, 0, wxALL | wxEXPAND, 5);
showDistanceGradientCheckBox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_SHOW_DISTANCE_GRADIENT_BOX,
wxT("Show Distance Gradient"),
wxDefaultPosition,
wxDefaultSize,
0);
placeGridOptionsSizer->Add(showDistanceGradientCheckBox, 0, wxALL | wxEXPAND, 5);
showFullSkeletonCheckBox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_SHOW_FULL_SKELETON_BOX,
wxT("Show Full Skeleton"),
wxDefaultPosition,
wxDefaultSize,
0);
placeGridOptionsSizer->Add(showFullSkeletonCheckBox, 0, wxALL, 5);
showReducedSkeletonCheckBox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_SHOW_REDUCED_SKELETON_BOX,
wxT("Show Reduced Skeleton"),
wxDefaultPosition,
wxDefaultSize,
0);
showReducedSkeletonCheckBox->SetValue(true);
placeGridOptionsSizer->Add(showReducedSkeletonCheckBox, 0, wxALL, 5);
followRobotTopoCheckBox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_FOLLOW_ROBOT_TOPO_BOX,
wxT("Center on Robot"),
wxDefaultPosition,
wxDefaultSize,
0);
followRobotTopoCheckBox->SetValue(true);
placeGridOptionsSizer->Add(followRobotTopoCheckBox, 0, wxALL, 5);
showFrontiersCheckbox = new wxCheckBox(placeGridOptionsSizer->GetStaticBox(),
ID_SHOW_FRONTIERS_BOX,
wxT("Show Frontiers"),
wxDefaultPosition,
wxDefaultSize,
0);
showFrontiersCheckbox->SetValue(true);
placeGridOptionsSizer->Add(showFrontiersCheckbox, 0, wxALL, 5);
localTopoOptionsSizer->Add(placeGridOptionsSizer, 0, wxALIGN_RIGHT | wxEXPAND, 5);
wxStaticBoxSizer* gatewayOptionsSizer;
gatewayOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Gateways Display Options")),
wxVERTICAL);
showGatewaysCheckBox = new wxCheckBox(gatewayOptionsSizer->GetStaticBox(),
ID_SHOW_GATEWAYS_BOX,
wxT("Show Gateways"),
wxDefaultPosition,
wxDefaultSize,
0);
gatewayOptionsSizer->Add(showGatewaysCheckBox, 0, wxALL, 5);
wxArrayString gatewayTypeChoiceChoices;
gatewayTypeChoice = new wxChoice(gatewayOptionsSizer->GetStaticBox(),
ID_GATEWAY_TYPE_CHOICE,
wxDefaultPosition,
wxDefaultSize,
gatewayTypeChoiceChoices,
0);
gatewayTypeChoice->SetSelection(0);
gatewayOptionsSizer->Add(gatewayTypeChoice, 0, wxALL | wxEXPAND, 5);
showNormalsCheckbox = new wxCheckBox(gatewayOptionsSizer->GetStaticBox(),
ID_SHOW_NORMALS_BOX,
wxT("Show Normals"),
wxDefaultPosition,
wxDefaultSize,
0);
gatewayOptionsSizer->Add(showNormalsCheckbox, 0, wxALL, 5);
localTopoOptionsSizer->Add(gatewayOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* areaOptionsSizer;
areaOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Area Display Options")), wxVERTICAL);
wxString showAreasRadioBoxChoices[] = {wxT("Local Topo Map"),
wxT("Local Topo Graph"),
wxT("HSSH Graph"),
wxT("None")};
int showAreasRadioBoxNChoices = sizeof(showAreasRadioBoxChoices) / sizeof(wxString);
showAreasRadioBox = new wxRadioBox(areaOptionsSizer->GetStaticBox(),
ID_SHOW_AREAS_BOX,
wxT("Areas To Show"),
wxDefaultPosition,
wxDefaultSize,
showAreasRadioBoxNChoices,
showAreasRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
showAreasRadioBox->SetSelection(0);
areaOptionsSizer->Add(showAreasRadioBox, 0, wxALL | wxEXPAND, 5);
saveLocalTopoMapButton = new wxButton(areaOptionsSizer->GetStaticBox(),
ID_SAVE_LOCAL_TOPO_MAP_BUTTON,
wxT("Save Local Topo Map"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(saveLocalTopoMapButton, 0, wxALL | wxEXPAND, 5);
loadLocalTopoMapButton = new wxButton(areaOptionsSizer->GetStaticBox(),
ID_LOAD_LOCAL_TOPO_MAP_BUTTON,
wxT("Load Local Topo Map"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(loadLocalTopoMapButton, 0, wxALL | wxEXPAND, 5);
sendLocalTopoMapButton = new wxButton(areaOptionsSizer->GetStaticBox(),
ID_SEND_LOCAL_TOPO_MAP_BUTTON,
wxT("Send Local Topo Map"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(sendLocalTopoMapButton, 0, wxALL | wxEXPAND, 5);
showSmallStarCheckBox = new wxCheckBox(areaOptionsSizer->GetStaticBox(),
ID_SHOW_SMALL_STAR_BOX,
wxT("Show Small-Scale Star"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(showSmallStarCheckBox, 0, wxALL, 5);
showAreaGatewaysCheckBox = new wxCheckBox(areaOptionsSizer->GetStaticBox(),
ID_SHOW_AREA_GATEWAYS_BOX,
wxT("Show Area Gateways"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(showAreaGatewaysCheckBox, 0, wxALL, 5);
showAreaGraphCheckBox = new wxCheckBox(areaOptionsSizer->GetStaticBox(),
ID_SHOW_AREA_GRAPH_BOX,
wxT("Show Area Graph"),
wxDefaultPosition,
wxDefaultSize,
0);
areaOptionsSizer->Add(showAreaGraphCheckBox, 0, wxALL, 5);
wxString areaHypothesisValueRadioChoices[] = {wxT("Label"), wxT("Distribution"), wxT("Feature")};
int areaHypothesisValueRadioNChoices = sizeof(areaHypothesisValueRadioChoices) / sizeof(wxString);
areaHypothesisValueRadio = new wxRadioBox(areaOptionsSizer->GetStaticBox(),
ID_AREA_HYPOTHESIS_VALUE_RADIO,
wxT("Displayed Value"),
wxDefaultPosition,
wxDefaultSize,
areaHypothesisValueRadioNChoices,
areaHypothesisValueRadioChoices,
1,
wxRA_SPECIFY_COLS);
areaHypothesisValueRadio->SetSelection(0);
areaOptionsSizer->Add(areaHypothesisValueRadio, 0, wxALL | wxEXPAND, 5);
wxBoxSizer* hypFeatureSizer;
hypFeatureSizer = new wxBoxSizer(wxHORIZONTAL);
hypFeatureLabel = new wxStaticText(areaOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Hypothesis Feature:"),
wxDefaultPosition,
wxDefaultSize,
0);
hypFeatureLabel->Wrap(-1);
hypFeatureSizer->Add(hypFeatureLabel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
hypFeatureValueText =
new wxStaticText(areaOptionsSizer->GetStaticBox(), wxID_ANY, wxT("0.0"), wxDefaultPosition, wxDefaultSize, 0);
hypFeatureValueText->Wrap(-1);
hypFeatureSizer->Add(hypFeatureValueText, 0, wxALL, 5);
areaOptionsSizer->Add(hypFeatureSizer, 0, wxEXPAND, 5);
wxArrayString hypFeatureChoiceChoices;
hypFeatureChoice = new wxChoice(areaOptionsSizer->GetStaticBox(),
ID_HYP_FEATURE_CHOICE,
wxDefaultPosition,
wxDefaultSize,
hypFeatureChoiceChoices,
0);
hypFeatureChoice->SetSelection(0);
areaOptionsSizer->Add(hypFeatureChoice, 0, wxALL | wxEXPAND, 5);
wxString hypothesesToShowRadioChoices[] = {wxT("None"),
wxT("Max Likelihood"),
wxT("Unnormalized"),
wxT("Boosting"),
wxT("Isovist")};
int hypothesesToShowRadioNChoices = sizeof(hypothesesToShowRadioChoices) / sizeof(wxString);
hypothesesToShowRadio = new wxRadioBox(areaOptionsSizer->GetStaticBox(),
ID_HYPOTHESES_TO_SHOW_RADIO,
wxT("Hypotheses to Show"),
wxDefaultPosition,
wxDefaultSize,
hypothesesToShowRadioNChoices,
hypothesesToShowRadioChoices,
1,
wxRA_SPECIFY_COLS);
hypothesesToShowRadio->SetSelection(0);
areaOptionsSizer->Add(hypothesesToShowRadio, 0, wxALL | wxEXPAND, 5);
labelDistributionText =
new wxStaticText(areaOptionsSizer->GetStaticBox(), wxID_ANY, wxT("0 0 0"), wxDefaultPosition, wxDefaultSize, 0);
labelDistributionText->Wrap(-1);
areaOptionsSizer->Add(labelDistributionText, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* labelingCSPSizer;
labelingCSPSizer =
new wxStaticBoxSizer(new wxStaticBox(areaOptionsSizer->GetStaticBox(), wxID_ANY, wxT("CSP Options")), wxVERTICAL);
cspLoadButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_LOAD_BUTTON,
wxT("Load CSP Info"),
wxDefaultPosition,
wxDefaultSize,
0);
labelingCSPSizer->Add(cspLoadButton, 0, wxALL | wxEXPAND, 5);
wxGridSizer* cspControlButtonSizer;
cspControlButtonSizer = new wxGridSizer(0, 3, 0, 0);
cspPlayButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_PLAY_BUTTON,
wxT("Play"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspControlButtonSizer->Add(cspPlayButton, 0, wxALL | wxEXPAND, 5);
cspPauseButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_PAUSE_BUTTON,
wxT("Pause"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspControlButtonSizer->Add(cspPauseButton, 0, wxALL | wxEXPAND, 5);
cspStopButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_STOP_BUTTON,
wxT("Stop"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspControlButtonSizer->Add(cspStopButton, 0, wxALL | wxEXPAND, 5);
labelingCSPSizer->Add(cspControlButtonSizer, 0, wxEXPAND, 5);
wxGridSizer* cspIterationControlSizer;
cspIterationControlSizer = new wxGridSizer(1, 4, 0, 0);
cspJumpToStartButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_JUMP_TO_START_BUTTON,
wxT("<<"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspIterationControlSizer->Add(cspJumpToStartButton, 0, wxALL | wxEXPAND, 5);
cspPrevIterationButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_PREV_ITERATION_BUTTON,
wxT(" <"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspIterationControlSizer->Add(cspPrevIterationButton, 0, wxALL | wxEXPAND, 5);
cspNextIterationButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_NEXT_ITERATION_BUTTON,
wxT("> "),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspIterationControlSizer->Add(cspNextIterationButton, 0, wxALL | wxEXPAND, 5);
cspJumpToEndButton = new wxButton(labelingCSPSizer->GetStaticBox(),
ID_CSP_JUMP_TO_END_BUTTON,
wxT(">>"),
wxDefaultPosition,
wxDefaultSize,
wxBU_EXACTFIT);
cspIterationControlSizer->Add(cspJumpToEndButton, 0, wxALL | wxEXPAND, 5);
labelingCSPSizer->Add(cspIterationControlSizer, 0, wxEXPAND, 5);
cspIterationSlider = new wxSlider(labelingCSPSizer->GetStaticBox(),
ID_CSP_ITERATION_SLIDER,
50,
0,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
cspIterationSlider->SetToolTip(wxT("Current iteration of CSP search being shown"));
labelingCSPSizer->Add(cspIterationSlider, 0, wxALL | wxEXPAND, 5);
cspSpeedSlider = new wxSlider(labelingCSPSizer->GetStaticBox(),
ID_CSP_SPEED_SLIDER,
10,
1,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_AUTOTICKS | wxSL_HORIZONTAL | wxSL_LABELS);
cspSpeedSlider->SetToolTip(wxT("Adjust speed of playback in frames per iteration"));
labelingCSPSizer->Add(cspSpeedSlider, 0, wxALL | wxEXPAND, 5);
areaOptionsSizer->Add(labelingCSPSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* localTopoHeatmapSizer;
localTopoHeatmapSizer =
new wxStaticBoxSizer(new wxStaticBox(areaOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Heat Map Options")),
wxVERTICAL);
showLocalHeatMapCheckBox = new wxCheckBox(localTopoHeatmapSizer->GetStaticBox(),
ID_SHOW_LOCAL_HEAT_MAP_BOX,
wxT("Show Heat Map"),
wxDefaultPosition,
wxDefaultSize,
0);
localTopoHeatmapSizer->Add(showLocalHeatMapCheckBox, 0, wxALL, 5);
wxBoxSizer* numHeatMapPathsSizer;
numHeatMapPathsSizer = new wxBoxSizer(wxHORIZONTAL);
numPathsHeatMapLabel = new wxStaticText(localTopoHeatmapSizer->GetStaticBox(),
wxID_ANY,
wxT("Num Paths:"),
wxDefaultPosition,
wxDefaultSize,
0);
numPathsHeatMapLabel->Wrap(-1);
numHeatMapPathsSizer->Add(numPathsHeatMapLabel, 0, wxALL, 5);
numHeatMapPathsText = new wxTextCtrl(localTopoHeatmapSizer->GetStaticBox(),
wxID_ANY,
wxT("10000"),
wxDefaultPosition,
wxDefaultSize,
0);
numHeatMapPathsText->SetToolTip(wxT("Number of paths to generate for creating the heat map"));
numHeatMapPathsSizer->Add(numHeatMapPathsText, 0, wxALL, 5);
localTopoHeatmapSizer->Add(numHeatMapPathsSizer, 1, wxEXPAND, 5);
generateLocalHeatMapButton = new wxButton(localTopoHeatmapSizer->GetStaticBox(),
ID_GENERATE_LOCAL_HEAT_MAP_BUTTON,
wxT("Generate Heat Map"),
wxDefaultPosition,
wxDefaultSize,
0);
localTopoHeatmapSizer->Add(generateLocalHeatMapButton, 0, wxALL | wxEXPAND, 5);
areaOptionsSizer->Add(localTopoHeatmapSizer, 0, wxEXPAND, 5);
localTopoOptionsSizer->Add(areaOptionsSizer, 0, wxALIGN_RIGHT | wxEXPAND, 5);
wxStaticBoxSizer* localTopoEventsSizer;
localTopoEventsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Event Options")), wxVERTICAL);
localTopoEventList = new wxListBox(localTopoEventsSizer->GetStaticBox(),
ID_LOCAL_TOPO_EVENT_LIST,
wxDefaultPosition,
wxDefaultSize,
0,
NULL,
wxLB_ALWAYS_SB | wxLB_SINGLE);
localTopoEventList->Append(wxT("First"));
localTopoEventList->Append(wxT("Second"));
localTopoEventList->Append(wxT("Third"));
localTopoEventList->Append(wxT("Fourth"));
localTopoEventList->Append(wxT("Fifth"));
localTopoEventList->Append(wxT("Sixth"));
localTopoEventList->SetMinSize(wxSize(225, -1));
localTopoEventsSizer->Add(localTopoEventList, 0, wxALL, 5);
showLocalTopoEventCheckbox = new wxCheckBox(localTopoEventsSizer->GetStaticBox(),
ID_SHOW_LOCAL_TOPO_EVENT_BOX,
wxT("Show Event Visualization"),
wxDefaultPosition,
wxDefaultSize,
0);
localTopoEventsSizer->Add(showLocalTopoEventCheckbox, 0, wxALL, 5);
localTopoOptionsSizer->Add(localTopoEventsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* isovistOptionsSizer;
isovistOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Isovist Options")), wxVERTICAL);
showIsovistBox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_ISOVIST_BOX,
wxT("Show Isovist"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showIsovistBox, 0, wxALL, 5);
showIsovistFieldBox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_ISOVIST_FIELD_BOX,
wxT("Show Isovist Field"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showIsovistFieldBox, 0, wxALL, 5);
showIsovistFieldDerivBox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_ISOVIST_DERIV_FIELD_BOX,
wxT("Show Isovist Deriv Field"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showIsovistFieldDerivBox, 0, wxALL | wxEXPAND, 5);
wxString isovistLocationRadioChoices[] = {wxT("Free Space"), wxT("Skeleton"), wxT("Reduced Skeleton")};
int isovistLocationRadioNChoices = sizeof(isovistLocationRadioChoices) / sizeof(wxString);
isovistLocationRadio = new wxRadioBox(isovistOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Location"),
wxDefaultPosition,
wxDefaultSize,
isovistLocationRadioNChoices,
isovistLocationRadioChoices,
1,
wxRA_SPECIFY_COLS);
isovistLocationRadio->SetSelection(2);
isovistOptionsSizer->Add(isovistLocationRadio, 0, wxALL | wxEXPAND, 5);
calculateIsovistsButton = new wxButton(isovistOptionsSizer->GetStaticBox(),
ID_CALCULATE_ISOVISTS_BUTTON,
wxT("Calculate"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(calculateIsovistsButton, 0, wxALL | wxEXPAND, 5);
selectIsovistsButton = new wxToggleButton(isovistOptionsSizer->GetStaticBox(),
ID_SELECT_ISOVISTS_BUTTON,
wxT("Select Isovists"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(selectIsovistsButton, 0, wxALL | wxEXPAND, 5);
wxBoxSizer* scalarOptionSizer;
scalarOptionSizer = new wxBoxSizer(wxHORIZONTAL);
scalarChoiceLabel = new wxStaticText(isovistOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Scalar:"),
wxDefaultPosition,
wxDefaultSize,
0);
scalarChoiceLabel->Wrap(-1);
scalarOptionSizer->Add(scalarChoiceLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
wxArrayString fieldScalarChoiceChoices;
fieldScalarChoice = new wxChoice(isovistOptionsSizer->GetStaticBox(),
ID_FIELD_SCALAR_CHOICE,
wxDefaultPosition,
wxDefaultSize,
fieldScalarChoiceChoices,
0);
fieldScalarChoice->SetSelection(0);
scalarOptionSizer->Add(fieldScalarChoice, 0, wxALL | wxEXPAND, 5);
isovistOptionsSizer->Add(scalarOptionSizer, 0, wxEXPAND, 5);
calculateGradientsButton = new wxButton(isovistOptionsSizer->GetStaticBox(),
ID_CALCULATE_GRADIENTS_BUTTON,
wxT("Calculate Gradients"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(calculateGradientsButton, 0, wxALL | wxEXPAND, 5);
showCellGradientsCheckbox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_CELL_GRADIENTS_BOX,
wxT("Show Cell Gradients"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showCellGradientsCheckbox, 0, wxALL, 5);
showIsovistMaximaCheckbox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_ISOVIST_MAXIMA_BOX,
wxT("Show Gradient Maxima"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showIsovistMaximaCheckbox, 0, wxALL, 5);
loadGatewayClassifierButton = new wxButton(isovistOptionsSizer->GetStaticBox(),
ID_LOAD_GATEWAY_CLASSIFIER_BUTTON,
wxT("Load Gateway Classifier"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(loadGatewayClassifierButton, 0, wxALL | wxEXPAND, 5);
calculateGatewayProbabilityButton = new wxButton(isovistOptionsSizer->GetStaticBox(),
ID_CALCULATE_GATEWAY_PROBABILITIES_BUTTON,
wxT("Calculate Probabilities"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(calculateGatewayProbabilityButton, 0, wxALL | wxEXPAND, 5);
showGatewayProbabilitiesBox = new wxCheckBox(isovistOptionsSizer->GetStaticBox(),
ID_SHOW_GATEWAY_PROBABILITIES_BOX,
wxT("Show Probabilities"),
wxDefaultPosition,
wxDefaultSize,
0);
isovistOptionsSizer->Add(showGatewayProbabilitiesBox, 0, wxALL | wxEXPAND, 5);
gatewayProbCutoffLabel = new wxStaticText(isovistOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Probability Cutoff:"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_CENTER_HORIZONTAL);
gatewayProbCutoffLabel->Wrap(-1);
isovistOptionsSizer->Add(gatewayProbCutoffLabel, 0, wxALL | wxEXPAND, 5);
gatewayCutoffSlider = new wxSlider(isovistOptionsSizer->GetStaticBox(),
ID_GATEWAY_CUTOFF_SLIDER,
50,
0,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
isovistOptionsSizer->Add(gatewayCutoffSlider, 0, wxALL | wxEXPAND, 5);
wxString gatewayClassifierRadioChoices[] = {wxT("Logistic"), wxT("SVM"), wxT("AdaBoost")};
int gatewayClassifierRadioNChoices = sizeof(gatewayClassifierRadioChoices) / sizeof(wxString);
gatewayClassifierRadio = new wxRadioBox(isovistOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Gateway Classifier To Use:"),
wxDefaultPosition,
wxDefaultSize,
gatewayClassifierRadioNChoices,
gatewayClassifierRadioChoices,
1,
wxRA_SPECIFY_COLS);
gatewayClassifierRadio->SetSelection(2);
isovistOptionsSizer->Add(gatewayClassifierRadio, 0, wxALL | wxEXPAND, 5);
localTopoOptionsSizer->Add(isovistOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* visibilityGraphOptionsSizer;
visibilityGraphOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(localTopoScrollWindow, wxID_ANY, wxT("Visibility Graph Options")),
wxVERTICAL);
showVisibilityGraphBox = new wxCheckBox(visibilityGraphOptionsSizer->GetStaticBox(),
ID_SHOW_VISIBILITY_GRAPH_BOX,
wxT("Show Visibility Graph"),
wxDefaultPosition,
wxDefaultSize,
0);
visibilityGraphOptionsSizer->Add(showVisibilityGraphBox, 0, wxALL, 5);
wxBoxSizer* visibilityFeatureSizer;
visibilityFeatureSizer = new wxBoxSizer(wxHORIZONTAL);
visibilityFeatureChoiceLabel = new wxStaticText(visibilityGraphOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Feature:"),
wxDefaultPosition,
wxDefaultSize,
0);
visibilityFeatureChoiceLabel->Wrap(-1);
visibilityFeatureSizer->Add(visibilityFeatureChoiceLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
wxArrayString visibilityFeatureChoiceChoices;
visibilityFeatureChoice = new wxChoice(visibilityGraphOptionsSizer->GetStaticBox(),
ID_VISIBILITY_FEATURE_CHOICE,
wxDefaultPosition,
wxDefaultSize,
visibilityFeatureChoiceChoices,
0);
visibilityFeatureChoice->SetSelection(0);
visibilityFeatureSizer->Add(visibilityFeatureChoice, 0, wxALL | wxEXPAND, 5);
visibilityGraphOptionsSizer->Add(visibilityFeatureSizer, 1, wxEXPAND, 5);
localTopoOptionsSizer->Add(visibilityGraphOptionsSizer, 0, wxEXPAND, 5);
localTopoScrollWindow->SetSizer(localTopoOptionsSizer);
localTopoScrollWindow->Layout();
localTopoOptionsSizer->Fit(localTopoScrollWindow);
localTopologySizer->Add(localTopoScrollWindow, 0, wxEXPAND | wxALL, 5);
localTopologyPanel->SetSizer(localTopologySizer);
localTopologyPanel->Layout();
localTopologySizer->Fit(localTopologyPanel);
frameNotebook->AddPage(localTopologyPanel, wxT("Local Topology"), false, wxNullBitmap);
globalTopologyPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* globalTopologySizer;
globalTopologySizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* globalTopoWidgetSizer;
globalTopoWidgetSizer = new wxBoxSizer(wxVERTICAL);
globalTopoWidget =
new GlobalTopoDisplayWidget(globalTopologyPanel, ID_GLOBAL_TOPO_WIDGET, wxDefaultPosition, wxDefaultSize);
globalTopoWidget->SetMinSize(wxSize(0, 0));
globalTopoWidgetSizer->Add(globalTopoWidget, 1, wxALL | wxEXPAND, 5);
globalTopologySizer->Add(globalTopoWidgetSizer, 1, wxEXPAND, 5);
globalTopoScrolledWindow =
new wxScrolledWindow(globalTopologyPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
globalTopoScrolledWindow->SetScrollRate(0, 5);
wxStaticBoxSizer* globalTopologyOptionsSizer;
globalTopologyOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(globalTopoScrolledWindow, wxID_ANY, wxT("Global Topology Options")),
wxVERTICAL);
wxString globalTopoMapViewRadioBoxChoices[] = {wxT("Graph View"), wxT("Place View"), wxT("Hypothesis Tree")};
int globalTopoMapViewRadioBoxNChoices = sizeof(globalTopoMapViewRadioBoxChoices) / sizeof(wxString);
globalTopoMapViewRadioBox = new wxRadioBox(globalTopologyOptionsSizer->GetStaticBox(),
ID_GLOBAL_TOPO_MAP_VIEW_RADIO_BOX,
wxT("Map View"),
wxDefaultPosition,
wxDefaultSize,
globalTopoMapViewRadioBoxNChoices,
globalTopoMapViewRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
globalTopoMapViewRadioBox->SetSelection(0);
globalTopologyOptionsSizer->Add(globalTopoMapViewRadioBox, 0, wxALL | wxEXPAND, 5);
wxFlexGridSizer* numHypothesesSizer;
numHypothesesSizer = new wxFlexGridSizer(0, 2, 0, 0);
numHypothesesSizer->SetFlexibleDirection(wxHORIZONTAL);
numHypothesesSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
activeHypothesesText = new wxStaticText(globalTopologyOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Num Leaves:"),
wxDefaultPosition,
wxDefaultSize,
0);
activeHypothesesText->Wrap(-1);
numHypothesesSizer->Add(activeHypothesesText, 0, wxALL, 5);
numActiveHypothesesLabel = new wxStaticText(globalTopologyOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("0"),
wxDefaultPosition,
wxDefaultSize,
0);
numActiveHypothesesLabel->Wrap(-1);
numHypothesesSizer->Add(numActiveHypothesesLabel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
numCompleteHypothesesText = new wxStaticText(globalTopologyOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Num Complete:"),
wxDefaultPosition,
wxDefaultSize,
0);
numCompleteHypothesesText->Wrap(-1);
numHypothesesSizer->Add(numCompleteHypothesesText, 0, wxALL, 5);
numCompleteHypothesesLabel = new wxStaticText(globalTopologyOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("0"),
wxDefaultPosition,
wxDefaultSize,
0);
numCompleteHypothesesLabel->Wrap(-1);
numHypothesesSizer->Add(numCompleteHypothesesLabel, 0, wxALL, 5);
globalTopologyOptionsSizer->Add(numHypothesesSizer, 0, wxEXPAND, 5);
showBestTopoMapCheckBox = new wxCheckBox(globalTopologyOptionsSizer->GetStaticBox(),
ID_SHOW_BEST_TOPO_MAP_CHECK_BOX,
wxT("Show Best Map"),
wxDefaultPosition,
wxDefaultSize,
0);
globalTopologyOptionsSizer->Add(showBestTopoMapCheckBox, 0, wxALL, 5);
mapToShowLabel = new wxStaticText(globalTopologyOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Map To Show:"),
wxDefaultPosition,
wxDefaultSize,
0);
mapToShowLabel->Wrap(-1);
globalTopologyOptionsSizer->Add(mapToShowLabel, 0, wxALL, 5);
topoHypothesisComboBox = new wxComboBox(globalTopologyOptionsSizer->GetStaticBox(),
ID_TOPO_HYPOTHESIS_COMBO_BOX,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0,
NULL,
wxCB_DROPDOWN);
globalTopologyOptionsSizer->Add(topoHypothesisComboBox, 0, wxALL | wxEXPAND, 5);
wxBoxSizer* switchMapsSizer;
switchMapsSizer = new wxBoxSizer(wxHORIZONTAL);
previousHypothesisButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_PREVIOUS_HYPOTHESIS_BUTTON,
wxT("Prev"),
wxDefaultPosition,
wxDefaultSize,
0);
switchMapsSizer->Add(previousHypothesisButton, 0, wxALL, 5);
nextHypothesisButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_NEXT_HYPOTHESIS_BUTTON,
wxT("Next"),
wxDefaultPosition,
wxDefaultSize,
0);
switchMapsSizer->Add(nextHypothesisButton, 0, wxALL, 5);
globalTopologyOptionsSizer->Add(switchMapsSizer, 0, 0, 5);
useGlobalTopoMapButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_USE_GLOBAL_TOPO_MAP_BUTTON,
wxT("Use Current Map"),
wxDefaultPosition,
wxDefaultSize,
0);
globalTopologyOptionsSizer->Add(useGlobalTopoMapButton, 0, wxALIGN_CENTER | wxALL, 5);
loadGlobalTopoMapButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_LOAD_GLOBAL_TOPO_MAP_FROM_FILE_BUTTON,
wxT("Load From File"),
wxDefaultPosition,
wxDefaultSize,
0);
globalTopologyOptionsSizer->Add(loadGlobalTopoMapButton, 0, wxALIGN_CENTER | wxALL, 5);
saveCurrentMapButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_SAVE_CURRENT_MAP_BUTTON,
wxT("Save Current Map"),
wxDefaultPosition,
wxDefaultSize,
0);
globalTopologyOptionsSizer->Add(saveCurrentMapButton, 0, wxALIGN_CENTER | wxALL, 5);
wxStaticBoxSizer* treeOfMapsCommandsSizer;
treeOfMapsCommandsSizer = new wxStaticBoxSizer(
new wxStaticBox(globalTopologyOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Tree of Maps Options")),
wxVERTICAL);
wxGridSizer* treeOfMapOptionsButtonSizer;
treeOfMapOptionsButtonSizer = new wxGridSizer(2, 2, 0, 0);
saveTreeButton = new wxButton(treeOfMapsCommandsSizer->GetStaticBox(),
ID_SAVE_TREE_BUTTON,
wxT("Save Tree"),
wxDefaultPosition,
wxDefaultSize,
0);
saveTreeButton->SetToolTip(wxT("Save the tree of maps in global_topo_hssh to current_tree_of_maps.tom"));
treeOfMapOptionsButtonSizer->Add(saveTreeButton, 0, wxALL, 5);
loadTreeButton = new wxButton(treeOfMapsCommandsSizer->GetStaticBox(),
ID_LOAD_TREE_BUTTON,
wxT("Load Tree"),
wxDefaultPosition,
wxDefaultSize,
0);
loadTreeButton->SetToolTip(wxT("Load the tree of maps saved at current_tree_of_maps.tom"));
treeOfMapOptionsButtonSizer->Add(loadTreeButton, 0, wxALL, 5);
saveMapCacheButton = new wxButton(treeOfMapsCommandsSizer->GetStaticBox(),
ID_SAVE_MAP_CACHE_BUTTON,
wxT("Save Cache"),
wxDefaultPosition,
wxDefaultSize,
0);
saveMapCacheButton->SetToolTip(wxT("Save current MetricMapCache to current_map_cache.mmc"));
treeOfMapOptionsButtonSizer->Add(saveMapCacheButton, 0, wxALL, 5);
loadMapCacheButton = new wxButton(treeOfMapsCommandsSizer->GetStaticBox(),
ID_LOAD_MAP_CACHE_BUTTON,
wxT("Load Cache"),
wxDefaultPosition,
wxDefaultSize,
0);
loadMapCacheButton->SetToolTip(wxT("Load current MetricMapCache from current_map_cache.mmc"));
treeOfMapOptionsButtonSizer->Add(loadMapCacheButton, 0, wxALL, 5);
treeOfMapsCommandsSizer->Add(treeOfMapOptionsButtonSizer, 1, wxEXPAND, 5);
globalTopologyOptionsSizer->Add(treeOfMapsCommandsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* hypothesisInfoSizer;
hypothesisInfoSizer = new wxStaticBoxSizer(
new wxStaticBox(globalTopologyOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Hypothesis Info:")),
wxVERTICAL);
hypothesisInfoGrid =
new wxGrid(hypothesisInfoSizer->GetStaticBox(), ID_HYPOTHESIS_INFO_GRID, wxDefaultPosition, wxDefaultSize, 0);
// Grid
hypothesisInfoGrid->CreateGrid(7, 1);
hypothesisInfoGrid->EnableEditing(true);
hypothesisInfoGrid->EnableGridLines(true);
hypothesisInfoGrid->EnableDragGridSize(false);
hypothesisInfoGrid->SetMargins(0, 0);
// Columns
hypothesisInfoGrid->EnableDragColMove(false);
hypothesisInfoGrid->EnableDragColSize(false);
hypothesisInfoGrid->SetColLabelSize(3);
hypothesisInfoGrid->SetColLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Rows
hypothesisInfoGrid->EnableDragRowSize(true);
hypothesisInfoGrid->SetRowLabelValue(0, wxT("Id:"));
hypothesisInfoGrid->SetRowLabelValue(1, wxT("Depth:"));
hypothesisInfoGrid->SetRowLabelValue(2, wxT("Posterior:"));
hypothesisInfoGrid->SetRowLabelValue(3, wxT("Likelihood:"));
hypothesisInfoGrid->SetRowLabelValue(4, wxT("Prior:"));
hypothesisInfoGrid->SetRowLabelValue(5, wxT("Heuristic Likelihood:"));
hypothesisInfoGrid->SetRowLabelValue(6, wxT("Heuristic Prior:"));
hypothesisInfoGrid->SetRowLabelValue(7, wxEmptyString);
hypothesisInfoGrid->SetRowLabelSize(80);
hypothesisInfoGrid->SetRowLabelAlignment(wxALIGN_RIGHT, wxALIGN_CENTER);
// Label Appearance
// Cell Defaults
hypothesisInfoGrid->SetDefaultCellAlignment(wxALIGN_LEFT, wxALIGN_CENTER);
hypothesisInfoSizer->Add(hypothesisInfoGrid, 0, wxALL | wxEXPAND, 5);
globalTopologyOptionsSizer->Add(hypothesisInfoSizer, 0, 0, 5);
clearGlobalTopoMapsButton = new wxButton(globalTopologyOptionsSizer->GetStaticBox(),
ID_CLEAR_GLOBAL_TOPO_MAPS_BUTTON,
wxT("Clear Maps"),
wxDefaultPosition,
wxDefaultSize,
0);
globalTopologyOptionsSizer->Add(clearGlobalTopoMapsButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
globalTopoScrolledWindow->SetSizer(globalTopologyOptionsSizer);
globalTopoScrolledWindow->Layout();
globalTopologyOptionsSizer->Fit(globalTopoScrolledWindow);
globalTopologySizer->Add(globalTopoScrolledWindow, 0, wxEXPAND | wxALL, 5);
globalTopologyPanel->SetSizer(globalTopologySizer);
globalTopologyPanel->Layout();
globalTopologySizer->Fit(globalTopologyPanel);
frameNotebook->AddPage(globalTopologyPanel, wxT("Global Topology"), false, wxNullBitmap);
evaluationPanel =
new wxPanel(frameNotebook, ID_EVALUATION_PANEL, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* evaluationSizer;
evaluationSizer = new wxBoxSizer(wxHORIZONTAL);
wxFlexGridSizer* evaluationWidgetSizer;
evaluationWidgetSizer = new wxFlexGridSizer(1, 1, 0, 0);
evaluationWidgetSizer->AddGrowableCol(0);
evaluationWidgetSizer->AddGrowableRow(0);
evaluationWidgetSizer->SetFlexibleDirection(wxBOTH);
evaluationWidgetSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
evaluationWidget =
new EvaluationDisplayWidget(evaluationPanel, ID_EVALUATION_WIDGET, wxDefaultPosition, wxDefaultSize);
evaluationWidget->SetMinSize(wxSize(0, 0));
evaluationWidgetSizer->Add(evaluationWidget, 1, wxALIGN_CENTER | wxEXPAND, 0);
evaluationSizer->Add(evaluationWidgetSizer, 1, wxALL | wxEXPAND, 5);
evaluationScrollWindow =
new wxScrolledWindow(evaluationPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
evaluationScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* evaluationOptionsSizer;
evaluationOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
evaluationOptionsSizer->SetFlexibleDirection(wxBOTH);
evaluationOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxStaticBoxSizer* stabilityEvalSizer;
stabilityEvalSizer =
new wxStaticBoxSizer(new wxStaticBox(evaluationScrollWindow, wxID_ANY, wxT("Stability:")), wxVERTICAL);
loadEvalMapButton = new wxButton(stabilityEvalSizer->GetStaticBox(),
ID_LOAD_EVAL_MAP_BUTTON,
wxT("Load Map"),
wxDefaultPosition,
wxDefaultSize,
0);
stabilityEvalSizer->Add(loadEvalMapButton, 0, wxALL | wxEXPAND, 5);
importStabilityLogButton = new wxButton(stabilityEvalSizer->GetStaticBox(),
ID_IMPORT_STABILITY_LOG_BUTTON,
wxT("Import Log"),
wxDefaultPosition,
wxDefaultSize,
0);
stabilityEvalSizer->Add(importStabilityLogButton, 0, wxALL | wxEXPAND, 5);
clearStabilityEvalButton = new wxButton(stabilityEvalSizer->GetStaticBox(),
ID_CLEAR_STABILITY_EVAL_BUTTON,
wxT("Clear All"),
wxDefaultPosition,
wxDefaultSize,
0);
stabilityEvalSizer->Add(clearStabilityEvalButton, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* evalRenderOptionsSizer;
evalRenderOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(stabilityEvalSizer->GetStaticBox(), wxID_ANY, wxT("Rendering Options:")),
wxVERTICAL);
drawEvalBoundaryBox = new wxCheckBox(evalRenderOptionsSizer->GetStaticBox(),
ID_DRAW_EVAL_BOUNDARY_BOX,
wxT("Draw Boundary"),
wxDefaultPosition,
wxDefaultSize,
0);
drawEvalBoundaryBox->SetValue(true);
evalRenderOptionsSizer->Add(drawEvalBoundaryBox, 0, wxALL | wxEXPAND, 5);
drawEvalStarBox = new wxCheckBox(evalRenderOptionsSizer->GetStaticBox(),
ID_DRAW_EVAL_STAR_BOX,
wxT("Draw Star"),
wxDefaultPosition,
wxDefaultSize,
0);
evalRenderOptionsSizer->Add(drawEvalStarBox, 0, wxALL | wxEXPAND, 5);
stabilityEvalSizer->Add(evalRenderOptionsSizer, 0, wxEXPAND, 5);
evaluationOptionsSizer->Add(stabilityEvalSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* mpepcTrajectoryEvalSizer;
mpepcTrajectoryEvalSizer =
new wxStaticBoxSizer(new wxStaticBox(evaluationScrollWindow, wxID_ANY, wxT("MPEPC Trajectory:")), wxHORIZONTAL);
loadMPEPCResultsFileButton = new wxButton(mpepcTrajectoryEvalSizer->GetStaticBox(),
ID_LOAD_MPEPC_RESULTS_FILE_BUTTON,
wxT("Load Results File"),
wxDefaultPosition,
wxDefaultSize,
0);
mpepcTrajectoryEvalSizer->Add(loadMPEPCResultsFileButton, 0, wxALL | wxEXPAND, 5);
evaluationOptionsSizer->Add(mpepcTrajectoryEvalSizer, 1, wxEXPAND, 5);
evaluationScrollWindow->SetSizer(evaluationOptionsSizer);
evaluationScrollWindow->Layout();
evaluationOptionsSizer->Fit(evaluationScrollWindow);
evaluationSizer->Add(evaluationScrollWindow, 0, wxEXPAND | wxALL, 5);
evaluationPanel->SetSizer(evaluationSizer);
evaluationPanel->Layout();
evaluationSizer->Fit(evaluationPanel);
frameNotebook->AddPage(evaluationPanel, wxT("Evaluation"), true, wxNullBitmap);
explorationPanel =
new wxPanel(frameNotebook, ID_EXPLORATION_PANEL, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* explorationPanelSizer;
explorationPanelSizer = new wxBoxSizer(wxHORIZONTAL);
explorationWidget =
new ExplorationDisplayWidget(explorationPanel, ID_EXPLORATION_WIDGET, wxDefaultPosition, wxDefaultSize);
localMetricWidget->SetSize(wxSize(800, 600));
explorationWidget->SetMinSize(wxSize(0, 0));
explorationPanelSizer->Add(explorationWidget, 1, wxALL | wxEXPAND, 5);
wxBoxSizer* explorationOptionsSizer;
explorationOptionsSizer = new wxBoxSizer(wxVERTICAL);
wxStaticBoxSizer* localTopoExplorationSizer;
localTopoExplorationSizer =
new wxStaticBoxSizer(new wxStaticBox(explorationPanel, wxID_ANY, wxT("Local Topo Exploration:")), wxVERTICAL);
wxGridSizer* localTopoExplorationStatusSizer;
localTopoExplorationStatusSizer = new wxGridSizer(0, 2, 0, 0);
totalLocalTopoAreasLabel = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("Total:"),
wxDefaultPosition,
wxDefaultSize,
0);
totalLocalTopoAreasLabel->Wrap(-1);
localTopoExplorationStatusSizer->Add(totalLocalTopoAreasLabel, 0, wxALIGN_RIGHT | wxALL, 5);
totalLocalTopoAreasText = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("0"),
wxDefaultPosition,
wxDefaultSize,
0);
totalLocalTopoAreasText->Wrap(-1);
localTopoExplorationStatusSizer->Add(totalLocalTopoAreasText, 0, wxALL | wxLEFT, 5);
visitedLocalTopoAreasLabel = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("Visited:"),
wxDefaultPosition,
wxDefaultSize,
0);
visitedLocalTopoAreasLabel->Wrap(-1);
localTopoExplorationStatusSizer->Add(visitedLocalTopoAreasLabel, 0, wxALIGN_RIGHT | wxALL, 5);
visitedLocalTopoAreasText = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("0"),
wxDefaultPosition,
wxDefaultSize,
0);
visitedLocalTopoAreasText->Wrap(-1);
localTopoExplorationStatusSizer->Add(visitedLocalTopoAreasText, 0, wxALL | wxLEFT, 5);
remainingLocalTopoAreasLabel = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("Remaining:"),
wxDefaultPosition,
wxDefaultSize,
0);
remainingLocalTopoAreasLabel->Wrap(-1);
localTopoExplorationStatusSizer->Add(remainingLocalTopoAreasLabel, 0, wxALIGN_RIGHT | wxALL, 5);
remainingLocalTopoAreasText = new wxStaticText(localTopoExplorationSizer->GetStaticBox(),
wxID_ANY,
wxT("0"),
wxDefaultPosition,
wxDefaultSize,
0);
remainingLocalTopoAreasText->Wrap(-1);
localTopoExplorationStatusSizer->Add(remainingLocalTopoAreasText, 0, wxALL, 5);
localTopoExplorationSizer->Add(localTopoExplorationStatusSizer, 0, wxALL | wxEXPAND, 5);
explorationOptionsSizer->Add(localTopoExplorationSizer, 0, wxALL | wxEXPAND, 5);
explorationCenterOnRobotCheckbox = new wxCheckBox(explorationPanel,
ID_EXPLORATION_CENTER_ON_ROBOT_BOX,
wxT("Center On Robot"),
wxDefaultPosition,
wxDefaultSize,
0);
explorationCenterOnRobotCheckbox->SetValue(true);
explorationOptionsSizer->Add(explorationCenterOnRobotCheckbox, 0, wxALL | wxEXPAND, 5);
explorationPanelSizer->Add(explorationOptionsSizer, 0, wxEXPAND, 5);
explorationPanel->SetSizer(explorationPanelSizer);
explorationPanel->Layout();
explorationPanelSizer->Fit(explorationPanel);
frameNotebook->AddPage(explorationPanel, wxT("Exploration"), false, wxNullBitmap);
relocalizationPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* relocalizationPanelSizer;
relocalizationPanelSizer = new wxBoxSizer(wxHORIZONTAL);
relocalizationWidget =
new RelocalizationDisplayWidget(relocalizationPanel, ID_RELOCALIZATION_WIDGET, wxDefaultPosition, wxDefaultSize);
relocalizationPanelSizer->Add(relocalizationWidget, 1, wxALL | wxEXPAND, 5);
relocalizationScrollWindow =
new wxScrolledWindow(relocalizationPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
relocalizationScrollWindow->SetScrollRate(0, 5);
wxGridBagSizer* relocalizationOptionsSizer;
relocalizationOptionsSizer = new wxGridBagSizer(0, 0);
relocalizationOptionsSizer->SetFlexibleDirection(wxBOTH);
relocalizationOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxStaticBoxSizer* relocalizeDataSizer;
relocalizeDataSizer =
new wxStaticBoxSizer(new wxStaticBox(relocalizationScrollWindow, wxID_ANY, wxT("Data to Show:")), wxHORIZONTAL);
relocalizeShowLaserCheckBox = new wxCheckBox(relocalizeDataSizer->GetStaticBox(),
ID_RELOCALIZE_SHOW_LASER_BOX,
wxT("Laser"),
wxDefaultPosition,
wxDefaultSize,
0);
relocalizeShowLaserCheckBox->SetValue(true);
relocalizeDataSizer->Add(relocalizeShowLaserCheckBox, 0, wxALL, 5);
relocalizeShowErrorCheckBox = new wxCheckBox(relocalizeDataSizer->GetStaticBox(),
ID_RELOCALIZE_SHOW_ERROR_BOX,
wxT("Error"),
wxDefaultPosition,
wxDefaultSize,
0);
relocalizeShowErrorCheckBox->SetValue(true);
relocalizeDataSizer->Add(relocalizeShowErrorCheckBox, 0, wxALL, 5);
relocalizeShowParticlesCheckBox = new wxCheckBox(relocalizeDataSizer->GetStaticBox(),
ID_RELOCALIZE_SHOW_PARTICLES_BOX,
wxT("Particles"),
wxDefaultPosition,
wxDefaultSize,
0);
relocalizeShowParticlesCheckBox->SetValue(true);
relocalizeDataSizer->Add(relocalizeShowParticlesCheckBox, 0, wxALL, 5);
relocalizationOptionsSizer->Add(relocalizeDataSizer, wxGBPosition(2, 0), wxGBSpan(1, 2), wxEXPAND, 5);
relocalizeLoadLPMButton = new wxButton(relocalizationScrollWindow,
ID_RELOCALIZE_LOAD_LPM_BUTTON,
wxT("Load LPM"),
wxDefaultPosition,
wxDefaultSize,
0);
relocalizationOptionsSizer->Add(relocalizeLoadLPMButton, wxGBPosition(1, 0), wxGBSpan(1, 1), wxALL, 5);
relocalizeLoadGMMButton = new wxButton(relocalizationScrollWindow,
ID_RELOCALIZE_LOAD_GMM_BUTTON,
wxT("Load GMM"),
wxDefaultPosition,
wxDefaultSize,
0);
relocalizationOptionsSizer->Add(relocalizeLoadGMMButton,
wxGBPosition(1, 1),
wxGBSpan(1, 1),
wxALIGN_CENTER | wxALIGN_LEFT | wxALL,
5);
wxString relocalizeModeRadioChoices[] = {wxT("Local"), wxT("Global")};
int relocalizeModeRadioNChoices = sizeof(relocalizeModeRadioChoices) / sizeof(wxString);
relocalizeModeRadio = new wxRadioBox(relocalizationScrollWindow,
ID_RELOCALIZATION_MODE_RADIO,
wxT("Relocalization Mode:"),
wxDefaultPosition,
wxDefaultSize,
relocalizeModeRadioNChoices,
relocalizeModeRadioChoices,
1,
wxRA_SPECIFY_ROWS);
relocalizeModeRadio->SetSelection(0);
relocalizationOptionsSizer->Add(relocalizeModeRadio, wxGBPosition(0, 0), wxGBSpan(1, 2), wxALL | wxEXPAND, 5);
wxStaticBoxSizer* initializerOptionsSizer;
initializerOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(relocalizationScrollWindow, wxID_ANY, wxT("Initializer Options:")),
wxVERTICAL);
wxStaticBoxSizer* regionInitializerOptionsSizer;
regionInitializerOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(initializerOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Region:")),
wxVERTICAL);
wxBoxSizer* regionNumSamplesSizer;
regionNumSamplesSizer = new wxBoxSizer(wxHORIZONTAL);
regionNumSamplesLabel = new wxStaticText(regionInitializerOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Num Samples:"),
wxDefaultPosition,
wxDefaultSize,
0);
regionNumSamplesLabel->Wrap(-1);
regionNumSamplesSizer->Add(regionNumSamplesLabel, 0, wxALIGN_CENTER | wxALL, 5);
regionNumSamplesText = new wxTextCtrl(regionInitializerOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("30000"),
wxDefaultPosition,
wxDefaultSize,
0);
regionNumSamplesSizer->Add(regionNumSamplesText, 0, wxALL, 5);
regionInitializerOptionsSizer->Add(regionNumSamplesSizer, 1, wxEXPAND, 5);
wxBoxSizer* regionPosesPerPosSizer;
regionPosesPerPosSizer = new wxBoxSizer(wxHORIZONTAL);
regionPosesPerPosLabel = new wxStaticText(regionInitializerOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Poses Per Position:"),
wxDefaultPosition,
wxDefaultSize,
0);
regionPosesPerPosLabel->Wrap(-1);
regionPosesPerPosSizer->Add(regionPosesPerPosLabel, 0, wxALIGN_CENTER | wxALL, 5);
regionPosesPerPositionText = new wxTextCtrl(regionInitializerOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("60"),
wxDefaultPosition,
wxDefaultSize,
0);
regionPosesPerPosSizer->Add(regionPosesPerPositionText, 0, wxALIGN_CENTER | wxALL, 5);
regionInitializerOptionsSizer->Add(regionPosesPerPosSizer, 1, wxEXPAND, 5);
setRegionRelocalizeButton = new wxToggleButton(regionInitializerOptionsSizer->GetStaticBox(),
ID_SET_REGION_RELOCALIZE_BUTTON,
wxT("Set Region"),
wxDefaultPosition,
wxDefaultSize,
0);
setRegionRelocalizeButton->SetFont(
wxFont(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxEmptyString));
regionInitializerOptionsSizer->Add(setRegionRelocalizeButton, 0, wxALL | wxEXPAND, 5);
sendRegionMessageButton = new wxButton(regionInitializerOptionsSizer->GetStaticBox(),
ID_SEND_REGION_MESSAGE_BUTTON,
wxT("Send Message"),
wxDefaultPosition,
wxDefaultSize,
0);
sendRegionMessageButton->SetFont(
wxFont(14, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxEmptyString));
regionInitializerOptionsSizer->Add(sendRegionMessageButton, 0, wxALL | wxEXPAND, 5);
initializerOptionsSizer->Add(regionInitializerOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* freeSpaceInitializerSizer;
freeSpaceInitializerSizer =
new wxStaticBoxSizer(new wxStaticBox(initializerOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Free Space:")),
wxVERTICAL);
wxBoxSizer* freeSpaceCellStrideSizer;
freeSpaceCellStrideSizer = new wxBoxSizer(wxHORIZONTAL);
freeSpaceCellStrideLabel = new wxStaticText(freeSpaceInitializerSizer->GetStaticBox(),
wxID_ANY,
wxT("Cell Stride:"),
wxDefaultPosition,
wxDefaultSize,
0);
freeSpaceCellStrideLabel->Wrap(-1);
freeSpaceCellStrideSizer->Add(freeSpaceCellStrideLabel, 0, wxALIGN_CENTER | wxALL, 5);
freeSpaceCellStrideText = new wxTextCtrl(freeSpaceInitializerSizer->GetStaticBox(),
wxID_ANY,
wxT("10"),
wxDefaultPosition,
wxDefaultSize,
0);
freeSpaceCellStrideSizer->Add(freeSpaceCellStrideText, 0, wxALIGN_CENTER | wxALL, 5);
freeSpaceInitializerSizer->Add(freeSpaceCellStrideSizer, 0, wxEXPAND, 5);
wxBoxSizer* freeSpacePosesPerCellSizer;
freeSpacePosesPerCellSizer = new wxBoxSizer(wxHORIZONTAL);
freeSpacePosesPerCellLabel = new wxStaticText(freeSpaceInitializerSizer->GetStaticBox(),
wxID_ANY,
wxT("Poses Per Cell:"),
wxDefaultPosition,
wxDefaultSize,
0);
freeSpacePosesPerCellLabel->Wrap(-1);
freeSpacePosesPerCellSizer->Add(freeSpacePosesPerCellLabel, 0, wxALIGN_CENTER | wxALL, 5);
freeSpacePosesPerCellText = new wxTextCtrl(freeSpaceInitializerSizer->GetStaticBox(),
wxID_ANY,
wxT("10"),
wxDefaultPosition,
wxDefaultSize,
0);
freeSpacePosesPerCellSizer->Add(freeSpacePosesPerCellText, 0, wxALL, 5);
freeSpaceInitializerSizer->Add(freeSpacePosesPerCellSizer, 1, wxEXPAND, 5);
sendFreeSpaceMessageButton = new wxButton(freeSpaceInitializerSizer->GetStaticBox(),
ID_SEND_FREE_SPACE_MESSAGE_BUTTON,
wxT("Send Message"),
wxDefaultPosition,
wxDefaultSize,
0);
sendFreeSpaceMessageButton->SetFont(
wxFont(14, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxEmptyString));
freeSpaceInitializerSizer->Add(sendFreeSpaceMessageButton, 0, wxALL | wxEXPAND, 5);
initializerOptionsSizer->Add(freeSpaceInitializerSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* scanMatchingInitializerSizer;
scanMatchingInitializerSizer =
new wxStaticBoxSizer(new wxStaticBox(initializerOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Scan Matching:")),
wxVERTICAL);
sendScanMatchingMessageButton = new wxButton(scanMatchingInitializerSizer->GetStaticBox(),
ID_SEND_SCAN_MATCHING_MESSAGE_BUTTON,
wxT("Send Message"),
wxDefaultPosition,
wxDefaultSize,
0);
sendScanMatchingMessageButton->SetFont(
wxFont(14, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxEmptyString));
scanMatchingInitializerSizer->Add(sendScanMatchingMessageButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
initializerOptionsSizer->Add(scanMatchingInitializerSizer, 0, wxEXPAND, 5);
relocalizationOptionsSizer->Add(initializerOptionsSizer, wxGBPosition(3, 0), wxGBSpan(1, 2), wxEXPAND, 5);
relocalizationScrollWindow->SetSizer(relocalizationOptionsSizer);
relocalizationScrollWindow->Layout();
relocalizationOptionsSizer->Fit(relocalizationScrollWindow);
relocalizationPanelSizer->Add(relocalizationScrollWindow, 0, wxEXPAND | wxALL, 5);
relocalizationPanel->SetSizer(relocalizationPanelSizer);
relocalizationPanel->Layout();
relocalizationPanelSizer->Fit(relocalizationPanel);
frameNotebook->AddPage(relocalizationPanel, wxT("Relocalization"), false, wxNullBitmap);
plannerScriptingPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* scriptingPanelSizer;
scriptingPanelSizer = new wxBoxSizer(wxHORIZONTAL);
scriptingWidget =
new PlannerScriptingWidget(plannerScriptingPanel, ID_PLANNER_SCRIPTING_WIDGET, wxDefaultPosition, wxDefaultSize);
scriptingPanelSizer->Add(scriptingWidget, 1, wxALL | wxEXPAND, 5);
scriptingOptionsScrolledWindow =
new wxScrolledWindow(plannerScriptingPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL);
scriptingOptionsScrolledWindow->SetScrollRate(0, 5);
wxBoxSizer* scriptingOptionsSizer;
scriptingOptionsSizer = new wxBoxSizer(wxVERTICAL);
wxStaticBoxSizer* scriptMapOptionsSizer;
scriptMapOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(scriptingOptionsScrolledWindow, wxID_ANY, wxT("Map Options")), wxHORIZONTAL);
scriptingLoadMapButton = new wxButton(scriptMapOptionsSizer->GetStaticBox(),
ID_SCRIPTING_LOAD_MAP_BUTTON,
wxT("Load"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptMapOptionsSizer->Add(scriptingLoadMapButton, 0, wxALL, 5);
scriptingCaptureMapButton = new wxButton(scriptMapOptionsSizer->GetStaticBox(),
ID_SCRIPTING_CAPTURE_MAP_BUTTON,
wxT("Capture"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptMapOptionsSizer->Add(scriptingCaptureMapButton, 0, wxALL, 5);
scriptingOptionsSizer->Add(scriptMapOptionsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* scriptingTargetsSizer;
scriptingTargetsSizer =
new wxStaticBoxSizer(new wxStaticBox(scriptingOptionsScrolledWindow, wxID_ANY, wxT("Target Options")),
wxVERTICAL);
scriptingTargetSetList = new wxListCtrl(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPTING_TARGET_SET_LIST,
wxDefaultPosition,
wxDefaultSize,
wxLC_HRULES | wxLC_REPORT | wxLC_SINGLE_SEL);
scriptingTargetsSizer->Add(scriptingTargetSetList, 1, wxALL | wxEXPAND, 5);
wxFlexGridSizer* targetDescriptionSizer;
targetDescriptionSizer = new wxFlexGridSizer(0, 2, 0, 0);
targetDescriptionSizer->SetFlexibleDirection(wxBOTH);
targetDescriptionSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
scriptTargetNameLabel = new wxStaticText(scriptingTargetsSizer->GetStaticBox(),
wxID_ANY,
wxT("Name:"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetNameLabel->Wrap(-1);
targetDescriptionSizer->Add(scriptTargetNameLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
scriptTargetNameText = new wxTextCtrl(scriptingTargetsSizer->GetStaticBox(),
wxID_ANY,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
targetDescriptionSizer->Add(scriptTargetNameText, 1, wxALL | wxEXPAND, 5);
scriptTargetTypeLael = new wxStaticText(scriptingTargetsSizer->GetStaticBox(),
wxID_ANY,
wxT("Type:"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetTypeLael->Wrap(-1);
targetDescriptionSizer->Add(scriptTargetTypeLael, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
wxBoxSizer* scriptTargetTypeRadioSizer;
scriptTargetTypeRadioSizer = new wxBoxSizer(wxHORIZONTAL);
scriptPoseTargetButton = new wxRadioButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_POSE_TARGET_BUTTON,
wxT("Pose"),
wxDefaultPosition,
wxDefaultSize,
wxRB_GROUP);
scriptPoseTargetButton->SetValue(true);
scriptTargetTypeRadioSizer->Add(scriptPoseTargetButton, 0, wxALL, 5);
scriptElevatorTargetButton = new wxRadioButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_ELEVATOR_TARGET_BUTTON,
wxT("Elevator"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetTypeRadioSizer->Add(scriptElevatorTargetButton, 0, wxALL, 5);
targetDescriptionSizer->Add(scriptTargetTypeRadioSizer, 1, wxEXPAND, 5);
scriptTargetPoseLabel = new wxStaticText(scriptingTargetsSizer->GetStaticBox(),
wxID_ANY,
wxT("Pose:"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetPoseLabel->Wrap(-1);
targetDescriptionSizer->Add(scriptTargetPoseLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
scriptTargetPoseText = new wxTextCtrl(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_TARGET_POSE_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
wxTE_READONLY);
targetDescriptionSizer->Add(scriptTargetPoseText, 0, wxALL | wxEXPAND, 5);
scriptTargetSelectPoseButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_TARGET_SELECT_POSE_BUTTON,
wxT("Select Pose"),
wxDefaultPosition,
wxDefaultSize,
0);
targetDescriptionSizer->Add(scriptTargetSelectPoseButton,
0,
wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL | wxALL | wxEXPAND,
5);
scriptTargetCurrentButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_TARGET_CURRENT_BUTTON,
wxT("Current Pose"),
wxDefaultPosition,
wxDefaultSize,
0);
targetDescriptionSizer->Add(scriptTargetCurrentButton, 0, wxALL, 5);
scriptingTargetsSizer->Add(targetDescriptionSizer, 0, wxEXPAND, 5);
wxGridSizer* scriptTargetCreationSizer;
scriptTargetCreationSizer = new wxGridSizer(2, 2, 0, 0);
scriptCreateTargetButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_CREATE_TARGET_BUTTON,
wxT("Add"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetCreationSizer->Add(scriptCreateTargetButton, 0, wxALL, 5);
scriptEraseTargetButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_ERASE_TARGET_BUTTON,
wxT("Remove"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetCreationSizer->Add(scriptEraseTargetButton, 0, wxALL, 5);
scriptSaveTargetsButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_SAVE_TARGETS_BUTTON,
wxT("Save"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetCreationSizer->Add(scriptSaveTargetsButton, 0, wxALL, 5);
scriptLoadTargetsButton = new wxButton(scriptingTargetsSizer->GetStaticBox(),
ID_SCRIPT_LOAD_TARGETS_BUTTON,
wxT("Load"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetCreationSizer->Add(scriptLoadTargetsButton, 0, wxALL, 5);
scriptingTargetsSizer->Add(scriptTargetCreationSizer, 0, wxALIGN_CENTER, 5);
scriptingOptionsSizer->Add(scriptingTargetsSizer, 0, wxEXPAND, 5);
wxStaticBoxSizer* scriptOptionsSizer;
scriptOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(scriptingOptionsScrolledWindow, wxID_ANY, wxT("Script Options")),
wxVERTICAL);
scriptTargetsList = new wxListBox(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_TARGETS_LIST,
wxDefaultPosition,
wxDefaultSize,
0,
NULL,
wxLB_SINGLE);
scriptOptionsSizer->Add(scriptTargetsList, 1, wxALL | wxEXPAND, 5);
wxGridSizer* scriptTargetAdditionSizer;
scriptTargetAdditionSizer = new wxGridSizer(2, 2, 0, 0);
scriptAddTargetButton = new wxButton(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_ADD_TARGET_BUTTON,
wxT("Add"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetAdditionSizer->Add(scriptAddTargetButton, 0, wxALL, 5);
scriptRemoveTargetButton = new wxButton(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_REMOVE_TARGET_BUTTON,
wxT("Remove"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetAdditionSizer->Add(scriptRemoveTargetButton, 0, wxALL, 5);
scriptSaveButton = new wxButton(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_SAVE_BUTTON,
wxT("Save"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetAdditionSizer->Add(scriptSaveButton, 0, wxALL, 5);
scriptLoadButton = new wxButton(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_LOAD_BUTTON,
wxT("Load"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptTargetAdditionSizer->Add(scriptLoadButton, 0, wxALL, 5);
scriptOptionsSizer->Add(scriptTargetAdditionSizer, 0, wxEXPAND, 5);
scriptSendButton = new wxButton(scriptOptionsSizer->GetStaticBox(),
ID_SCRIPT_SEND_BUTTON,
wxT("Send"),
wxDefaultPosition,
wxDefaultSize,
0);
scriptOptionsSizer->Add(scriptSendButton, 0, wxALL | wxEXPAND, 5);
scriptingOptionsSizer->Add(scriptOptionsSizer, 1, wxEXPAND, 5);
scriptingOptionsScrolledWindow->SetSizer(scriptingOptionsSizer);
scriptingOptionsScrolledWindow->Layout();
scriptingOptionsSizer->Fit(scriptingOptionsScrolledWindow);
scriptingPanelSizer->Add(scriptingOptionsScrolledWindow, 0, wxALL | wxEXPAND, 5);
plannerScriptingPanel->SetSizer(scriptingPanelSizer);
plannerScriptingPanel->Layout();
scriptingPanelSizer->Fit(plannerScriptingPanel);
frameNotebook->AddPage(plannerScriptingPanel, wxT("Scripting"), false, wxNullBitmap);
globalMetricPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* globalMetricPanelSizer;
globalMetricPanelSizer = new wxBoxSizer(wxHORIZONTAL);
globalMetricWidget =
new GlobalMetricDisplayWidget(globalMetricPanel, ID_GLOBAL_METRIC_WIDGET, wxDefaultPosition, wxDefaultSize);
globalMetricPanelSizer->Add(globalMetricWidget, 1, wxALL | wxEXPAND, 5);
globalMetricScrolledWindow =
new wxScrolledWindow(globalMetricPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL);
globalMetricScrolledWindow->SetScrollRate(5, 5);
wxBoxSizer* globalMetricOptionsSizer;
globalMetricOptionsSizer = new wxBoxSizer(wxVERTICAL);
wxStaticBoxSizer* globalMetricLoadOptions;
globalMetricLoadOptions =
new wxStaticBoxSizer(new wxStaticBox(globalMetricScrolledWindow, wxID_ANY, wxT("Loading Options:")), wxVERTICAL);
globalMetricCaptureLPMButton = new wxButton(globalMetricLoadOptions->GetStaticBox(),
ID_GLOBAL_METRIC_CAPTURE_LPM_BUTTON,
wxT("Capture LPM"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricLoadOptions->Add(globalMetricCaptureLPMButton, 0, wxALL | wxEXPAND, 5);
loadLPMForGlobalMetricButton = new wxButton(globalMetricLoadOptions->GetStaticBox(),
ID_LOAD_LPM_FOR_GLOBAL_METRIC_BUTTON,
wxT("Load LPM"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricLoadOptions->Add(loadLPMForGlobalMetricButton, 0, wxALL | wxEXPAND, 5);
loadGlobalMetricMapButton = new wxButton(globalMetricLoadOptions->GetStaticBox(),
ID_LOAD_GLOBAL_METRIC_MAP_BUTTON,
wxT("Local Global Map"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricLoadOptions->Add(loadGlobalMetricMapButton, 0, wxALL | wxEXPAND, 5);
globalMetricOptionsSizer->Add(globalMetricLoadOptions, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* globalMetricSaveOptions;
globalMetricSaveOptions =
new wxStaticBoxSizer(new wxStaticBox(globalMetricScrolledWindow, wxID_ANY, wxT("Save Options:")), wxVERTICAL);
globalMetricMapNameText = new wxTextCtrl(globalMetricSaveOptions->GetStaticBox(),
ID_GLOBAL_METRIC_MAP_NAME_TEXT,
wxT("Map Name"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricSaveOptions->Add(globalMetricMapNameText, 0, wxALL | wxEXPAND, 5);
saveGlobalMapButton = new wxButton(globalMetricSaveOptions->GetStaticBox(),
ID_SAVE_GLOBAL_MAP_BUTTON,
wxT("Save Global Map"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricSaveOptions->Add(saveGlobalMapButton, 0, wxALL | wxEXPAND, 5);
globalMetricOptionsSizer->Add(globalMetricSaveOptions, 0, wxEXPAND, 5);
globalMetricRelocalizeButton = new wxButton(globalMetricScrolledWindow,
ID_GLOBAL_METRIC_RELOCALIZE_BUTTON,
wxT("Relocalize!"),
wxDefaultPosition,
wxDefaultSize,
0);
globalMetricRelocalizeButton->SetFont(
wxFont(16, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Sans")));
globalMetricOptionsSizer->Add(globalMetricRelocalizeButton, 0, wxALL | wxEXPAND, 5);
globalMetricScrolledWindow->SetSizer(globalMetricOptionsSizer);
globalMetricScrolledWindow->Layout();
globalMetricOptionsSizer->Fit(globalMetricScrolledWindow);
globalMetricPanelSizer->Add(globalMetricScrolledWindow, 0, wxALL | wxEXPAND | wxFIXED_MINSIZE, 5);
globalMetricPanel->SetSizer(globalMetricPanelSizer);
globalMetricPanel->Layout();
globalMetricPanelSizer->Fit(globalMetricPanel);
frameNotebook->AddPage(globalMetricPanel, wxT("Global Metric"), false, wxNullBitmap);
calibrationPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* calibrationPanelSizer;
calibrationPanelSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* calibrationWidgetSizer;
calibrationWidgetSizer = new wxBoxSizer(wxHORIZONTAL);
calibrationWidget =
new CalibrationDisplayWidget(calibrationPanel, ID_CALIBRATION_WIDGET, wxDefaultPosition, wxDefaultSize);
calibrationWidget->SetSize(wxSize(800, 600));
calibrationWidget->SetMinSize(wxSize(0, 0));
calibrationWidgetSizer->Add(calibrationWidget, 1, wxALIGN_CENTER | wxEXPAND, 0);
calibrationPanelSizer->Add(calibrationWidgetSizer, 1, wxALL | wxEXPAND, 5);
calibrationScrollWindow =
new wxScrolledWindow(calibrationPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL);
calibrationScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* calibrationOptionsSizer;
calibrationOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
calibrationOptionsSizer->SetFlexibleDirection(wxBOTH);
calibrationOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxStaticBoxSizer* laserOptionsSizer;
laserOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(calibrationScrollWindow, wxID_ANY, wxT("Laser Options")), wxHORIZONTAL);
wxFlexGridSizer* laserOptionsFlexGridSizer;
laserOptionsFlexGridSizer = new wxFlexGridSizer(0, 2, 0, 0);
laserOptionsFlexGridSizer->SetFlexibleDirection(wxBOTH);
laserOptionsFlexGridSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
showFrontLaserCheckBox = new wxCheckBox(laserOptionsSizer->GetStaticBox(),
ID_SHOW_FRONT_LASER_BOX,
wxT("Show Front Laser"),
wxDefaultPosition,
wxDefaultSize,
0);
showFrontLaserCheckBox->SetValue(true);
laserOptionsFlexGridSizer->Add(showFrontLaserCheckBox, 0, wxALL, 5);
showBackLaserCheckBox = new wxCheckBox(laserOptionsSizer->GetStaticBox(),
ID_SHOW_BACK_LASER_BOX,
wxT("Show Back Laser"),
wxDefaultPosition,
wxDefaultSize,
0);
showBackLaserCheckBox->SetValue(true);
laserOptionsFlexGridSizer->Add(showBackLaserCheckBox, 0, wxALL, 5);
wxFlexGridSizer* frontLaserCoords;
frontLaserCoords = new wxFlexGridSizer(0, 2, 0, 0);
frontLaserCoords->SetFlexibleDirection(wxBOTH);
frontLaserCoords->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
frontLaserCoordsXLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" x:"), wxDefaultPosition, wxDefaultSize, 0);
frontLaserCoordsXLabel->Wrap(-1);
frontLaserCoords->Add(frontLaserCoordsXLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
frontLaserCoordsXText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_FRONT_LASER_COORDS_X,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
frontLaserCoords->Add(frontLaserCoordsXText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
frontLaserCoordsYLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" y:"), wxDefaultPosition, wxDefaultSize, 0);
frontLaserCoordsYLabel->Wrap(-1);
frontLaserCoords->Add(frontLaserCoordsYLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
frontLaserCoordsYText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_FRONT_LASER_COORDS_Y,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
frontLaserCoords->Add(frontLaserCoordsYText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
frontLaserCoordsThetaLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" θ:"), wxDefaultPosition, wxDefaultSize, 0);
frontLaserCoordsThetaLabel->Wrap(-1);
frontLaserCoords->Add(frontLaserCoordsThetaLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
frontLaserCoordsThetaText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_FRONT_LASER_COORDS_THETA,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
frontLaserCoords->Add(frontLaserCoordsThetaText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
frontLaserPitchLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Pitch:"), wxDefaultPosition, wxDefaultSize, 0);
frontLaserPitchLabel->Wrap(-1);
frontLaserCoords->Add(frontLaserPitchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
frontLaserPitchText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_FRONT_LASER_PITCH_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
frontLaserCoords->Add(frontLaserPitchText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
frontLaserRollLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Roll:"), wxDefaultPosition, wxDefaultSize, 0);
frontLaserRollLabel->Wrap(-1);
frontLaserCoords->Add(frontLaserRollLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
frontLaserRollText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_FRONT_LASER_ROLL_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
frontLaserCoords->Add(frontLaserRollText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
laserOptionsFlexGridSizer->Add(frontLaserCoords, 1, wxEXPAND, 5);
wxFlexGridSizer* BackLaserCoords;
BackLaserCoords = new wxFlexGridSizer(0, 2, 0, 0);
BackLaserCoords->SetFlexibleDirection(wxBOTH);
BackLaserCoords->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
backLaserCoordsXLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" x:"), wxDefaultPosition, wxDefaultSize, 0);
backLaserCoordsXLabel->Wrap(-1);
BackLaserCoords->Add(backLaserCoordsXLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
backLaserCoordsXText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_BACK_LASER_COORDS_X,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
BackLaserCoords->Add(backLaserCoordsXText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
backLaserCoordsYLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" y:"), wxDefaultPosition, wxDefaultSize, 0);
backLaserCoordsYLabel->Wrap(-1);
BackLaserCoords->Add(backLaserCoordsYLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
backLaserCoordsYText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_BACK_LASER_COORDS_Y,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
BackLaserCoords->Add(backLaserCoordsYText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
backLaserCoordsThetaLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT(" θ:"), wxDefaultPosition, wxDefaultSize, 0);
backLaserCoordsThetaLabel->Wrap(-1);
BackLaserCoords->Add(backLaserCoordsThetaLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
backLaserCoordsThetaText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_BACK_LASER_COORDS_THETA,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
BackLaserCoords->Add(backLaserCoordsThetaText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
backLaserPitchLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Pitch:"), wxDefaultPosition, wxDefaultSize, 0);
backLaserPitchLabel->Wrap(-1);
BackLaserCoords->Add(backLaserPitchLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
backLaserPitchText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_BACK_LASER_PITCH_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
BackLaserCoords->Add(backLaserPitchText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
backLaserRollLabel =
new wxStaticText(laserOptionsSizer->GetStaticBox(), wxID_ANY, wxT("Roll:"), wxDefaultPosition, wxDefaultSize, 0);
backLaserRollLabel->Wrap(-1);
BackLaserCoords->Add(backLaserRollLabel, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, 5);
backLaserRollText = new wxTextCtrl(laserOptionsSizer->GetStaticBox(),
ID_BACK_LASER_ROLL_TEXT,
wxEmptyString,
wxDefaultPosition,
wxDefaultSize,
0);
BackLaserCoords->Add(backLaserRollText, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
laserOptionsFlexGridSizer->Add(BackLaserCoords, 1, wxEXPAND, 5);
laserOptionsSizer->Add(laserOptionsFlexGridSizer, 1, wxEXPAND, 5);
calibrationOptionsSizer->Add(laserOptionsSizer, 1, wxALIGN_RIGHT | wxEXPAND, 5);
wxStaticBoxSizer* tiltCalibrationSizer;
tiltCalibrationSizer =
new wxStaticBoxSizer(new wxStaticBox(calibrationScrollWindow, wxID_ANY, wxT("Tilt Calibration")), wxVERTICAL);
loadTiltDataButton = new wxButton(tiltCalibrationSizer->GetStaticBox(),
ID_LOAD_TILT_DATA_BUTTON,
wxT("Load Tilt Data"),
wxDefaultPosition,
wxDefaultSize,
0);
tiltCalibrationSizer->Add(loadTiltDataButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
wxString tiltLaserRadioChoices[] = {wxT("Front"), wxT("Back")};
int tiltLaserRadioNChoices = sizeof(tiltLaserRadioChoices) / sizeof(wxString);
tiltLaserRadio = new wxRadioBox(tiltCalibrationSizer->GetStaticBox(),
ID_TILT_LASER_RADIO,
wxT("Laser to Calibrate:"),
wxDefaultPosition,
wxDefaultSize,
tiltLaserRadioNChoices,
tiltLaserRadioChoices,
1,
wxRA_SPECIFY_COLS);
tiltLaserRadio->SetSelection(0);
tiltCalibrationSizer->Add(tiltLaserRadio, 0, wxALL | wxEXPAND, 5);
wxBoxSizer* lineStartIndexSizer;
lineStartIndexSizer = new wxBoxSizer(wxHORIZONTAL);
lineStartIndexLabel = new wxStaticText(tiltCalibrationSizer->GetStaticBox(),
wxID_ANY,
wxT("Line start index:"),
wxDefaultPosition,
wxDefaultSize,
0);
lineStartIndexLabel->Wrap(-1);
lineStartIndexSizer->Add(lineStartIndexLabel, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
lineStartIndexText = new wxTextCtrl(tiltCalibrationSizer->GetStaticBox(),
ID_LINE_START_INDEX_TEXT,
wxT("-1"),
wxDefaultPosition,
wxDefaultSize,
0);
lineStartIndexSizer->Add(lineStartIndexText, 1, wxALL, 5);
tiltCalibrationSizer->Add(lineStartIndexSizer, 1, wxEXPAND, 5);
wxBoxSizer* lineEndIndexSizer;
lineEndIndexSizer = new wxBoxSizer(wxHORIZONTAL);
lineEndIndexLabel = new wxStaticText(tiltCalibrationSizer->GetStaticBox(),
wxID_ANY,
wxT("Line end index:"),
wxDefaultPosition,
wxDefaultSize,
0);
lineEndIndexLabel->Wrap(-1);
lineEndIndexSizer->Add(lineEndIndexLabel, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
lineEndIndexText = new wxTextCtrl(tiltCalibrationSizer->GetStaticBox(),
ID_LINE_END_INDEX_TEXT,
wxT("-1"),
wxDefaultPosition,
wxDefaultSize,
0);
lineEndIndexSizer->Add(lineEndIndexText, 1, wxALL, 5);
tiltCalibrationSizer->Add(lineEndIndexSizer, 1, wxEXPAND, 5);
calibratePitchButton = new wxButton(tiltCalibrationSizer->GetStaticBox(),
ID_CALIBRATE_PITCH_BUTTON,
wxT("Calibrate Pitch"),
wxDefaultPosition,
wxDefaultSize,
0);
tiltCalibrationSizer->Add(calibratePitchButton, 0, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
calibrateRollButton = new wxButton(tiltCalibrationSizer->GetStaticBox(),
ID_CALIBRATE_ROLL_BUTTON,
wxT("Calibrate Roll"),
wxDefaultPosition,
wxDefaultSize,
0);
tiltCalibrationSizer->Add(calibrateRollButton, 0, wxALL | wxEXPAND, 5);
calibrationOptionsSizer->Add(tiltCalibrationSizer, 1, wxEXPAND, 5);
calibrationScrollWindow->SetSizer(calibrationOptionsSizer);
calibrationScrollWindow->Layout();
calibrationOptionsSizer->Fit(calibrationScrollWindow);
calibrationPanelSizer->Add(calibrationScrollWindow, 0, wxALL | wxEXPAND, 5);
calibrationPanel->SetSizer(calibrationPanelSizer);
calibrationPanel->Layout();
calibrationPanelSizer->Fit(calibrationPanel);
frameNotebook->AddPage(calibrationPanel, wxT("Calibration"), false, wxNullBitmap);
decisionPlannerPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
decisionPlannerPanel->Enable(false);
decisionPlannerPanel->Hide();
wxBoxSizer* decisionPlannerPanelSizer;
decisionPlannerPanelSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* decisionPlannerWidgetSizer;
decisionPlannerWidgetSizer = new wxBoxSizer(wxVERTICAL);
decisionPlannerWidget = new DecisionPlannerDisplayWidget(decisionPlannerPanel,
ID_DECISION_PLANNER_WIDGET,
wxDefaultPosition,
wxDefaultSize);
decisionPlannerWidgetSizer->Add(decisionPlannerWidget, 1, wxALL | wxEXPAND, 5);
decisionPlannerPanelSizer->Add(decisionPlannerWidgetSizer, 1, wxEXPAND, 5);
decisionPlannerScrollWindow =
new wxScrolledWindow(decisionPlannerPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
decisionPlannerScrollWindow->SetScrollRate(0, 5);
wxFlexGridSizer* decisionPlannerOptionsSizer;
decisionPlannerOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
decisionPlannerOptionsSizer->SetFlexibleDirection(wxBOTH);
decisionPlannerOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
decisionCommandQueueList = new wxListBox(decisionPlannerScrollWindow,
ID_DECISION_COMMAND_QUEUE_LIST,
wxDefaultPosition,
wxDefaultSize,
0,
NULL,
wxLB_EXTENDED | wxLB_MULTIPLE | wxLB_NEEDED_SB);
decisionCommandQueueList->Append(wxT("1"));
decisionCommandQueueList->Append(wxT("2"));
decisionCommandQueueList->Append(wxT("3"));
decisionCommandQueueList->Append(wxT("4"));
decisionCommandQueueList->Append(wxT("5"));
decisionCommandQueueList->Append(wxT("6"));
decisionCommandQueueList->Append(wxT("7"));
decisionCommandQueueList->Append(wxT("8"));
decisionCommandQueueList->Append(wxT("9"));
decisionCommandQueueList->Append(wxT("10"));
decisionPlannerOptionsSizer->Add(decisionCommandQueueList, 1, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* localPlaceStateSizer;
localPlaceStateSizer =
new wxStaticBoxSizer(new wxStaticBox(decisionPlannerScrollWindow, wxID_ANY, wxT("Local Place State:")),
wxVERTICAL);
localPlaceStateGrid =
new wxGrid(localPlaceStateSizer->GetStaticBox(), wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
// Grid
localPlaceStateGrid->CreateGrid(3, 1);
localPlaceStateGrid->EnableEditing(true);
localPlaceStateGrid->EnableGridLines(true);
localPlaceStateGrid->EnableDragGridSize(false);
localPlaceStateGrid->SetMargins(0, 0);
// Columns
localPlaceStateGrid->EnableDragColMove(false);
localPlaceStateGrid->EnableDragColSize(true);
localPlaceStateGrid->SetColLabelSize(1);
localPlaceStateGrid->SetColLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Rows
localPlaceStateGrid->AutoSizeRows();
localPlaceStateGrid->EnableDragRowSize(true);
localPlaceStateGrid->SetRowLabelValue(0, wxT("ID:"));
localPlaceStateGrid->SetRowLabelValue(1, wxT("Entry:"));
localPlaceStateGrid->SetRowLabelValue(2, wxT("Exit:"));
localPlaceStateGrid->SetRowLabelSize(80);
localPlaceStateGrid->SetRowLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Label Appearance
// Cell Defaults
localPlaceStateGrid->SetDefaultCellAlignment(wxALIGN_LEFT, wxALIGN_TOP);
localPlaceStateSizer->Add(localPlaceStateGrid, 0, wxALIGN_CENTER | wxALL, 5);
decisionPlannerOptionsSizer->Add(localPlaceStateSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* localPathStateSizer;
localPathStateSizer =
new wxStaticBoxSizer(new wxStaticBox(decisionPlannerScrollWindow, wxID_ANY, wxT("Local Path State:")),
wxVERTICAL);
localPathStateGrid = new wxGrid(localPathStateSizer->GetStaticBox(), wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
// Grid
localPathStateGrid->CreateGrid(3, 1);
localPathStateGrid->EnableEditing(true);
localPathStateGrid->EnableGridLines(true);
localPathStateGrid->EnableDragGridSize(false);
localPathStateGrid->SetMargins(0, 0);
// Columns
localPathStateGrid->EnableDragColMove(false);
localPathStateGrid->EnableDragColSize(true);
localPathStateGrid->SetColLabelSize(1);
localPathStateGrid->SetColLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Rows
localPathStateGrid->EnableDragRowSize(true);
localPathStateGrid->SetRowLabelValue(0, wxT("Start:"));
localPathStateGrid->SetRowLabelValue(1, wxT("End:"));
localPathStateGrid->SetRowLabelValue(2, wxT("Direction:"));
localPathStateGrid->SetRowLabelSize(80);
localPathStateGrid->SetRowLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Label Appearance
// Cell Defaults
localPathStateGrid->SetDefaultCellAlignment(wxALIGN_RIGHT, wxALIGN_CENTER);
localPathStateSizer->Add(localPathStateGrid, 0, wxALIGN_CENTER | wxALL, 5);
decisionPlannerOptionsSizer->Add(localPathStateSizer, 1, wxEXPAND, 5);
wxStaticBoxSizer* relativeTargetSizer;
relativeTargetSizer =
new wxStaticBoxSizer(new wxStaticBox(decisionPlannerScrollWindow, wxID_ANY, wxT("Build Target Sequence:")),
wxVERTICAL);
forwardTargetButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_FORWARD_TARGET_BUTTON,
wxT("Forward"),
wxDefaultPosition,
wxDefaultSize,
0);
relativeTargetSizer->Add(forwardTargetButton, 0, wxALIGN_CENTER | wxALL, 5);
wxGridSizer* leftRightTargetSizer;
leftRightTargetSizer = new wxGridSizer(1, 2, 0, 0);
leftTargetButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_LEFT_TARGET_BUTTON,
wxT("Left"),
wxDefaultPosition,
wxDefaultSize,
0);
leftRightTargetSizer->Add(leftTargetButton, 0, wxALIGN_RIGHT | wxALL, 5);
rightTargetButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_RIGHT_TARGET_BUTTON,
wxT("Right"),
wxDefaultPosition,
wxDefaultSize,
0);
leftRightTargetSizer->Add(rightTargetButton, 0, wxALIGN_LEFT | wxALL, 5);
relativeTargetSizer->Add(leftRightTargetSizer, 1, wxEXPAND, 5);
backTargetButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_BACK_TARGET_BUTTON,
wxT("Back"),
wxDefaultPosition,
wxDefaultSize,
0);
relativeTargetSizer->Add(backTargetButton, 0, wxALIGN_CENTER | wxALL, 5);
wxGridSizer* pathTargetSizer;
pathTargetSizer = new wxGridSizer(1, 2, 0, 0);
pathTargetStartButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_PATH_TARGET_START_BUTTON,
wxT("Path Start"),
wxDefaultPosition,
wxDefaultSize,
0);
pathTargetSizer->Add(pathTargetStartButton, 0, wxALIGN_RIGHT | wxALL, 5);
pathTargetEndButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_PATH_TARGET_END_BUTTON,
wxT("Path End"),
wxDefaultPosition,
wxDefaultSize,
0);
pathTargetSizer->Add(pathTargetEndButton, 0, wxALIGN_LEFT | wxALL, 5);
relativeTargetSizer->Add(pathTargetSizer, 1, wxEXPAND, 5);
wxGridSizer* targetSequenceOptionsSizer;
targetSequenceOptionsSizer = new wxGridSizer(2, 3, 0, 0);
removeRelativeTargetButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_REMOVE_RELATIVE_TARGET_BUTTON,
wxT("Remove"),
wxDefaultPosition,
wxDefaultSize,
0);
targetSequenceOptionsSizer->Add(removeRelativeTargetButton, 0, wxALL, 5);
clearRelativeTargetsButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_CLEAR_RELATIVE_TARGETS_BUTTON,
wxT("Clear"),
wxDefaultPosition,
wxDefaultSize,
0);
targetSequenceOptionsSizer->Add(clearRelativeTargetsButton, 0, wxALL, 5);
sendRelativeTargetsButton = new wxButton(relativeTargetSizer->GetStaticBox(),
ID_SEND_RELATIVE_TARGETS_BUTTON,
wxT("Send"),
wxDefaultPosition,
wxDefaultSize,
0);
targetSequenceOptionsSizer->Add(sendRelativeTargetsButton, 0, wxALL, 5);
relativeTargetSizer->Add(targetSequenceOptionsSizer, 1, wxEXPAND, 5);
decisionPlannerOptionsSizer->Add(relativeTargetSizer, 1, wxEXPAND, 5);
decisionPlannerScrollWindow->SetSizer(decisionPlannerOptionsSizer);
decisionPlannerScrollWindow->Layout();
decisionPlannerOptionsSizer->Fit(decisionPlannerScrollWindow);
decisionPlannerPanelSizer->Add(decisionPlannerScrollWindow, 0, wxEXPAND | wxALL, 5);
decisionPlannerPanel->SetSizer(decisionPlannerPanelSizer);
decisionPlannerPanel->Layout();
decisionPlannerPanelSizer->Fit(decisionPlannerPanel);
frameNotebook->AddPage(decisionPlannerPanel, wxT("Decision Planner"), false, wxNullBitmap);
goalPlannerPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
goalPlannerPanel->Enable(false);
goalPlannerPanel->Hide();
wxBoxSizer* goalPlannerPanelSizer;
goalPlannerPanelSizer = new wxBoxSizer(wxHORIZONTAL);
goalPlannerWidget =
new GoalPlannerDisplayWidget(goalPlannerPanel, ID_GOAL_PLANNER_WIDGET, wxDefaultPosition, wxDefaultSize);
goalPlannerPanelSizer->Add(goalPlannerWidget, 1, wxALL | wxEXPAND, 5);
goalPlannerScrollWindow =
new wxScrolledWindow(goalPlannerPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
goalPlannerScrollWindow->SetScrollRate(0, 5);
wxBoxSizer* goalPlannerOptionsSizer;
goalPlannerOptionsSizer = new wxBoxSizer(wxVERTICAL);
wxString mapRepresentationRadioBoxChoices[] = {wxT("Topological"), wxT("Graph")};
int mapRepresentationRadioBoxNChoices = sizeof(mapRepresentationRadioBoxChoices) / sizeof(wxString);
mapRepresentationRadioBox = new wxRadioBox(goalPlannerScrollWindow,
ID_MAP_REPRESENTATION_RADIO_BOX,
wxT("Map Representation"),
wxDefaultPosition,
wxDefaultSize,
mapRepresentationRadioBoxNChoices,
mapRepresentationRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
mapRepresentationRadioBox->SetSelection(0);
goalPlannerOptionsSizer->Add(mapRepresentationRadioBox, 0, wxALL | wxEXPAND, 5);
wxString globalRouteDisplayRadioBoxChoices[] = {wxT("Route"), wxT("Progress")};
int globalRouteDisplayRadioBoxNChoices = sizeof(globalRouteDisplayRadioBoxChoices) / sizeof(wxString);
globalRouteDisplayRadioBox = new wxRadioBox(goalPlannerScrollWindow,
ID_GLOBAL_ROUTE_DISPLAY_RADIO_BOX,
wxT("Route Display"),
wxDefaultPosition,
wxDefaultSize,
globalRouteDisplayRadioBoxNChoices,
globalRouteDisplayRadioBoxChoices,
1,
wxRA_SPECIFY_COLS);
globalRouteDisplayRadioBox->SetSelection(0);
goalPlannerOptionsSizer->Add(globalRouteDisplayRadioBox, 0, wxALL | wxEXPAND, 5);
wxStaticBoxSizer* setLocationSizer;
setLocationSizer =
new wxStaticBoxSizer(new wxStaticBox(goalPlannerScrollWindow, wxID_ANY, wxT("Global Location")), wxHORIZONTAL);
setLocationButton = new wxButton(setLocationSizer->GetStaticBox(),
ID_SET_LOCATION_BUTTON,
wxT("Set"),
wxDefaultPosition,
wxDefaultSize,
0);
setLocationSizer->Add(setLocationButton, 0, wxALL, 5);
sendLocationButton = new wxButton(setLocationSizer->GetStaticBox(),
ID_SEND_LOCATION_BUTTON,
wxT("Send"),
wxDefaultPosition,
wxDefaultSize,
0);
setLocationSizer->Add(sendLocationButton, 0, wxALL, 5);
goalPlannerOptionsSizer->Add(setLocationSizer, 0, 0, 5);
wxStaticBoxSizer* setGoalSizer;
setGoalSizer = new wxStaticBoxSizer(new wxStaticBox(goalPlannerScrollWindow, wxID_ANY, wxT("Goal")), wxHORIZONTAL);
setGoalButton =
new wxButton(setGoalSizer->GetStaticBox(), ID_SET_GOAL_BUTTON, wxT("Set"), wxDefaultPosition, wxDefaultSize, 0);
setGoalSizer->Add(setGoalButton, 0, wxALL, 5);
sendGoalButton =
new wxButton(setGoalSizer->GetStaticBox(), ID_SEND_GOAL_BUTTON, wxT("Send"), wxDefaultPosition, wxDefaultSize, 0);
setGoalSizer->Add(sendGoalButton, 0, wxALL, 5);
goalPlannerOptionsSizer->Add(setGoalSizer, 0, 0, 5);
wxStaticBoxSizer* animateSearchSizer;
animateSearchSizer =
new wxStaticBoxSizer(new wxStaticBox(goalPlannerScrollWindow, wxID_ANY, wxT("Animate Search (FPS)")),
wxHORIZONTAL);
animateFPSText = new wxTextCtrl(animateSearchSizer->GetStaticBox(),
ID_ANIMATE_FPS_TEXT,
wxT("15"),
wxDefaultPosition,
wxDefaultSize,
wxTE_RIGHT);
#ifdef __WXGTK__
if (!animateFPSText->HasFlag(wxTE_MULTILINE)) {
animateFPSText->SetMaxLength(3);
}
#else
animateFPSText->SetMaxLength(3);
#endif
animateSearchSizer->Add(animateFPSText, 0, wxALIGN_CENTER | wxALL, 5);
animateSearchButton = new wxButton(animateSearchSizer->GetStaticBox(),
ID_ANIMATE_SEARCH_BUTTON,
wxT("Animate"),
wxDefaultPosition,
wxDefaultSize,
0);
animateSearchSizer->Add(animateSearchButton, 0, wxALL, 5);
goalPlannerOptionsSizer->Add(animateSearchSizer, 0, 0, 5);
wxStaticBoxSizer* routeControlSizer;
routeControlSizer =
new wxStaticBoxSizer(new wxStaticBox(goalPlannerScrollWindow, wxID_ANY, wxT("Route Commands")), wxHORIZONTAL);
confirmRouteButton = new wxButton(routeControlSizer->GetStaticBox(),
ID_CONFIRM_ROUTE_BUTTON,
wxT("Confirm"),
wxDefaultPosition,
wxDefaultSize,
0);
routeControlSizer->Add(confirmRouteButton, 0, wxALL, 5);
cancelRouteButton = new wxButton(routeControlSizer->GetStaticBox(),
ID_CANCEL_ROUTE_BUTTON,
wxT("Cancel"),
wxDefaultPosition,
wxDefaultSize,
0);
routeControlSizer->Add(cancelRouteButton, 0, wxALL, 5);
goalPlannerOptionsSizer->Add(routeControlSizer, 0, 0, 5);
goalPlannerScrollWindow->SetSizer(goalPlannerOptionsSizer);
goalPlannerScrollWindow->Layout();
goalPlannerOptionsSizer->Fit(goalPlannerScrollWindow);
goalPlannerPanelSizer->Add(goalPlannerScrollWindow, 0, wxEXPAND | wxALL, 5);
goalPlannerPanel->SetSizer(goalPlannerPanelSizer);
goalPlannerPanel->Layout();
goalPlannerPanelSizer->Fit(goalPlannerPanel);
frameNotebook->AddPage(goalPlannerPanel, wxT("Goal Planner"), false, wxNullBitmap);
visionPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer* visionPanelSizer;
visionPanelSizer = new wxBoxSizer(wxHORIZONTAL);
visionWidget = new VisionDisplayWidget(visionPanel, ID_VISION_WIDGET, wxDefaultPosition, wxDefaultSize);
visionWidget->SetMinSize(wxSize(640, 480));
visionPanelSizer->Add(visionWidget, 1, wxALIGN_CENTER | wxALL | wxEXPAND, 5);
wxFlexGridSizer* visionOptionsSizer;
visionOptionsSizer = new wxFlexGridSizer(0, 1, 0, 0);
visionOptionsSizer->SetFlexibleDirection(wxBOTH);
visionOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
wxStaticBoxSizer* imageSegmentationOptionsSizer;
imageSegmentationOptionsSizer =
new wxStaticBoxSizer(new wxStaticBox(visionPanel, wxID_ANY, wxT("Segmentation Options")), wxVERTICAL);
showSegmentsCheckBox = new wxCheckBox(imageSegmentationOptionsSizer->GetStaticBox(),
ID_SHOW_SEGMENTS_BOX,
wxT("Show Segments"),
wxDefaultPosition,
wxDefaultSize,
0);
imageSegmentationOptionsSizer->Add(showSegmentsCheckBox, 0, wxALL, 5);
wxFlexGridSizer* segmentationOptionsSizer;
segmentationOptionsSizer = new wxFlexGridSizer(5, 2, 0, 0);
segmentationOptionsSizer->SetFlexibleDirection(wxVERTICAL);
segmentationOptionsSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);
minEdgeWeightLabel = new wxStaticText(imageSegmentationOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Min Edge Weight:"),
wxDefaultPosition,
wxDefaultSize,
0);
minEdgeWeightLabel->Wrap(-1);
segmentationOptionsSizer->Add(minEdgeWeightLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
minEdgeWeightSlider = new wxSlider(imageSegmentationOptionsSizer->GetStaticBox(),
ID_MIN_EDGE_WEIGHT_SLIDER,
42,
0,
50,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
segmentationOptionsSizer->Add(minEdgeWeightSlider, 1, wxALL | wxEXPAND, 5);
maxEdgeWeightLabel = new wxStaticText(imageSegmentationOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Max Edge Weight:"),
wxDefaultPosition,
wxDefaultSize,
0);
maxEdgeWeightLabel->Wrap(-1);
segmentationOptionsSizer->Add(maxEdgeWeightLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
maxEdgeWeightSlider = new wxSlider(imageSegmentationOptionsSizer->GetStaticBox(),
ID_MAX_EDGE_WEIGHT_SLIDER,
21,
0,
50,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
segmentationOptionsSizer->Add(maxEdgeWeightSlider, 0, wxALL | wxEXPAND, 5);
pixelSigmaLabel = new wxStaticText(imageSegmentationOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Pixel Sigma:"),
wxDefaultPosition,
wxDefaultSize,
0);
pixelSigmaLabel->Wrap(-1);
segmentationOptionsSizer->Add(pixelSigmaLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
pixelSigmaSlider = new wxSlider(imageSegmentationOptionsSizer->GetStaticBox(),
ID_PIXEL_SIGMA_SLIDER,
20,
0,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
segmentationOptionsSizer->Add(pixelSigmaSlider, 0, wxALL | wxEXPAND, 5);
creditMultiplierLabel = new wxStaticText(imageSegmentationOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Credit Multiplier:"),
wxDefaultPosition,
wxDefaultSize,
0);
creditMultiplierLabel->Wrap(-1);
segmentationOptionsSizer->Add(creditMultiplierLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
creditMultiplierSlider = new wxSlider(imageSegmentationOptionsSizer->GetStaticBox(),
ID_CREDIT_MULTIPLIER_SLIDER,
10,
0,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
segmentationOptionsSizer->Add(creditMultiplierSlider, 0, wxALL | wxEXPAND, 5);
filterWidthLabel = new wxStaticText(imageSegmentationOptionsSizer->GetStaticBox(),
wxID_ANY,
wxT("Filter Width:"),
wxDefaultPosition,
wxDefaultSize,
0);
filterWidthLabel->Wrap(-1);
segmentationOptionsSizer->Add(filterWidthLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
filterWidthSlider = new wxSlider(imageSegmentationOptionsSizer->GetStaticBox(),
ID_FILTER_WIDTH_SLIDER,
13,
0,
100,
wxDefaultPosition,
wxDefaultSize,
wxSL_HORIZONTAL | wxSL_LABELS);
segmentationOptionsSizer->Add(filterWidthSlider, 0, wxALL | wxEXPAND, 5);
imageSegmentationOptionsSizer->Add(segmentationOptionsSizer, 1, wxEXPAND, 5);
visionOptionsSizer->Add(imageSegmentationOptionsSizer, 1, wxEXPAND, 5);
visionPanelSizer->Add(visionOptionsSizer, 0, wxALL, 5);
visionPanel->SetSizer(visionPanelSizer);
visionPanel->Layout();
visionPanelSizer->Fit(visionPanel);
frameNotebook->AddPage(visionPanel, wxT("Vision"), false, wxNullBitmap);
systemPanel = new wxPanel(frameNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
systemPanel->Enable(false);
systemPanel->Hide();
wxBoxSizer* systemPanelSizer;
systemPanelSizer = new wxBoxSizer(wxVERTICAL);
moduleStatusGrid = new wxGrid(systemPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
// Grid
moduleStatusGrid->CreateGrid(5, 5);
moduleStatusGrid->EnableEditing(false);
moduleStatusGrid->EnableGridLines(true);
moduleStatusGrid->EnableDragGridSize(false);
moduleStatusGrid->SetMargins(0, 0);
// Columns
moduleStatusGrid->EnableDragColMove(false);
moduleStatusGrid->EnableDragColSize(true);
moduleStatusGrid->SetColLabelSize(30);
moduleStatusGrid->SetColLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Rows
moduleStatusGrid->EnableDragRowSize(true);
moduleStatusGrid->SetRowLabelSize(80);
moduleStatusGrid->SetRowLabelAlignment(wxALIGN_CENTER, wxALIGN_CENTER);
// Label Appearance
// Cell Defaults
moduleStatusGrid->SetDefaultCellAlignment(wxALIGN_LEFT, wxALIGN_TOP);
systemPanelSizer->Add(moduleStatusGrid, 0, wxALL, 5);
systemPanel->SetSizer(systemPanelSizer);
systemPanel->Layout();
systemPanelSizer->Fit(systemPanel);
frameNotebook->AddPage(systemPanel, wxT("System"), false, wxNullBitmap);
debugFrameSizer->Add(frameNotebook, 1, wxEXPAND | wxALL, 5);
this->SetSizer(debugFrameSizer);
this->Layout();
gridCellStatusBar = this->CreateStatusBar(1, wxSTB_SIZEGRIP, ID_GRID_CELL_STATUS_BAR);
debugUIMenu = new wxMenuBar(0);
windowMenu = new wxMenu();
wxMenuItem* localMetricWindowItem;
localMetricWindowItem = new wxMenuItem(windowMenu,
ID_LOCAL_METRIC_WINDOW_ITEM,
wxString(wxT("Local Metric")),
wxT("Display Local Metric HSSH tab"),
wxITEM_CHECK);
windowMenu->Append(localMetricWindowItem);
localMetricWindowItem->Check(true);
wxMenuItem* localTopologyWindowItem;
localTopologyWindowItem = new wxMenuItem(windowMenu,
ID_LOCAL_TOPOLOGY_WINDOW_ITEM,
wxString(wxT("Local Topology")),
wxT("Show Local Topology HSSH tab"),
wxITEM_CHECK);
windowMenu->Append(localTopologyWindowItem);
localTopologyWindowItem->Check(true);
wxMenuItem* globalTopologyWindowItem;
globalTopologyWindowItem = new wxMenuItem(windowMenu,
ID_GLOBAL_TOPOLOGY_WINDOW_ITEM,
wxString(wxT("Global Topology")),
wxT("Show Global Topology HSSH tab"),
wxITEM_CHECK);
windowMenu->Append(globalTopologyWindowItem);
globalTopologyWindowItem->Check(true);
wxMenuItem* relocalizationWindowItem;
relocalizationWindowItem = new wxMenuItem(windowMenu,
ID_RELOCALIZATION_WINDOW_ITEM,
wxString(wxT("Relocalization")),
wxT("Show Relocalization tab"),
wxITEM_CHECK);
windowMenu->Append(relocalizationWindowItem);
relocalizationWindowItem->Check(true);
wxMenuItem* metricPlannerWindowItem;
metricPlannerWindowItem = new wxMenuItem(windowMenu,
ID_METRIC_PLANNER_WINDOW_ITEM,
wxString(wxT("Metric Planner")),
wxT("Show Metric Planner tab"),
wxITEM_CHECK);
windowMenu->Append(metricPlannerWindowItem);
metricPlannerWindowItem->Check(true);
wxMenuItem* decisionPlannerWindowItem;
decisionPlannerWindowItem = new wxMenuItem(windowMenu,
ID_DECISION_PLANNER_WINDOW_ITEM,
wxString(wxT("Decision Planner")),
wxT("Show Decision Planner tab"),
wxITEM_CHECK);
windowMenu->Append(decisionPlannerWindowItem);
decisionPlannerWindowItem->Check(true);
wxMenuItem* goalPlannerWindowItem;
goalPlannerWindowItem = new wxMenuItem(windowMenu,
ID_GOAL_PLANNER_WINDOW_ITEM,
wxString(wxT("Goal Planner")),
wxT("Show Goal Planner tab"),
wxITEM_CHECK);
windowMenu->Append(goalPlannerWindowItem);
goalPlannerWindowItem->Check(true);
wxMenuItem* visionWindowItem;
visionWindowItem =
new wxMenuItem(windowMenu, ID_VISION_WINDOW_ITEM, wxString(wxT("Vision")), wxT("Show Vision tab"), wxITEM_CHECK);
windowMenu->Append(visionWindowItem);
wxMenuItem* systemWindowItem;
systemWindowItem =
new wxMenuItem(windowMenu, ID_SYSTEM_WINDOW_ITEM, wxString(wxT("System")), wxT("Show System tab"), wxITEM_CHECK);
windowMenu->Append(systemWindowItem);
debugUIMenu->Append(windowMenu, wxT("Window"));
this->SetMenuBar(debugUIMenu);
this->Centre(wxBOTH);
// Connect Events
numTrajectoriesText->Connect(wxEVT_COMMAND_TEXT_UPDATED,
wxCommandEventHandler(DebugFrame::numTrajectoriesTextOnText),
NULL,
this);
}
DebugFrame::~DebugFrame()
{
// Disconnect Events
numTrajectoriesText->Disconnect(wxEVT_COMMAND_TEXT_UPDATED,
wxCommandEventHandler(DebugFrame::numTrajectoriesTextOnText),
NULL,
this);
}
| 51.819121 | 120 | 0.536711 | [
"object"
] |
4241011e3869f31f85a8c3bebbb199668c6f0146 | 10,719 | cpp | C++ | admin/snapin/wsecmgr/precpage.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/snapin/wsecmgr/precpage.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/snapin/wsecmgr/precpage.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation 1996-2001.
//
// File: precpage.cpp
//
// Contents: implementation of CPrecedencePage
//
//----------------------------------------------------------------------------
#include "stdafx.h"
#include <secedit.h>
#include "wsecmgr.h"
#include "precpage.h"
#include "snapmgr.h"
#include "util.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define PRECEDENCE_STATUS_SUCCESS 1
#define PRECEDENCE_STATUS_NO_CONFIG 0
#define PRECEDENCE_STATUS_INVALID 2
#define PRECEDENCE_STATUS_ERROR 3
#define PRECEDENCE_STATUS_CHILD_ERROR 4
/////////////////////////////////////////////////////////////////////////////
// CPrecedencePage property page
IMPLEMENT_DYNCREATE(CPrecedencePage, CSelfDeletingPropertyPage)
CPrecedencePage::CPrecedencePage() : CSelfDeletingPropertyPage(IDD)
{
//{{AFX_DATA_INIT(CPrecedencePage)
m_strSuccess = _T("");
m_strTitle = _T("");
m_strError = _T("");
//}}AFX_DATA_INIT
m_pResult = NULL;
m_pWMI = NULL;
m_pHelpIDs = (DWORD_PTR)a239HelpIDs;
}
CPrecedencePage::~CPrecedencePage()
{
}
void CPrecedencePage::DoDataExchange(CDataExchange* pDX)
{
CSelfDeletingPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPrecedencePage)
DDX_Control(pDX, IDC_PRECEDENCE_LIST, m_PrecedenceList);
DDX_Control(pDX, IDC_ERROR_ICON, m_iconError);
DDX_Text(pDX, IDC_SUCCESS_TEXT, m_strSuccess);
DDX_Text(pDX, IDC_TITLE, m_strTitle);
DDX_Text(pDX, IDC_ERROR_TEXT, m_strError);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPrecedencePage, CSelfDeletingPropertyPage)
//{{AFX_MSG_MAP(CPrecedencePage)
//}}AFX_MSG_MAP
ON_MESSAGE(WM_HELP, OnHelp)
ON_MESSAGE(WM_CONTEXTMENU, OnContextHelp) //Bug 139470, 4/19/2001
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPrecedencePage message handlers
BOOL CPrecedencePage::OnInitDialog()
{
CSelfDeletingPropertyPage::OnInitDialog();
CString strColumn;
#define COL_WIDTH 200
strColumn.LoadString(IDS_PRECEDENCE_GPO_HEADER);
m_PrecedenceList.InsertColumn(0,strColumn,LVCFMT_LEFT,COL_WIDTH,0);
switch(m_pResult->GetType())
{
case ITEM_PROF_GROUP:
//
// Two value columns for groups
//
strColumn.LoadString(IDS_COL_MEMBERSHIP);
m_PrecedenceList.InsertColumn(1,strColumn,LVCFMT_LEFT,COL_WIDTH,1);
strColumn.LoadString(IDS_COL_MEMBEROF);
m_PrecedenceList.InsertColumn(2,strColumn,LVCFMT_LEFT,COL_WIDTH,1);
break;
case ITEM_PROF_REGSD:
case ITEM_PROF_FILESD:
case ITEM_PROF_SERV:
//
// No value columns for files, reg keys, or services
//
break;
default:
//
// One value column for everything else
//
strColumn.LoadString(IDS_PRECEDENCE_VALUE_HEADER);
m_PrecedenceList.InsertColumn(1,strColumn,LVCFMT_LEFT,COL_WIDTH,1);
break;
}
vector<PPRECEDENCEDISPLAY>* pvecDisplay = m_pResult->GetPrecedenceDisplays();
ASSERT(pvecDisplay);
if (!pvecDisplay || pvecDisplay->empty())
{
return TRUE;
}
int nItem = 0;
for(vector<PPRECEDENCEDISPLAY>::iterator i = pvecDisplay->begin();
i != pvecDisplay->end();
++i )
{
PPRECEDENCEDISPLAY ppd = *i;
if ( ppd->m_szGPO.IsEmpty ())
{
ASSERT(!ppd->m_szGPO.IsEmpty ());
continue;
}
//
// CListCtrl will make a copy of the string passed in so
// there is no point allocating buffer
// (and not free it)
//
nItem = m_PrecedenceList.InsertItem (nItem,
(PCWSTR) ppd->m_szGPO);
if (nItem != -1)
{
if ( !ppd->m_szValue.IsEmpty () )
{
m_PrecedenceList.SetItem(nItem,
1,
LVIF_TEXT,
(PCWSTR) ppd->m_szValue,
0,
0,
0,
0);
}
if ( !ppd->m_szValue2.IsEmpty () )
{
m_PrecedenceList.SetItem(nItem,
2,
LVIF_TEXT,
(PCWSTR) ppd->m_szValue2,
0,
0,
0,
0);
}
}
nItem++;
}
vector<PPRECEDENCEDISPLAY>::reference ppd = pvecDisplay->front();
if (ppd)
{
if (ppd->m_uStatus == PRECEDENCE_STATUS_SUCCESS)
{
GetDlgItem(IDC_ERROR_TEXT)->SetWindowPos(NULL,0,0,0,0,SWP_HIDEWINDOW|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER);
GetDlgItem(IDC_ERROR_ICON)->SetWindowPos(NULL,0,0,0,0,SWP_HIDEWINDOW|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER);
}
else
{
GetDlgItem(IDC_SUCCESS_TEXT)->SetWindowPos(NULL,0,0,0,0,SWP_HIDEWINDOW|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER);
}
CImageList il;
HICON icon = NULL;
il.Create(IDB_ICON16,16,1,RGB(255,0,255));
if (ppd->m_uStatus != PRECEDENCE_STATUS_SUCCESS)
{
icon = m_iconError.SetIcon(il.ExtractIcon(SCE_CRITICAL_IDX));
if (icon)
{
DestroyIcon(icon);
}
}
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CPrecedencePage::Initialize(CResult *pResult, CWMIRsop *pWMI)
{
m_pResult = pResult;
m_pWMI = pWMI;
vector<PPRECEDENCEDISPLAY>* pvecDisplay = m_pResult->GetPrecedenceDisplays();
ASSERT(pvecDisplay);
if (pvecDisplay && !pvecDisplay->empty())
{
vector<PPRECEDENCEDISPLAY>::reference ppd = pvecDisplay->front();
if (ppd)
{
switch (ppd->m_uStatus)
{
case PRECEDENCE_STATUS_NO_CONFIG:
m_strError.LoadString(IDS_PRECEDENCE_NO_CONFIG);
break;
case PRECEDENCE_STATUS_INVALID:
AfxFormatString1 (m_strError, IDS_PRECEDENCE_INVALID,
(PCWSTR) ppd->m_szGPO);
break;
case PRECEDENCE_STATUS_ERROR:
{
CString strErr;
if (SCESTATUS_SUCCESS != FormatDBErrorMessage (ppd->m_uError,
NULL, strErr))
{
strErr.LoadString(IDS_UNKNOWN_ERROR);
}
AfxFormatString2 (m_strError, IDS_PRECEDENCE_ERROR,
(PCWSTR) ppd->m_szGPO, strErr);
}
break;
case PRECEDENCE_STATUS_SUCCESS:
AfxFormatString1 (m_strSuccess, IDS_PRECEDENCE_SUCCESS,
(PCWSTR) ppd->m_szGPO);
break;
case PRECEDENCE_STATUS_CHILD_ERROR:
m_strError.LoadString(IDS_PRECEDENCE_CHILD_ERROR);
break;
default:
break;
}
}
}
}
BOOL CPrecedencePage::OnHelp(WPARAM wParam, LPARAM lParam) //Bug 316461, Yanggao, 3/14/2001
{
const LPHELPINFO pHelpInfo = (LPHELPINFO)lParam;
if (pHelpInfo && pHelpInfo->iContextType == HELPINFO_WINDOW)
{
if(pHelpInfo->iCtrlId != -1)
this->DoContextHelp ((HWND) pHelpInfo->hItemHandle);
}
return TRUE;
}
void CPrecedencePage::DoContextHelp(HWND hWndControl) //Bug 316461, Yanggao, 3/14/2001
{
// Display context help for a control
if ( !::WinHelp (
hWndControl,
GetGpeditHelpFilename(),
HELP_WM_HELP,
m_pHelpIDs))
{
}
}
BOOL CPrecedencePage::OnContextHelp(WPARAM wParam, LPARAM lParam)
{
HMENU hMenu = CreatePopupMenu();
if( hMenu )
{
CString str;
str.LoadString(IDS_WHAT_ISTHIS);
if( AppendMenu(hMenu, MF_STRING, IDM_WHAT_ISTHIS, str) )
{
int itemID = TrackPopupMenu(hMenu,
TPM_LEFTALIGN|TPM_TOPALIGN|TPM_RETURNCMD|
TPM_LEFTBUTTON|TPM_RIGHTBUTTON,
LOWORD(lParam), HIWORD(lParam), 0, (HWND)wParam, NULL);
if( itemID == IDM_WHAT_ISTHIS ) //Raid #139470, 4/11/2001
{
if( ((HWND)wParam) != this->m_hWnd )
{
::WinHelp((HWND)wParam,
GetGpeditHelpFilename(),
HELP_WM_HELP,
m_pHelpIDs);
}
else
{
POINT pos;
pos.x = LOWORD(lParam);
pos.y = HIWORD(lParam);
ScreenToClient( &pos );
CWnd* pWnd = ChildWindowFromPoint(pos, CWP_SKIPINVISIBLE);
if( pWnd )
{
::WinHelp(pWnd->m_hWnd,
GetGpeditHelpFilename(),
HELP_WM_HELP,
m_pHelpIDs);
}
else
{
::WinHelp((HWND)wParam,
GetGpeditHelpFilename(),
HELP_WM_HELP,
m_pHelpIDs);
}
}
}
}
}
return TRUE;
}
//********************************************************************
//Get the image icon for the result item, based on where the status of
//RSOP result item.
//********************************************************************
int GetRSOPImageIndex(int nImage, CResult* pResult)
{
if ( !pResult )
{
return nImage;
}
vector<PPRECEDENCEDISPLAY>* vppd = pResult->GetPrecedenceDisplays();
if (vppd && !vppd->empty())
{
PPRECEDENCEDISPLAY ppd = vppd->front();
if( ppd && ppd->m_uStatus != PRECEDENCE_STATUS_SUCCESS )
{
return SCE_CRITICAL_IDX;
}
}
return nImage;
}
| 30.109551 | 117 | 0.506391 | [
"vector"
] |
4242fdeebc18094efb6c9685e8cd78f632eb9026 | 766 | cpp | C++ | cpp/algorithm_move.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/algorithm_move.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/algorithm_move.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | /*
g++ --std=c++20 -pthread -o ../_build/cpp/algorithm_move.exe ./cpp/algorithm_move.cpp && (cd ../_build/cpp/;./algorithm_move.exe)
https://en.cppreference.com/w/cpp/algorithm/move
*/
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <thread>
#include <chrono>
void f(int n)
{
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "thread " << n << " ended" << std::endl;
}
int main()
{
std::vector<std::thread> v;
v.emplace_back(f, 1);
v.emplace_back(f, 2);
v.emplace_back(f, 3);
std::list<std::thread> l;
// copy() would not compile, because std::thread is noncopyable
std::move(v.begin(), v.end(), std::back_inserter(l));
for (auto& t : l) t.join();
}
| 26.413793 | 129 | 0.630548 | [
"vector"
] |
4246cd9bbfa899fd9c3671ab5d766f9cedf59f39 | 344 | cpp | C++ | LeetCode/CoinChange.cpp | sawantaditi24/Competitive-Programming | 36e024215d8041c92c5ec78a22561aaa0025f8d2 | [
"MIT"
] | 2 | 2019-08-27T21:48:55.000Z | 2020-04-20T05:56:56.000Z | LeetCode/CoinChange.cpp | gauravsingh58/competitive-programming | fa5548f435cdf2aa059e1d6ab733885790c6a592 | [
"MIT"
] | 1 | 2020-10-10T16:14:54.000Z | 2020-10-10T16:14:54.000Z | LeetCode/CoinChange.cpp | gauravsingh58/competitive-programming | fa5548f435cdf2aa059e1d6ab733885790c6a592 | [
"MIT"
] | 2 | 2020-10-21T17:12:05.000Z | 2020-10-27T09:34:57.000Z | class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(auto coin : coins) {
if(coin <= i) {
dp[i] = min(dp[i], dp[i-coin] + 1);
}
}
}
if(dp[amount] > amount)
return -1;
return dp[amount];
}
}; | 20.235294 | 52 | 0.514535 | [
"vector"
] |
424ae6d0ceab2b725949c3b3618fe46743cca6f9 | 27,614 | cpp | C++ | src/custom_nodes/model_zoo_intel_object_detection/model_zoo_intel_object_detection.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 305 | 2018-10-01T12:41:28.000Z | 2020-04-24T10:36:08.000Z | src/custom_nodes/model_zoo_intel_object_detection/model_zoo_intel_object_detection.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 61 | 2018-11-15T09:23:01.000Z | 2020-04-23T09:29:56.000Z | src/custom_nodes/model_zoo_intel_object_detection/model_zoo_intel_object_detection.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 67 | 2018-10-13T14:33:48.000Z | 2020-04-22T19:01:32.000Z | //*****************************************************************************
// Copyright 2021 Intel Corporation
//
// 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 <iostream>
#include <shared_mutex>
#include <string>
#include <vector>
#include "../../custom_node_interface.h"
#include "../common/custom_node_library_internal_manager.hpp"
#include "../common/opencv_utils.hpp"
#include "../common/utils.hpp"
#include "opencv2/opencv.hpp"
using CustomNodeLibraryInternalManager = ovms::custom_nodes_common::CustomNodeLibraryInternalManager;
static constexpr const char* INPUT_IMAGE_TENSOR_NAME = "image";
static constexpr const char* INPUT_DETECTION_TENSOR_NAME = "detection";
static constexpr const char* INPUT_TENSOR_INFO_NAME = "input_info";
static constexpr const char* INPUT_IMAGE_INFO_DIMS_NAME = "image_info_dims";
static constexpr const char* INPUT_DETECTION_INFO_DIMS_NAME = "detection_info_dims";
static constexpr const char* OUTPUT_TENSOR_NAME = "output";
static constexpr const char* OUTPUT_IMAGES_TENSOR_NAME = "images";
static constexpr const char* OUTPUT_COORDINATES_TENSOR_NAME = "coordinates";
static constexpr const char* OUTPUT_CONFIDENCES_TENSOR_NAME = "confidences";
static constexpr const char* OUTPUT_LABEL_IDS_TENSOR_NAME = "label_ids";
static constexpr const char* OUTPUT_IMAGES_DIMS_NAME = "images_dims";
static constexpr const char* OUTPUT_COORDINATES_DIMS_NAME = "coordinates_dims";
static constexpr const char* OUTPUT_CONFIDENCES_DIMS_NAME = "confidences_dims";
static constexpr const char* OUTPUT_LABEL_IDS_DIMS_NAME = "label_ids_dims";
static constexpr const char* OUTPUT_TENSOR_INFO_NAME = "output_info";
static constexpr const char* OUTPUT_COORDINATES_INFO_DIMS_NAME = "coordinates_info_dims";
static constexpr const char* OUTPUT_IMAGES_INFO_DIMS_NAME = "images_info_dims";
static constexpr const char* OUTPUT_CONFIDENCES_INFO_DIMS_NAME = "confidences_info_dims";
static constexpr const char* OUTPUT_LABEL_IDS_INFO_DIMS_NAME = "label_ids_info_dims";
bool copy_images_into_output(struct CustomNodeTensor* output, const std::vector<cv::Rect>& boxes, const cv::Mat& originalImage, int targetImageHeight, int targetImageWidth, const std::string& targetImageLayout, bool convertToGrayScale, CustomNodeLibraryInternalManager* internalManager) {
const uint64_t outputBatch = boxes.size();
int channels = convertToGrayScale ? 1 : 3;
uint64_t byteSize = sizeof(float) * targetImageHeight * targetImageWidth * channels * outputBatch;
float* buffer = nullptr;
if (!get_buffer<float>(internalManager, &buffer, OUTPUT_IMAGES_TENSOR_NAME, byteSize))
return false;
cv::Size targetShape(targetImageWidth, targetImageHeight);
for (uint64_t i = 0; i < outputBatch; i++) {
cv::Mat image;
if (!crop_rotate_resize(originalImage, image, boxes[i], 0.0, boxes[i].width, boxes[i].height, targetShape)) {
std::cout << "box is outside of original image" << std::endl;
release(buffer, internalManager);
return false;
}
if (convertToGrayScale) {
image = apply_grayscale(image);
}
if (targetImageLayout == "NCHW") {
auto imgBuffer = reorder_to_nchw((float*)image.data, image.rows, image.cols, image.channels());
std::memcpy(buffer + (i * channels * targetImageWidth * targetImageHeight), imgBuffer.data(), byteSize / outputBatch);
} else {
std::memcpy(buffer + (i * channels * targetImageWidth * targetImageHeight), image.data, byteSize / outputBatch);
}
}
output->data = reinterpret_cast<uint8_t*>(buffer);
output->dataBytes = byteSize;
output->dimsCount = 5;
if (!get_buffer<uint64_t>(internalManager, &(output->dims), OUTPUT_IMAGES_DIMS_NAME, output->dimsCount * sizeof(uint64_t))) {
release(buffer, internalManager);
return false;
}
output->dims[0] = outputBatch;
output->dims[1] = 1;
if (targetImageLayout == "NCHW") {
output->dims[2] = channels;
output->dims[3] = targetImageHeight;
output->dims[4] = targetImageWidth;
} else {
output->dims[2] = targetImageHeight;
output->dims[3] = targetImageWidth;
output->dims[4] = channels;
}
output->precision = FP32;
return true;
}
bool copy_coordinates_into_output(struct CustomNodeTensor* output, const std::vector<cv::Vec4f>& detections, CustomNodeLibraryInternalManager* internalManager) {
const uint64_t outputBatch = detections.size();
uint64_t byteSize = sizeof(int32_t) * 4 * outputBatch;
int32_t* buffer = nullptr;
if (!get_buffer<int32_t>(internalManager, &buffer, OUTPUT_COORDINATES_TENSOR_NAME, byteSize))
return false;
for (size_t i = 0; i < outputBatch; i++) {
float entry[] = {
detections[i][0], detections[i][1], detections[i][2], detections[i][3]};
std::memcpy(buffer + (i * 4), entry, byteSize / outputBatch);
}
output->data = reinterpret_cast<uint8_t*>(buffer);
output->dataBytes = byteSize;
output->dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &(output->dims), OUTPUT_COORDINATES_DIMS_NAME, output->dimsCount * sizeof(uint64_t))) {
release(buffer, internalManager);
return false;
}
output->dims[0] = outputBatch;
output->dims[1] = 1;
output->dims[2] = 4;
output->precision = FP32;
return true;
}
bool copy_confidences_into_output(struct CustomNodeTensor* output, const std::vector<float>& confidences, CustomNodeLibraryInternalManager* internalManager) {
const uint64_t outputBatch = confidences.size();
uint64_t byteSize = sizeof(float) * outputBatch;
float* buffer = nullptr;
if (!get_buffer<float>(internalManager, &buffer, OUTPUT_CONFIDENCES_TENSOR_NAME, byteSize))
return false;
std::memcpy(buffer, confidences.data(), byteSize);
output->data = reinterpret_cast<uint8_t*>(buffer);
output->dataBytes = byteSize;
output->dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &(output->dims), OUTPUT_CONFIDENCES_DIMS_NAME, output->dimsCount * sizeof(uint64_t))) {
release(buffer, internalManager);
return false;
}
output->dims[0] = outputBatch;
output->dims[1] = 1;
output->dims[2] = 1;
output->precision = FP32;
return true;
}
bool copy_label_ids_into_output(struct CustomNodeTensor* output, const std::vector<int>& labelIds, CustomNodeLibraryInternalManager* internalManager) {
const uint64_t outputBatch = labelIds.size();
uint64_t byteSize = sizeof(int32_t) * outputBatch;
int32_t* buffer = nullptr;
if (!get_buffer<int32_t>(internalManager, &buffer, OUTPUT_LABEL_IDS_TENSOR_NAME, byteSize))
return false;
std::memcpy(buffer, labelIds.data(), byteSize);
output->data = reinterpret_cast<uint8_t*>(buffer);
output->dataBytes = byteSize;
output->dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &(output->dims), OUTPUT_LABEL_IDS_DIMS_NAME, output->dimsCount * sizeof(uint64_t))) {
release(buffer, internalManager);
return false;
}
output->dims[0] = outputBatch;
output->dims[1] = 1;
output->dims[2] = 1;
output->precision = I32;
return true;
}
int initialize(void** customNodeLibraryInternalManager, const struct CustomNodeParam* params, int paramsCount) {
// creating InternalManager instance
std::unique_ptr<CustomNodeLibraryInternalManager> internalManager = std::make_unique<CustomNodeLibraryInternalManager>();
NODE_ASSERT(internalManager != nullptr, "internalManager allocation failed");
// reading parameters to determine size of pre-allocated buffers
uint64_t maxOutputBatch = get_int_parameter("max_output_batch", params, paramsCount, 100);
NODE_ASSERT(maxOutputBatch > 0, "max output batch must be larger than 0");
bool convertToGrayScale = get_string_parameter("convert_to_gray_scale", params, paramsCount) == "true";
int targetImageHeight = get_int_parameter("target_image_height", params, paramsCount, -1);
int targetImageWidth = get_int_parameter("target_image_width", params, paramsCount, -1);
NODE_ASSERT(targetImageHeight > 0, "target image height must be larger than 0");
NODE_ASSERT(targetImageWidth > 0, "target image width must be larger than 0");
const int queueSize = get_int_parameter("buffer_queue_size", params, paramsCount, 24);
NODE_ASSERT(queueSize > 0, "buffer queue size must be larger than 0");
// creating BuffersQueues for output tensor
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_TENSOR_NAME, 4 * sizeof(CustomNodeTensor), queueSize), "buffer creation failed");
// creating BuffersQueues for output: images
int channels = convertToGrayScale ? 1 : 3;
uint64_t imagesByteSize = sizeof(float) * targetImageHeight * targetImageWidth * channels * maxOutputBatch;
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_IMAGES_TENSOR_NAME, imagesByteSize, queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_IMAGES_DIMS_NAME, 5 * sizeof(uint64_t), queueSize), "buffer creation failed");
// creating BuffersQueues for output: coordinates
uint64_t coordinatesByteSize = sizeof(int32_t) * 4 * maxOutputBatch;
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_COORDINATES_TENSOR_NAME, coordinatesByteSize, queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_COORDINATES_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
// creating BuffersQueues for output: confidences
uint64_t confidenceByteSize = sizeof(float) * maxOutputBatch;
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_CONFIDENCES_TENSOR_NAME, confidenceByteSize, queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_CONFIDENCES_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
// creating BuffersQueues for output: label_ids
uint64_t labelIdsByteSize = sizeof(int32_t) * maxOutputBatch;
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_LABEL_IDS_TENSOR_NAME, labelIdsByteSize, queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_LABEL_IDS_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
// creating BuffersQueues for info tensors
NODE_ASSERT(internalManager->createBuffersQueue(INPUT_TENSOR_INFO_NAME, 2 * sizeof(CustomNodeTensorInfo), queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_TENSOR_INFO_NAME, 4 * sizeof(CustomNodeTensorInfo), queueSize), "buffer creation failed");
// creating BuffersQueues for inputs dims in getInputsInfo
NODE_ASSERT(internalManager->createBuffersQueue(INPUT_IMAGE_INFO_DIMS_NAME, 4 * sizeof(uint64_t), queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(INPUT_DETECTION_INFO_DIMS_NAME, 4 * sizeof(uint64_t), queueSize), "buffer creation failed");
// creating BuffersQueues for outputs dims in getOutputsInfo
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_IMAGES_INFO_DIMS_NAME, 5 * sizeof(uint64_t), queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_COORDINATES_INFO_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_CONFIDENCES_INFO_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
NODE_ASSERT(internalManager->createBuffersQueue(OUTPUT_LABEL_IDS_INFO_DIMS_NAME, 3 * sizeof(uint64_t), queueSize), "buffer creation failed");
*customNodeLibraryInternalManager = internalManager.release();
return 0;
}
int deinitialize(void* customNodeLibraryInternalManager) {
// deallocate InternalManager and its contents
if (customNodeLibraryInternalManager != nullptr) {
CustomNodeLibraryInternalManager* internalManager = static_cast<CustomNodeLibraryInternalManager*>(customNodeLibraryInternalManager);
delete internalManager;
}
return 0;
}
int execute(const struct CustomNodeTensor* inputs, int inputsCount, struct CustomNodeTensor** outputs, int* outputsCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
// Parameters reading
int originalImageHeight = get_int_parameter("original_image_height", params, paramsCount, -1);
int originalImageWidth = get_int_parameter("original_image_width", params, paramsCount, -1);
NODE_ASSERT(originalImageHeight > 0, "original image height must be larger than 0");
NODE_ASSERT(originalImageWidth > 0, "original image width must be larger than 0");
int targetImageHeight = get_int_parameter("target_image_height", params, paramsCount, -1);
int targetImageWidth = get_int_parameter("target_image_width", params, paramsCount, -1);
NODE_ASSERT(targetImageHeight > 0, "target image height must be larger than 0");
NODE_ASSERT(targetImageWidth > 0, "target image width must be larger than 0");
std::string originalImageLayout = get_string_parameter("original_image_layout", params, paramsCount, "NCHW");
NODE_ASSERT(originalImageLayout == "NCHW" || originalImageLayout == "NHWC", "original image layout must be NCHW or NHWC");
std::string targetImageLayout = get_string_parameter("target_image_layout", params, paramsCount, "NCHW");
NODE_ASSERT(targetImageLayout == "NCHW" || targetImageLayout == "NHWC", "target image layout must be NCHW or NHWC");
bool convertToGrayScale = get_string_parameter("convert_to_gray_scale", params, paramsCount) == "true";
float confidenceThreshold = get_float_parameter("confidence_threshold", params, paramsCount, -1.0);
NODE_ASSERT(confidenceThreshold >= 0 && confidenceThreshold <= 1.0, "confidence threshold must be in 0-1 range");
uint64_t maxOutputBatch = get_int_parameter("max_output_batch", params, paramsCount, 100);
NODE_ASSERT(maxOutputBatch > 0, "max output batch must be larger than 0");
int filterLabelId = get_int_parameter("filter_label_id", params, paramsCount, -1);
bool debugMode = get_string_parameter("debug", params, paramsCount) == "true";
const CustomNodeTensor* imageTensor = nullptr;
const CustomNodeTensor* detectionTensor = nullptr;
for (int i = 0; i < inputsCount; i++) {
if (std::strcmp(inputs[i].name, INPUT_IMAGE_TENSOR_NAME) == 0) {
imageTensor = &(inputs[i]);
} else if (std::strcmp(inputs[i].name, INPUT_DETECTION_TENSOR_NAME) == 0) {
detectionTensor = &(inputs[i]);
} else {
std::cout << "Unrecognized input: " << inputs[i].name << std::endl;
return 1;
}
}
NODE_ASSERT(imageTensor != nullptr, "Missing input image");
NODE_ASSERT(detectionTensor != nullptr, "Missing input scores");
NODE_ASSERT(imageTensor->precision == FP32, "image input is not FP32");
NODE_ASSERT(detectionTensor->precision == FP32, "image input is not FP32");
NODE_ASSERT(imageTensor->dimsCount == 4, "input image shape must have 4 dimensions");
NODE_ASSERT(imageTensor->dims[0] == 1, "input image batch must be 1");
NODE_ASSERT(imageTensor->dims[originalImageLayout == "NCHW" ? 1 : 3] == 3, "input image needs to have 3 color channels");
NODE_ASSERT(detectionTensor->dimsCount == 4, "input detection shape must have 4 dimensions");
NODE_ASSERT(detectionTensor->dims[0] == 1, "input detection dim[0] must be 1");
NODE_ASSERT(detectionTensor->dims[1] == 1, "input detection dim[1] must be 1");
NODE_ASSERT(detectionTensor->dims[2] == 200, "input detection dim[2] must be 200");
NODE_ASSERT(detectionTensor->dims[3] == 7, "input detection dim[3] must be 7");
uint64_t _imageHeight = imageTensor->dims[originalImageLayout == "NCHW" ? 2 : 1];
uint64_t _imageWidth = imageTensor->dims[originalImageLayout == "NCHW" ? 3 : 2];
NODE_ASSERT(_imageHeight <= std::numeric_limits<int>::max(), "image height is too large");
NODE_ASSERT(_imageWidth <= std::numeric_limits<int>::max(), "image width is too large");
int imageHeight = static_cast<int>(_imageHeight);
int imageWidth = static_cast<int>(_imageWidth);
if (debugMode) {
std::cout << "Processing input tensor image resolution: " << cv::Size(imageHeight, imageWidth) << "; expected resolution: " << cv::Size(originalImageHeight, originalImageWidth) << std::endl;
}
NODE_ASSERT(imageHeight == originalImageHeight, "original image size parameter differs from original image tensor size");
NODE_ASSERT(imageWidth == originalImageWidth, "original image size parameter differs from original image tensor size");
cv::Mat image;
if (originalImageLayout == "NHWC") {
image = nhwc_to_mat(imageTensor);
} else {
image = nchw_to_mat(imageTensor);
}
NODE_ASSERT(image.cols == imageWidth, "Mat generation failed");
NODE_ASSERT(image.rows == imageHeight, "Mat generation failed");
uint64_t detectionsCount = detectionTensor->dims[2];
uint64_t featuresCount = detectionTensor->dims[3];
std::vector<cv::Rect> boxes;
std::vector<cv::Vec4f> detections;
std::vector<float> confidences;
std::vector<int> labelIds;
for (uint64_t i = 0; i < detectionsCount; i++) {
float* detection = (float*)(detectionTensor->data + (i * featuresCount * sizeof(float)));
int imageId = static_cast<int>(detection[0]);
int labelId = static_cast<int>(detection[1]);
float confidence = detection[2];
int xMin = static_cast<int>(detection[3] * imageWidth);
int yMin = static_cast<int>(detection[4] * imageHeight);
int xMax = static_cast<int>(detection[5] * imageWidth);
int yMax = static_cast<int>(detection[6] * imageHeight);
if (imageId == 0 && confidence >= confidenceThreshold) {
if (filterLabelId != -1 && filterLabelId != labelId) {
if (debugMode) {
std::cout << "Skipping label ID: " << labelId << std::endl;
}
continue;
}
auto box = cv::Rect(cv::Point(xMin, yMin), cv::Point(xMax, yMax));
boxes.emplace_back(box);
detections.emplace_back(detection[3], detection[4], detection[5], detection[6]);
confidences.emplace_back(confidence);
labelIds.emplace_back(labelId);
if (debugMode) {
std::cout << "Detection:\nImageID: " << imageId << "; LabelID:" << labelId << "; Confidence:" << confidence << "; Box:" << box << std::endl;
}
}
}
NODE_ASSERT(boxes.size() == confidences.size(), "boxes and confidences are not equal length");
if (boxes.size() > maxOutputBatch) {
boxes.resize(maxOutputBatch);
confidences.resize(maxOutputBatch);
}
CustomNodeLibraryInternalManager* internalManager = static_cast<CustomNodeLibraryInternalManager*>(customNodeLibraryInternalManager);
std::shared_lock lock(internalManager->getInternalManagerLock());
*outputsCount = 4;
if (!get_buffer<struct CustomNodeTensor>(internalManager, outputs, OUTPUT_TENSOR_NAME, *outputsCount * sizeof(CustomNodeTensor))) {
return 1;
}
CustomNodeTensor& imagesTensor = (*outputs)[0];
imagesTensor.name = OUTPUT_IMAGES_TENSOR_NAME;
if (!copy_images_into_output(&imagesTensor, boxes, image, targetImageHeight, targetImageWidth, targetImageLayout, convertToGrayScale, internalManager)) {
release(*outputs, internalManager);
return 1;
}
CustomNodeTensor& coordinatesTensor = (*outputs)[1];
coordinatesTensor.name = OUTPUT_COORDINATES_TENSOR_NAME;
if (!copy_coordinates_into_output(&coordinatesTensor, detections, internalManager)) {
cleanup(imagesTensor, internalManager);
release(*outputs, internalManager);
return 1;
}
CustomNodeTensor& confidencesTensor = (*outputs)[2];
confidencesTensor.name = OUTPUT_CONFIDENCES_TENSOR_NAME;
if (!copy_confidences_into_output(&confidencesTensor, confidences, internalManager)) {
cleanup(coordinatesTensor, internalManager);
cleanup(imagesTensor, internalManager);
release(*outputs, internalManager);
return 1;
}
CustomNodeTensor& labelIdsTensor = (*outputs)[3];
labelIdsTensor.name = OUTPUT_LABEL_IDS_TENSOR_NAME;
if (!copy_label_ids_into_output(&labelIdsTensor, labelIds, internalManager)) {
cleanup(confidencesTensor, internalManager);
cleanup(coordinatesTensor, internalManager);
cleanup(imagesTensor, internalManager);
release(*outputs, internalManager);
return 1;
}
return 0;
}
int getInputsInfo(struct CustomNodeTensorInfo** info, int* infoCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
int originalImageHeight = get_int_parameter("original_image_height", params, paramsCount, -1);
int originalImageWidth = get_int_parameter("original_image_width", params, paramsCount, -1);
NODE_ASSERT(originalImageHeight > 0, "original image height must be larger than 0");
NODE_ASSERT(originalImageWidth > 0, "original image width must be larger than 0");
std::string originalImageLayout = get_string_parameter("original_image_layout", params, paramsCount, "NCHW");
NODE_ASSERT(originalImageLayout == "NCHW" || originalImageLayout == "NHWC", "original image layout must be NCHW or NHWC");
CustomNodeLibraryInternalManager* internalManager = static_cast<CustomNodeLibraryInternalManager*>(customNodeLibraryInternalManager);
std::shared_lock lock(internalManager->getInternalManagerLock());
*infoCount = 2;
if (!get_buffer<struct CustomNodeTensorInfo>(internalManager, info, INPUT_TENSOR_INFO_NAME, *infoCount * sizeof(CustomNodeTensorInfo))) {
return 1;
}
(*info)[0].name = INPUT_IMAGE_TENSOR_NAME;
(*info)[0].dimsCount = 4;
if (!get_buffer<uint64_t>(internalManager, &((*info)[0].dims), INPUT_IMAGE_INFO_DIMS_NAME, (*info)[0].dimsCount * sizeof(uint64_t))) {
release(*info, internalManager);
return 1;
}
(*info)[0].dims[0] = 1;
if (originalImageLayout == "NCHW") {
(*info)[0].dims[1] = 3;
(*info)[0].dims[2] = originalImageHeight;
(*info)[0].dims[3] = originalImageWidth;
} else {
(*info)[0].dims[1] = originalImageHeight;
(*info)[0].dims[2] = originalImageWidth;
(*info)[0].dims[3] = 3;
}
(*info)[0].precision = FP32;
(*info)[1].name = INPUT_DETECTION_TENSOR_NAME;
(*info)[1].dimsCount = 4;
if (!get_buffer<uint64_t>(internalManager, &((*info)[1].dims), INPUT_DETECTION_INFO_DIMS_NAME, (*info)[1].dimsCount * sizeof(uint64_t))) {
release((*info)[0].dims, internalManager);
release(*info, internalManager);
return 1;
}
(*info)[1].dims[0] = 1;
(*info)[1].dims[1] = 1;
(*info)[1].dims[2] = 200;
(*info)[1].dims[3] = 7;
(*info)[1].precision = FP32;
return 0;
}
int getOutputsInfo(struct CustomNodeTensorInfo** info, int* infoCount, const struct CustomNodeParam* params, int paramsCount, void* customNodeLibraryInternalManager) {
int targetImageHeight = get_int_parameter("target_image_height", params, paramsCount, -1);
int targetImageWidth = get_int_parameter("target_image_width", params, paramsCount, -1);
NODE_ASSERT(targetImageHeight > 0, "target image height must be larger than 0");
NODE_ASSERT(targetImageWidth > 0, "target image width must be larger than 0");
std::string targetImageLayout = get_string_parameter("target_image_layout", params, paramsCount, "NCHW");
NODE_ASSERT(targetImageLayout == "NCHW" || targetImageLayout == "NHWC", "target image layout must be NCHW or NHWC");
bool convertToGrayScale = get_string_parameter("convert_to_gray_scale", params, paramsCount) == "true";
CustomNodeLibraryInternalManager* internalManager = static_cast<CustomNodeLibraryInternalManager*>(customNodeLibraryInternalManager);
std::shared_lock lock(internalManager->getInternalManagerLock());
*infoCount = 4;
if (!get_buffer<struct CustomNodeTensorInfo>(internalManager, info, OUTPUT_TENSOR_INFO_NAME, *infoCount * sizeof(CustomNodeTensorInfo))) {
return 1;
}
(*info)[0].name = OUTPUT_IMAGES_TENSOR_NAME;
(*info)[0].dimsCount = 5;
if (!get_buffer<uint64_t>(internalManager, &((*info)[0].dims), OUTPUT_IMAGES_INFO_DIMS_NAME, (*info)[0].dimsCount * sizeof(uint64_t))) {
release(*info, internalManager);
return 1;
}
(*info)[0].dims[0] = 0;
(*info)[0].dims[1] = 1;
if (targetImageLayout == "NCHW") {
(*info)[0].dims[2] = convertToGrayScale ? 1 : 3;
(*info)[0].dims[3] = targetImageHeight;
(*info)[0].dims[4] = targetImageWidth;
} else {
(*info)[0].dims[2] = targetImageHeight;
(*info)[0].dims[3] = targetImageWidth;
(*info)[0].dims[4] = convertToGrayScale ? 1 : 3;
}
(*info)[0].precision = FP32;
(*info)[1].name = OUTPUT_COORDINATES_TENSOR_NAME;
(*info)[1].dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &((*info)[1].dims), OUTPUT_COORDINATES_INFO_DIMS_NAME, (*info)[1].dimsCount * sizeof(uint64_t))) {
release((*info)[0].dims, internalManager);
release(*info, internalManager);
return 1;
}
(*info)[1].dims[0] = 0;
(*info)[1].dims[1] = 1;
(*info)[1].dims[2] = 4;
(*info)[1].precision = FP32;
(*info)[2].name = OUTPUT_CONFIDENCES_TENSOR_NAME;
(*info)[2].dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &((*info)[2].dims), OUTPUT_CONFIDENCES_INFO_DIMS_NAME, (*info)[2].dimsCount * sizeof(uint64_t))) {
release((*info)[1].dims, internalManager);
release((*info)[0].dims, internalManager);
release(*info, internalManager);
return 1;
}
(*info)[2].dims[0] = 0;
(*info)[2].dims[1] = 1;
(*info)[2].dims[2] = 1;
(*info)[2].precision = FP32;
(*info)[3].name = OUTPUT_LABEL_IDS_TENSOR_NAME;
(*info)[3].dimsCount = 3;
if (!get_buffer<uint64_t>(internalManager, &((*info)[3].dims), OUTPUT_LABEL_IDS_INFO_DIMS_NAME, (*info)[3].dimsCount * sizeof(uint64_t))) {
release((*info)[2].dims, internalManager);
release((*info)[1].dims, internalManager);
release((*info)[0].dims, internalManager);
release(*info, internalManager);
return 1;
}
(*info)[3].dims[0] = 0;
(*info)[3].dims[1] = 1;
(*info)[3].dims[2] = 1;
(*info)[3].precision = I32;
return 0;
}
int release(void* ptr, void* customNodeLibraryInternalManager) {
CustomNodeLibraryInternalManager* internalManager = static_cast<CustomNodeLibraryInternalManager*>(customNodeLibraryInternalManager);
if (!internalManager->releaseBuffer(ptr)) {
free(ptr);
return 0;
}
return 0;
}
| 51.422719 | 288 | 0.704679 | [
"shape",
"vector"
] |
4250b6e7d1028e0e006eb9f7f948e4d465180237 | 1,144 | cpp | C++ | test/test_nearest_intersection_dist_batch.cpp | cogsys-tuebingen/cslibs_boost_geometry | a6438e6ef62afb2699173c75430b7f97e0cc451f | [
"BSD-3-Clause"
] | null | null | null | test/test_nearest_intersection_dist_batch.cpp | cogsys-tuebingen/cslibs_boost_geometry | a6438e6ef62afb2699173c75430b7f97e0cc451f | [
"BSD-3-Clause"
] | null | null | null | test/test_nearest_intersection_dist_batch.cpp | cogsys-tuebingen/cslibs_boost_geometry | a6438e6ef62afb2699173c75430b7f97e0cc451f | [
"BSD-3-Clause"
] | 1 | 2019-10-16T09:43:15.000Z | 2019-10-16T09:43:15.000Z | #include <cslibs_boost_geometry/algorithms.h>
#include <gtest/gtest.h>
#include "points_and_lines.hpp"
using namespace cslibs_boost_geometry::algorithms;
using namespace cslibs_boost_geometry::types;
using namespace cslibs_boost_geometry::test_samples;
TEST(TestCSLibsBoostGeometry, testNearestIntersectionDistBatch)
{
std::vector<double> test_result;
nearestIntersectionDistanceBatch<double, Point2d>(lines_i, lines_h, 0.0, test_result);
EXPECT_EQ(test_result[0], 1.0);
EXPECT_EQ(test_result[1], 0.0);
EXPECT_EQ(test_result[2], 1.0);
test_result.clear();
nearestIntersectionDistanceBatch<double, Point2d>(lines_i, lines_i, -1.0, test_result);
EXPECT_EQ(test_result[0], 0.0);
EXPECT_EQ(test_result[1], 0.0);
EXPECT_EQ(test_result[2], 0.0);
test_result.clear();
nearestIntersectionDistanceBatch<double, Point2d>(lines_i, lines_h, -1.0, test_result);
assert(test_result[0] == 1.0);
assert(test_result[1] == -1.0);
assert(test_result[2] == 1.0);
test_result.clear();
}
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.777778 | 91 | 0.727273 | [
"vector"
] |
425427c6ac423767590d4de54f777257ae23e9b7 | 10,458 | cpp | C++ | hoodwind/firmware/mvc/view.cpp | jessecrossen/hautmidi | 7ef969d842c6cd9bc412d08ca422d962547e88e8 | [
"Unlicense"
] | 4 | 2017-09-28T02:06:42.000Z | 2021-07-15T01:58:58.000Z | hoodwind/firmware/mvc/view.cpp | jessecrossen/hautmidi | 7ef969d842c6cd9bc412d08ca422d962547e88e8 | [
"Unlicense"
] | null | null | null | hoodwind/firmware/mvc/view.cpp | jessecrossen/hautmidi | 7ef969d842c6cd9bc412d08ca422d962547e88e8 | [
"Unlicense"
] | null | null | null | #include "view.h"
#include "../debug.h"
// VIEW ***********************************************************************
// constructor
View::View() {
_parent = _nextChild = _nextModelView = NULL;
_children = NULL;
_model = NULL;
_visible = true;
_enabled = false;
_cs = {
.bg = TFT_RGB(0, 0, 0),
.fg = TFT_RGB(255, 255, 255),
.active = TFT_RGB(64, 64, 64),
.accent = TFT_RGB(255, 0, 0)
};
_ts = {
.font = fontWithHeight(22),
.xalign = 0.5,
.yalign = 0.5
};
invalidate();
}
// rect access
Rect View::rect() { return(_r); }
void View::setRect(Rect r) {
if ((_r.x != r.x) || (_r.y != r.y) || (_r.w != r.w) || (_r.h != r.h)) {
_r = r;
invalidate();
}
}
void View::setWidth(coord_t w) {
if (w != _r.w) {
_r.w = w;
invalidate();
}
}
void View::setHeight(coord_t h) {
if (h != _r.h) {
_r.h = h;
invalidate();
}
}
// color scheme access
ColorScheme View::colorScheme() { return(_cs); }
void View::setColorScheme(ColorScheme cs) {
if ((_cs.bg != cs.bg) || (_cs.fg != cs.fg) ||
(_cs.active != cs.active) || (_cs.accent != cs.accent)) {
_cs = cs;
invalidate();
}
}
// text scheme access
TextScheme View::textScheme() { return(_ts); }
void View::setTextScheme(TextScheme ts) {
if ((_ts.font != ts.font) ||
(_ts.xalign != ts.xalign) || (_ts.yalign != ts.yalign)) {
_ts = ts;
invalidate();
}
}
// visible access
bool View::visible() { return(_visible); }
void View::setVisible(bool e) {
if (e != _visible) {
_visible = e;
invalidate();
if (_parent != NULL) _parent->invalidate();
}
}
// enabled access
bool View::enabled() { return(_enabled); }
void View::setEnabled(bool e) {
if (e != _enabled) {
_enabled = e;
invalidate();
}
}
// model access
Model *View::model() { return(_model); }
void View::setModel(Model *m) {
if (m != _model) {
if (_model != NULL) _model->removeView(this);
_model = m;
_model->addView(this);
}
}
// redraw
void View::invalidate() {
_invalid = true;
}
void View::render(Screen *s) {
// skip invisible containers
if (! _visible) return;
// redraw the view itself if it's changed
if (_invalid) {
layout();
draw(s);
}
// render subviews
View *child = _children;
while (child) {
if (child->visible()) {
// if this view has been redrawn, all of its child views
// should also be redrawn, since we may have painted over them
if (_invalid) child->invalidate();
child->render(s);
}
child = child->_nextChild;
}
// when we're done redrawing, the rect is valid
_invalid = false;
}
void View::draw(Screen *s) {
// implement this in subclasses
}
void View::layout() {
// implement this in subclasses
}
// child views
void View::addChild(View *child) {
if (_children == NULL) {
_children = child;
_children->_nextChild = NULL;
}
else {
View *node = _children;
while (node->_nextChild != NULL) node = node->_nextChild;
node->_nextChild = child;
child->_nextChild = NULL;
}
child->_parent = this;
invalidate();
}
void View::removeChild(View *child) {
View *prev = NULL;
View *node = _children;
while (node != NULL) {
if (node == child) {
// handle the first child being removed
if (prev == NULL) _children = node->_nextChild;
// handle later children being removed
else prev->_nextChild = node->_nextChild;
// remove this view as the child's parent
child->_parent = NULL;
}
prev = node;
node = node->_nextChild;
}
invalidate();
}
// handle touches
View *View::getTouchedView(Point p) {
// skip invisible views
if (! _visible) return(NULL);
// pass to child views if any intersect
View *result;
View *node = _children;
while (node != NULL) {
Rect r = node->rect();
if ((p.x >= r.x) && (p.y >= r.y) &&
(p.x <= r.x + r.w) && (p.y <= r.y + r.h)) {
result = node->getTouchedView(p);
if (result != NULL) return(result);
}
node = node->_nextChild;
}
// if no child nodes caught the touch assume this one did
if (_enabled) return(this);
return(NULL);
}
void View::touch(Point p) {
// implement behaviors in the subclass
}
void View::drag(Point p) {
// implement behaviors in the subclass
}
void View::release(Point p) {
// implement behaviors in the subclass
}
// LAYOUT CONTAINERS **********************************************************
void HStack::layout() {
coord_t w;
coord_t x = _r.x;
View *child = _children;
while (child != NULL) {
w = child->rect().w;
child->setRect({ .x = x, .y = _r.y, .w = w, .h = _r.h});
x += w;
child = child->_nextChild;
}
}
void VStack::layout() {
coord_t h;
coord_t y = _r.y;
View *child = _children;
while (child != NULL) {
h = child->rect().h;
child->setRect({ .x = _r.x, .y = y, .w = _r.w, .h = h});
y += h;
child = child->_nextChild;
}
}
ScreenStack::ScreenStack() : View() {
_currentChild = NULL;
}
void ScreenStack::addChild(View *child) {
View::addChild(child);
if (_currentChild == NULL) setCurrentChild(_children);
}
void ScreenStack::draw(Screen *s) {
s->fillRect(_r, _cs.bg);
}
void ScreenStack::layout() {
// make sure we have a current screen if there is one
if (_currentChild == NULL) _currentChild = _children;
View *child = _children;
while (child != NULL) {
child->setVisible(child == _currentChild);
child->setRect(_r);
child = child->_nextChild;
}
}
bool ScreenStack::canGoPrev() {
return((_currentChild != NULL) && (_currentChild != _children));
}
bool ScreenStack::canGoNext() {
return((_currentChild != NULL) && (_currentChild->_nextChild != NULL));
}
void ScreenStack::goPrev() {
View *child = _children;
while (child != NULL) {
if (child->_nextChild == _currentChild) {
setCurrentChild(child);
return;
}
}
child = child->_nextChild;
}
void ScreenStack::goNext() {
if (_currentChild != NULL) setCurrentChild(_currentChild->_nextChild);
}
View *ScreenStack::currentChild() { return(_currentChild); }
void ScreenStack::setCurrentChild(View *newChild) {
if (newChild == NULL) return;
View *child = _children;
while (child != NULL) {
if ((child == newChild) && (newChild != _currentChild)) {
_currentChild = newChild;
invalidate();
if (_parent != NULL) _parent->invalidate();
return;
}
child = child->_nextChild;
}
}
// ADD LABEL ******************************************************************
const char *ViewWithLabel::label() { return(_label); }
void ViewWithLabel::setLabel(const char *s) {
if (_label != s) {
_label = s;
invalidate();
}
}
void ViewWithLabel::draw(Screen *s) {
coord_t y;
coord_t tb, tx, ty;
tb = tx = ty = -1;
if (_label != NULL) {
// compute the text size
coord_t tw = strlen(_label) * _ts.font->charWidth;
coord_t th = _ts.font->charHeight;
// position the text in the box according to alignment
tx = (coord_t)((float)(_r.w - tw) * _ts.xalign);
ty = (coord_t)((float)(_r.h - th) * _ts.yalign);
tb = ty + th;
}
// fill the background
for (y = 0; y < _r.h; y++) {
_drawBackScan(s, y, _r.w);
// draw text when we get to its box
if ((y >= ty) && (y < tb)) {
s->scanText(tx, y - ty, _label, _ts.font, _cs.fg);
}
s->commitScanBuffer(_r.x, _r.y + y, _r.w);
}
}
void ViewWithLabel::_drawBackScan(Screen *s, coord_t y, coord_t w) {
// implement in subclasses
s->fillScanBuffer(0, w, _cs.bg);
}
// BUTTON VIEW ****************************************************************
Button::Button() : ViewWithLabel() {
_toggled = _touched = false;
_enabled = true;
action = NULL;
}
Button::Button(const char *s) : Button() {
setLabel(s);
}
Button::Button(const char *s, ButtonType t) : Button(s) {
type = t;
}
bool Button::toggled() { return(_toggled); }
void Button::setToggled(bool state) {
if (_toggled != state) {
_toggled = state;
invalidate();
}
}
void Button::touch(Point p) {
_touched = true;
if (type == ButtonTypeToggle) {
setToggled(! toggled());
}
invalidate();
if (action != NULL) action->onButton(this);
}
void Button::release(Point p) {
_touched = false;
invalidate();
}
void Button::_drawBackScan(Screen *s, coord_t y, coord_t w) {
// draw blank edges at top and bottom
if ((y == 0) || (y == _r.h - 1)) {
s->fillScanBuffer(0, w, _cs.bg);
return;
}
// draw the button area
color_t bg = _enabled ? _cs.active : _cs.bg;
if (_toggled) bg = _cs.accent;
s->fillScanBuffer(1, w - 2, bg);
// draw blank edges at left and right
s->scanBuffer[0] = _cs.bg;
s->scanBuffer[w - 1] = _cs.bg;
}
// SLIDER VIEW ****************************************************************
Slider::Slider() : ViewWithLabel() {
_value = 0.5;
_enabled = true;
action = NULL;
}
Slider::Slider(const char *s) : Slider() {
setLabel(s);
}
float Slider::value() { return(_value); }
void Slider::setValue(float v) {
if (! (v >= 0.0)) v = 0.0;
if (! (v <= 1.0)) v = 1.0;
if (_value != v) {
_value = v;
invalidate();
if (action != NULL) action->onSlider(this);
}
}
void Slider::touch(Point p) { drag(p); }
void Slider::drag(Point p) {
// detect orientation
if (_r.w > _r.h) {
setValue((float)(p.x - (_r.x + SliderMargin)) / (float)(_r.w - (2 * SliderMargin)));
}
else {
setValue(1.0 - ((float)(p.y - (_r.y + SliderMargin)) / (float)(_r.h - (2 * SliderMargin))));
}
}
void Slider::draw(Screen *s) {
// detect orientation and compute the size of the filled bar
if (_r.w > _r.h) { // horizontal
_valueSize = (coord_t)((float)(_r.w - 2) * _value);
}
else { // vertical
_valueSize = (coord_t)((float)(_r.h - 2) * _value);
}
ViewWithLabel::draw(s);
}
void Slider::_drawBackScan(Screen *s, coord_t y, coord_t w) {
// draw blank edges at top and bottom
if ((y == 0) || (y == _r.h - 1)) {
s->fillScanBuffer(0, w, _cs.bg);
return;
}
// fill in the center part
color_t bg = _enabled ? _cs.active : _cs.bg;
if (_r.w > _r.h) { // horizontal
s->fillScanBuffer(1, _valueSize, _cs.accent);
s->fillScanBuffer(1 + _valueSize, (_r.w - 2) - _valueSize, bg);
}
else { // vertical
s->fillScanBuffer(1, _r.w - 2,
((_r.h - 1) - y <= _valueSize) ? _cs.accent : bg);
}
// draw blank edges at left and right
s->scanBuffer[0] = _cs.bg;
s->scanBuffer[w - 1] = _cs.bg;
}
| 24.152425 | 96 | 0.576018 | [
"render",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.