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
40fc8f1cc6564c7f4ba9859022f937bceb218766
7,282
cc
C++
tensorflow/compiler/xla/python/shared_device_buffer.cc
jim-meyer/tensorflow
37eafe0e7463fa72a45624206b1b94b36021df53
[ "Apache-2.0" ]
1
2019-07-15T08:40:24.000Z
2019-07-15T08:40:24.000Z
tensorflow/compiler/xla/python/shared_device_buffer.cc
jim-meyer/tensorflow
37eafe0e7463fa72a45624206b1b94b36021df53
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/python/shared_device_buffer.cc
jim-meyer/tensorflow
37eafe0e7463fa72a45624206b1b94b36021df53
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/python/shared_device_buffer.h" #include <memory> #include "tensorflow/stream_executor/device_memory_allocator.h" namespace xla { void BufferDefinitionEvent::SetDefinitionEvent(EventPool::Handle event, se::Stream* stream) { absl::MutexLock lock(&mu_); CHECK(!event_.event()); event_ = std::move(event); CHECK(streams_defined_on_.empty()); streams_defined_on_.push_back(stream); } void BufferDefinitionEvent::WaitForEventOnStream(se::Stream* stream) { absl::MutexLock lock(&mu_); // The set of defined streams is expected to be very small indeed (usually // 1-2), so a simple linear scan should be fast enough. if (std::find(streams_defined_on_.begin(), streams_defined_on_.end(), stream) != streams_defined_on_.end()) { // stream is in streams_defined_on_; it doesn't need to be waited on. return; } stream->ThenWaitFor(event_.event()); streams_defined_on_.push_back(stream); } static std::shared_ptr<SharedDeviceBuffer> BufferFromScopedShapedBufferIterator( const Shape& on_device_shape, int device_ordinal, se::DeviceMemoryAllocator* allocator, ShapeTree<se::DeviceMemoryBase>::iterator* iterator, const ShapeTree<se::DeviceMemoryBase>::iterator& end, const std::shared_ptr<BufferDefinitionEvent>& definition_event) { CHECK(*iterator != end); se::OwningDeviceMemory device_memory((*iterator)->second, device_ordinal, allocator); (*iterator)->second = se::DeviceMemoryBase(); ++*iterator; std::vector<std::shared_ptr<SharedDeviceBuffer>> children; if (on_device_shape.IsTuple()) { int num_children = ShapeUtil::TupleElementCount(on_device_shape); children.reserve(num_children); for (int i = 0; i < num_children; ++i) { children.push_back(BufferFromScopedShapedBufferIterator( on_device_shape.tuple_shapes(i), device_ordinal, allocator, iterator, end, definition_event)); } } return std::make_shared<SharedDeviceBuffer>( on_device_shape, std::move(device_memory), children, definition_event); } /* static */ std::shared_ptr<SharedDeviceBuffer> SharedDeviceBuffer::FromScopedShapedBuffer( ScopedShapedBuffer shaped_buffer, const std::shared_ptr<BufferDefinitionEvent>& definition_event) { ShapeTree<se::DeviceMemoryBase>::iterator iterator = shaped_buffer.buffers().begin(); std::shared_ptr<SharedDeviceBuffer> output = BufferFromScopedShapedBufferIterator( shaped_buffer.on_device_shape(), shaped_buffer.device_ordinal(), shaped_buffer.memory_allocator(), &iterator, shaped_buffer.buffers().end(), definition_event); CHECK(iterator == shaped_buffer.buffers().end()); return output; } /* static */ StatusOr<std::shared_ptr<SharedDeviceBuffer>> SharedDeviceBuffer::MakeTuple( std::vector<std::shared_ptr<SharedDeviceBuffer>> children, TransferManager* transfer_manager, se::DeviceMemoryAllocator* allocator, int device_ordinal, std::shared_ptr<BufferDefinitionEvent> definition_event) { std::vector<Shape> child_shapes; child_shapes.reserve(children.size()); for (const auto& child : children) { TF_RET_CHECK(child->device_memory().device_ordinal() == device_ordinal); child_shapes.push_back(child->on_device_shape()); } Shape shape = ShapeUtil::MakeTupleShape(child_shapes); TF_ASSIGN_OR_RETURN( se::OwningDeviceMemory device_memory, allocator->Allocate(device_ordinal, transfer_manager->GetByteSizeRequirement(shape))); return std::make_shared<SharedDeviceBuffer>( std::move(shape), std::move(device_memory), std::move(children), std::move(definition_event)); } /* static */ StatusOr<std::shared_ptr<SharedDeviceBuffer>> SharedDeviceBuffer::MakeArray( Shape on_device_shape, TransferManager* transfer_manager, se::DeviceMemoryAllocator* allocator, int device_ordinal, std::shared_ptr<BufferDefinitionEvent> definition_event) { TF_ASSIGN_OR_RETURN( se::OwningDeviceMemory device_memory, allocator->Allocate( device_ordinal, transfer_manager->GetByteSizeRequirement(on_device_shape))); return std::make_shared<SharedDeviceBuffer>( std::move(on_device_shape), std::move(device_memory), /*children=*/std::vector<std::shared_ptr<SharedDeviceBuffer>>{}, std::move(definition_event)); } // Populates a buffer tree from a ShapeTree iterator. static void PopulateShapedBufferFromBuffer( const SharedDeviceBuffer& buffer, ShapeTree<se::DeviceMemoryBase>::iterator* iterator, const ShapeTree<se::DeviceMemoryBase>::iterator& end) { CHECK(*iterator != end); (*iterator)->second = *buffer.device_memory(); ++*iterator; for (const auto& child : buffer.children()) { PopulateShapedBufferFromBuffer(*child, iterator, end); } } ShapedBuffer SharedDeviceBuffer::AsShapedBuffer( const Shape& on_host_shape) const { ShapedBuffer shaped_buffer(on_host_shape, on_device_shape_, device_memory_.allocator()->platform(), device_memory_.device_ordinal()); ShapeTree<se::DeviceMemoryBase>::iterator iterator = shaped_buffer.buffers().begin(); PopulateShapedBufferFromBuffer(*this, &iterator, shaped_buffer.buffers().end()); CHECK(iterator == shaped_buffer.buffers().end()); return shaped_buffer; } SharedDeviceBuffer::SharedDeviceBuffer( Shape on_device_shape, se::OwningDeviceMemory device_memory, std::vector<std::shared_ptr<SharedDeviceBuffer>> children, std::shared_ptr<BufferDefinitionEvent> definition_event) : on_device_shape_(std::move(on_device_shape)), device_memory_(std::move(device_memory)), children_(std::move(children)), definition_event_(std::move(definition_event)) {} void GetDeviceBufferDefinitionEvents( const SharedDeviceBuffer& buffer, absl::flat_hash_set<BufferDefinitionEvent*>* events) { if (buffer.definition_event()) { events->insert(buffer.definition_event().get()); } for (const auto& child : buffer.children()) { GetDeviceBufferDefinitionEvents(*child, events); } } void WaitForBufferDefinitionEventsOnStream(const SharedDeviceBuffer& buffer, se::Stream* stream) { absl::flat_hash_set<BufferDefinitionEvent*> events; GetDeviceBufferDefinitionEvents(buffer, &events); for (BufferDefinitionEvent* event : events) { event->WaitForEventOnStream(stream); } } } // namespace xla
39.362162
80
0.716149
[ "shape", "vector" ]
dc011cc07840f50976d3280d68c036670aea81c8
16,801
cpp
C++
src/demos/fea/demo_FEA_dynamics.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/demos/fea/demo_FEA_dynamics.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/demos/fea/demo_FEA_dynamics.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora // ============================================================================= // // FEA (introduction to dynamics) // // ============================================================================= #include "chrono/physics/ChSystemSMC.h" #include "chrono/solver/ChIterativeSolverLS.h" #include "chrono/fea/ChElementSpring.h" #include "chrono/fea/ChElementShellANCF_3423.h" #include "chrono/fea/ChElementHexaANCF_3813.h" #include "chrono/fea/ChElementBar.h" #include "chrono/fea/ChElementTetraCorot_4.h" #include "chrono/fea/ChElementTetraCorot_10.h" #include "chrono/fea/ChElementHexaCorot_8.h" #include "chrono/fea/ChElementHexaCorot_20.h" #include "chrono/fea/ChMesh.h" #include "chrono/fea/ChLinkPointFrame.h" #include "chrono/fea/ChLinkDirFrame.h" // Remember to use the namespace 'chrono' because all classes // of Chrono::Engine belong to this namespace and its children... using namespace chrono; using namespace fea; void test_1() { GetLog() << "\n-------------------------------------------------\n"; GetLog() << "TEST: spring FEM dynamics, implicit integration \n\n"; // The physical system: it contains all physical objects. ChSystemSMC sys; // Create a mesh, that is a container for groups // of elements and their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); // Create some nodes. These are the classical point-like // nodes with x,y,z degrees of freedom, that can be used // for many types of FEM elements in space. auto mnodeA = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 0)); auto mnodeB = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 1, 0)); // Default mass for FEM nodes is zero, so set point-like // masses because the ChElementSpring FEM element that we // are going to use won't add any mass: mnodeA->SetMass(100.0); mnodeB->SetMass(100.0); // For example, set an applied force to a node: mnodeB->SetForce(ChVector<>(0, 5, 0)); // For example, set an initial displacement to a node: mnodeB->SetPos(mnodeB->GetX0() + ChVector<>(0, 0.1, 0)); // Remember to add nodes and elements to the mesh! my_mesh->AddNode(mnodeA); my_mesh->AddNode(mnodeB); // Create some elements of 'spring-damper' type, each connecting // two 3D nodes: auto melementA = chrono_types::make_shared<ChElementSpring>(); melementA->SetNodes(mnodeA, mnodeB); melementA->SetSpringK(2000); melementA->SetDamperR(0); // Remember to add elements to the mesh! my_mesh->AddElement(melementA); // Remember to add the mesh to the system! sys.Add(my_mesh); // Create also a truss auto truss = chrono_types::make_shared<ChBody>(); truss->SetBodyFixed(true); sys.Add(truss); // Create a constraint between a node and the truss auto constraintA = chrono_types::make_shared<ChLinkPointFrame>(); constraintA->Initialize(mnodeA, // node truss); // body to be connected to sys.Add(constraintA); // Set no gravity // sys.Set_G_acc(VNULL); // Perform a dynamic time integration: auto solver = chrono_types::make_shared<ChSolverMINRES>(); sys.SetSolver(solver); solver->SetMaxIterations(40); sys.SetSolverForceTolerance(1e-10); sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED); double timestep = 0.01; while (sys.GetChTime() < 2) { sys.DoStepDynamics(timestep); GetLog() << " t=" << sys.GetChTime() << " nodeB pos.y()=" << mnodeB->GetPos().y() << " \n"; } } void test_2() { GetLog() << "\n-------------------------------------------------\n"; GetLog() << "TEST: bar FEM dynamics, implicit integration \n\n"; // The physical system: it contains all physical objects. ChSystemSMC sys; // Create a mesh, that is a container for groups // of elements and their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); // Create some nodes. These are the classical point-like // nodes with x,y,z degrees of freedom, that can be used // for many types of FEM elements in space. auto mnodeA = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 0)); auto mnodeB = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 1, 0)); // Set no point-like masses because mass is already in bar element: mnodeA->SetMass(0.0); mnodeB->SetMass(0.0); // For example, set an applied force to a node: mnodeB->SetForce(ChVector<>(0, 5, 0)); // For example, set an initial displacement to a node: mnodeB->SetPos(mnodeB->GetX0() + ChVector<>(0, 0.1, 0)); // Remember to add nodes and elements to the mesh! my_mesh->AddNode(mnodeA); my_mesh->AddNode(mnodeB); // Create some elements of 'bar' type, each connecting // two 3D nodes: auto melementA = chrono_types::make_shared<ChElementBar>(); melementA->SetNodes(mnodeA, mnodeB); melementA->SetBarArea(0.1 * 0.02); melementA->SetBarYoungModulus(0.01e9); // rubber 0.01e9, steel 200e9 melementA->SetBarRaleyghDamping(0.01); melementA->SetBarDensity(2. * 0.1 / (melementA->GetBarArea() * 1.0)); // melementA->SetBarDensity(0); // Remember to add elements to the mesh! my_mesh->AddElement(melementA); // Remember to add the mesh to the system! sys.Add(my_mesh); // Create also a truss auto truss = chrono_types::make_shared<ChBody>(); truss->SetBodyFixed(true); sys.Add(truss); // Create a constraint between a node and the truss auto constraintA = chrono_types::make_shared<ChLinkPointFrame>(); constraintA->Initialize(mnodeA, // node truss); // body to be connected to sys.Add(constraintA); // Set no gravity // sys.Set_G_acc(VNULL); // Perform a dynamic time integration: auto solver = chrono_types::make_shared<ChSolverMINRES>(); sys.SetSolver(solver); solver->SetMaxIterations(100); solver->SetTolerance(1e-8); solver->EnableDiagonalPreconditioner(true); sys.SetSolverForceTolerance(1e-10); sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); double timestep = 0.001; while (sys.GetChTime() < 0.2) { sys.DoStepDynamics(timestep); GetLog() << " t=" << sys.GetChTime() << " nodeB pos.y()=" << mnodeB->GetPos().y() << " \n"; } GetLog() << " Bar mass = " << melementA->GetMass() << " restlength = " << melementA->GetRestLength() << "\n"; } void test_2b() { GetLog() << "\n-------------------------------------------------\n"; GetLog() << "TEST: spring FEM dynamics compare to bar \n\n"; // The physical system: it contains all physical objects. ChSystemSMC sys; // Create a mesh, that is a container for groups // of elements and their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); // Create some nodes. These are the classical point-like // nodes with x,y,z degrees of freedom, that can be used // for many types of FEM elements in space. auto mnodeA = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 0)); auto mnodeB = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 1, 0)); // Default mass for FEM nodes is zero, so set point-like // masses because the ChElementSpring FEM element that we // are going to use won't add any mass: mnodeA->SetMass(0.1); mnodeB->SetMass(0.1); // For example, set an applied force to a node: mnodeB->SetForce(ChVector<>(0, 5, 0)); // For example, set an initial displacement to a node: mnodeB->SetPos(mnodeB->GetX0() + ChVector<>(0, 0.1, 0)); // Remember to add nodes and elements to the mesh! my_mesh->AddNode(mnodeA); my_mesh->AddNode(mnodeB); // Create some elements of 'spring-damper' type, each connecting // two 3D nodes: auto melementA = chrono_types::make_shared<ChElementSpring>(); melementA->SetNodes(mnodeA, mnodeB); melementA->SetSpringK(20000); melementA->SetDamperR(200); // Remember to add elements to the mesh! my_mesh->AddElement(melementA); // Remember to add the mesh to the system! sys.Add(my_mesh); // Create also a truss auto truss = chrono_types::make_shared<ChBody>(); truss->SetBodyFixed(true); sys.Add(truss); // Create a constraint between a node and the truss auto constraintA = chrono_types::make_shared<ChLinkPointFrame>(); constraintA->Initialize(mnodeA, // node truss); // body to be connected to sys.Add(constraintA); // Set no gravity // sys.Set_G_acc(VNULL); // Perform a dynamic time integration: auto solver = chrono_types::make_shared<ChSolverMINRES>(); sys.SetSolver(solver); solver->SetMaxIterations(200); solver->SetTolerance(1e-12); sys.SetSolverForceTolerance(1e-10); sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); double timestep = 0.001; while (sys.GetChTime() < 0.2) { sys.DoStepDynamics(timestep); GetLog() << " t=" << sys.GetChTime() << " nodeB pos.y()=" << mnodeB->GetPos().y() << " \n"; } } void test_3() { GetLog() << "\n-------------------------------------------------\n"; GetLog() << "TEST: tetrahedron FEM dynamics, implicit integration \n\n"; // The physical system: it contains all physical objects. ChSystemSMC sys; // Create a mesh, that is a container for groups // of elements and their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); // Create a material, that must be assigned to each element, // and set its parameters auto mmaterial = chrono_types::make_shared<ChContinuumElastic>(); mmaterial->Set_E(0.01e9); // rubber 0.01e9, steel 200e9 mmaterial->Set_v(0.3); mmaterial->Set_RayleighDampingK(0.01); mmaterial->Set_density(1000); // Create some nodes. These are the classical point-like // nodes with x,y,z degrees of freedom, that can be used // for many types of FEM elements in space. auto mnode1 = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 0)); auto mnode2 = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 1)); auto mnode3 = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 1, 0)); auto mnode4 = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(1, 0, 0)); // For example, set a point-like mass at a node: mnode1->SetMass(200); mnode2->SetMass(200); mnode3->SetMass(200); mnode4->SetMass(200); // For example, set an initial displacement to a node: mnode3->SetPos(mnode3->GetX0() + ChVector<>(0, 0.01, 0)); // Remember to add nodes and elements to the mesh! my_mesh->AddNode(mnode1); my_mesh->AddNode(mnode2); my_mesh->AddNode(mnode3); my_mesh->AddNode(mnode4); // Create the tetrahedron element, and assign // nodes and material auto melement1 = chrono_types::make_shared<ChElementTetraCorot_4>(); melement1->SetNodes(mnode1, mnode2, mnode3, mnode4); melement1->SetMaterial(mmaterial); // Remember to add elements to the mesh! my_mesh->AddElement(melement1); // Remember to add the mesh to the system! sys.Add(my_mesh); // Create also a truss auto truss = chrono_types::make_shared<ChBody>(); truss->SetBodyFixed(true); sys.Add(truss); // Create a constraint between a node and the truss auto constraint1 = chrono_types::make_shared<ChLinkPointFrame>(); auto constraint2 = chrono_types::make_shared<ChLinkPointFrame>(); auto constraint3 = chrono_types::make_shared<ChLinkPointFrame>(); constraint1->Initialize(mnode1, // node truss); // body to be connected to constraint2->Initialize(mnode2, // node truss); // body to be connected to constraint3->Initialize(mnode4, // node truss); // body to be connected to sys.Add(constraint1); sys.Add(constraint2); sys.Add(constraint3); // Perform a dynamic time integration: auto solver = chrono_types::make_shared<ChSolverMINRES>(); sys.SetSolver(solver); solver->SetMaxIterations(40); solver->SetTolerance(1e-8); sys.SetSolverForceTolerance(1e-10); sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED); double timestep = 0.001; while (sys.GetChTime() < 0.1) { sys.DoStepDynamics(timestep); GetLog() << " t =" << sys.GetChTime() << " mnode3 pos.y()=" << mnode3->GetPos().y() << " \n"; } } void test_4() { GetLog() << "\n-------------------------------------------------\n"; GetLog() << "TEST: bar FEM dynamics (2 elements), implicit integration \n\n"; // The physical system: it contains all physical objects. ChSystemSMC sys; // Create a mesh, that is a container for groups // of elements and their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); // Create some nodes. These are the classical point-like // nodes with x,y,z degrees of freedom, that can be used // for many types of FEM elements in space. auto mnodeA = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 0, 0)); auto mnodeB = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 1, 0)); auto mnodeC = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(0, 2, 0)); // Set no point-like masses because mass is already in bar element: mnodeA->SetMass(0.0); mnodeB->SetMass(0.0); mnodeC->SetMass(0.0); // For example, set an applied force to a node: mnodeB->SetForce(ChVector<>(0, 5, 0)); // For example, set an applied force to a node: mnodeC->SetForce(ChVector<>(0, 2, 0)); // For example, set an initial displacement to a node: mnodeC->SetPos(mnodeC->GetX0() + ChVector<>(0, 0.1, 0)); // Remember to add nodes and elements to the mesh! my_mesh->AddNode(mnodeA); my_mesh->AddNode(mnodeB); my_mesh->AddNode(mnodeC); // Create some elements of 'bar' type, each connecting // two 3D nodes: auto melementA = chrono_types::make_shared<ChElementBar>(); melementA->SetNodes(mnodeA, mnodeB); melementA->SetBarArea(0.1 * 0.02); melementA->SetBarYoungModulus(0.01e9); // rubber 0.01e9, steel 200e9 melementA->SetBarRaleyghDamping(0.01); melementA->SetBarDensity(2. * 0.1 / (melementA->GetBarArea() * 1.0)); auto melementB = chrono_types::make_shared<ChElementBar>(); melementB->SetNodes(mnodeB, mnodeC); melementB->SetBarArea(0.1 * 0.02); melementB->SetBarYoungModulus(0.01e9); // rubber 0.01e9, steel 200e9 melementB->SetBarRaleyghDamping(0.01); melementB->SetBarDensity(2. * 0.1 / (melementB->GetBarArea() * 1.0)); // Remember to add elements to the mesh! my_mesh->AddElement(melementA); my_mesh->AddElement(melementB); // Remember to add the mesh to the system! sys.Add(my_mesh); // Create also a truss auto truss = chrono_types::make_shared<ChBody>(); truss->SetBodyFixed(true); sys.Add(truss); // Create a constraint between a node and the truss auto constraintA = chrono_types::make_shared<ChLinkPointFrame>(); constraintA->Initialize(mnodeA, // node truss); // body to be connected to sys.Add(constraintA); // Set no gravity // sys.Set_G_acc(VNULL); // Perform a dynamic time integration: auto solver = chrono_types::make_shared<ChSolverMINRES>(); sys.SetSolver(solver); solver->SetMaxIterations(100); solver->SetTolerance(1e-8); solver->EnableDiagonalPreconditioner(true); sys.SetSolverForceTolerance(1e-10); sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); double timestep = 0.001; while (sys.GetChTime() < 0.2) { sys.DoStepDynamics(timestep); GetLog() << " t=" << sys.GetChTime() << " nodeB pos.y()=" << mnodeB->GetPos().y() << " nodeC pos.y()=" << mnodeC->GetPos().y() << " \n"; } } int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // test_1(); // test_2(); test_3(); // test_4(); return 0; }
34.569959
114
0.637522
[ "mesh", "3d" ]
dc02b661cbe5a1b3bbb83596b4dd5cb5b9c9db63
853
cpp
C++
Src/Evora/Engine/drop_center.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
1
2020-11-25T20:53:36.000Z
2020-11-25T20:53:36.000Z
Src/Evora/Engine/drop_center.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
16
2020-03-06T09:11:55.000Z
2020-07-24T10:57:41.000Z
Src/Evora/Engine/drop_center.cpp
medovina/Evora
95e41e7b2d5c408d515a01a5649ddfaa211e9349
[ "Apache-2.0" ]
1
2020-01-18T13:11:38.000Z
2020-01-18T13:11:38.000Z
#include "drop_center.h" using namespace control; void drop_center::execute(std::shared_ptr<model::game> game) { m_starter_tile = game->handle_center_starter_tile(m_player_index); m_tile_indices = game->get_center_tile_indices(m_color); m_moved_to_floor = game->center_to_floor(m_player_index, m_color); m_moved_to_lid = game->center_to_lid(m_color); } void drop_center::unexecute(std::shared_ptr<model::game> game) { game->floor_to_center(m_player_index, m_color, m_moved_to_floor, m_tile_indices); game->lid_to_center(m_color, m_moved_to_lid, m_tile_indices); if(m_starter_tile) { game->starter_tile_to_center(m_player_index); } } std::unique_ptr<command> drop_center::clone() { return std::make_unique<drop_center>(*this); } bool drop_center::is_move() { return true; } int drop_center::player_index() { return m_player_index; }
23.054054
82
0.779601
[ "model" ]
dc09d688742cc82be22532463f13d9502571f61b
8,750
cpp
C++
src/test/chainparams_tests.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
src/test/chainparams_tests.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
src/test/chainparams_tests.cpp
koalajack/koalachain
84b5d5351072947f79f982ca24666047e955df3d
[ "MIT" ]
null
null
null
/* * chainparams_tests.cpp * * Created on: Jul 31, 2014 * Author: spark.huang */ #include "chainparams.h" #include "util.h" #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include <boost/assign/list_of.hpp> BOOST_AUTO_TEST_SUITE(chainparam_tests) static void ResetArgs(const std::string& strArg) { std::vector<std::string> vecArg; boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on); // Insert dummy executable name: vecArg.insert(vecArg.begin(), "testbitcoin"); // Convert to char*: std::vector<const char*> vecChar; for (auto& s : vecArg) vecChar.push_back(s.c_str()); CBaseParams::IntialParams(vecChar.size(), &vecChar[0]); } BOOST_AUTO_TEST_CASE(boolarg) { map<string, string> mapArgs = SysCfg().GetMapArgs(); map<string, vector<string> > mapMultiArgs = SysCfg().GetMapMultiArgs(); ResetArgs("-foo"); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(!SysCfg().GetBoolArg("-fo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-fo", true)); BOOST_CHECK(!SysCfg().GetBoolArg("-fooo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-fooo", true)); ResetArgs("-foo=0"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); ResetArgs("-foo=1"); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); // New 0.6 feature: auto-map -nosomething to !-something: ResetArgs("-nofoo"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); ResetArgs("-nofoo=1"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); ResetArgs("-foo -nofoo"); // -foo should win BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); ResetArgs("-foo=1 -nofoo=1"); // -foo should win BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); ResetArgs("-foo=0 -nofoo=0"); // -foo should win BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); // New 0.6 feature: treat -- same as -: ResetArgs("--foo=1"); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); ResetArgs("--nofoo=1"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); SysCfg().SetMapArgs(mapArgs); SysCfg().SetMultiMapArgs(mapMultiArgs); } BOOST_AUTO_TEST_CASE(stringarg) { map<string, string> mapArgs = SysCfg().GetMapArgs(); map<string, vector<string> > mapMultiArgs = SysCfg().GetMapMultiArgs(); ResetArgs(""); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", "eleven"), "eleven"); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", "eleven"), ""); ResetArgs("-foo="); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", "eleven"), ""); ResetArgs("-foo=11"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), "11"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", "eleven"), "11"); ResetArgs("-foo=eleven"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), "eleven"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", "eleven"), "eleven"); SysCfg().SetMapArgs(mapArgs); SysCfg().SetMultiMapArgs(mapMultiArgs); } BOOST_AUTO_TEST_CASE(intarg) { map<string, string> mapArgs = SysCfg().GetMapArgs(); map<string, vector<string> > mapMultiArgs = SysCfg().GetMapMultiArgs(); ResetArgs(""); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", 11), 11); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", 0), 0); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", 11), 0); BOOST_CHECK_EQUAL(SysCfg().GetArg("-bar", 11), 0); ResetArgs("-foo=11 -bar=12"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", 0), 11); BOOST_CHECK_EQUAL(SysCfg().GetArg("-bar", 11), 12); ResetArgs("-foo=NaN -bar=NotANumber"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", 1), 0); BOOST_CHECK_EQUAL(SysCfg().GetArg("-bar", 11), 0); SysCfg().SetMapArgs(mapArgs); SysCfg().SetMultiMapArgs(mapMultiArgs); } BOOST_AUTO_TEST_CASE(doubledash) { map<string, string> mapArgs = SysCfg().GetMapArgs(); map<string, vector<string> > mapMultiArgs = SysCfg().GetMapMultiArgs(); ResetArgs("--foo"); BOOST_CHECK_EQUAL(SysCfg().GetBoolArg("-foo", false), true); ResetArgs("--foo=verbose --bar=1"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-foo", ""), "verbose"); BOOST_CHECK_EQUAL(SysCfg().GetArg("-bar", 0), 1); SysCfg().SetMapArgs(mapArgs); SysCfg().SetMultiMapArgs(mapMultiArgs); } BOOST_AUTO_TEST_CASE(boolargno) { map<string, string> mapArgs = SysCfg().GetMapArgs(); map<string, vector<string> > mapMultiArgs = SysCfg().GetMapMultiArgs(); ResetArgs("-nofoo"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); ResetArgs("-nofoo=1"); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(!SysCfg().GetBoolArg("-foo", false)); ResetArgs("-nofoo=0"); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); ResetArgs("-foo --nofoo"); BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); ResetArgs("-nofoo -foo"); // foo always wins: BOOST_CHECK(SysCfg().GetBoolArg("-foo", true)); BOOST_CHECK(SysCfg().GetBoolArg("-foo", false)); SysCfg().SetMapArgs(mapArgs); SysCfg().SetMultiMapArgs(mapMultiArgs); } BOOST_AUTO_TEST_CASE(chain_main) { // BOOST_CHECK( // SysParamsMain().HashGenesisBlock() // == uint256("30090f75e06a2edb5faf635626dbdbebc3fdc8d8922382b0c0d261aa561666f9")); BOOST_CHECK(SysParamsMain().MessageStart()[0] == 0xfe); BOOST_CHECK(SysParamsMain().MessageStart()[1] == 0xfd); BOOST_CHECK(SysParamsMain().MessageStart()[2] == 0x3a); BOOST_CHECK(SysParamsMain().MessageStart()[3] == 0x16); BOOST_CHECK_MESSAGE(SysParamsMain().AlertKey() == ParseHex("02f8f48123e5cf8ead7e5d09828209acee41b2d41920350a36535532decf28d19a"), "" << HexStr(SysParamsMain().AlertKey())); BOOST_CHECK(SysParamsMain().GetDefaultPort() == 5666); // BOOST_CHECK(SysParamsMain().ProofOfWorkLimit() == (~arith_uint256(0) >> 10)); BOOST_CHECK(SysParamsMain().RequireRPCPassword() == true); BOOST_CHECK(SysParamsMain().DataDir() == "main"); BOOST_CHECK(SysParamsMain().NetworkID() == CBaseParams::MAIN); BOOST_CHECK_MESSAGE(SysParamsMain().RPCPort() == 18356, "" << SysParamsMain().RPCPort()); } BOOST_AUTO_TEST_CASE(chain_test) { // BOOST_CHECK( // SysParamsTest().HashGenesisBlock() // == uint256("379789424d6706afff7d19410c857601e483a8a70e8e83bea4d72bbe71ea1781")); BOOST_CHECK(SysParamsTest().MessageStart()[0] == 0xfd); BOOST_CHECK(SysParamsTest().MessageStart()[1] == 0x1a); BOOST_CHECK(SysParamsTest().MessageStart()[2] == 0x2c); BOOST_CHECK(SysParamsTest().MessageStart()[3] == 0x1d); BOOST_CHECK_MESSAGE(SysParamsMain().AlertKey() == ParseHex("02f8f48123e5cf8ead7e5d09828209acee41b2d41920350a36535532decf28d19a"), "" << HexStr(SysParamsMain().AlertKey())); BOOST_CHECK(SysParamsTest().GetDefaultPort() == 15666); // BOOST_CHECK(SysParamsTest().ProofOfWorkLimit() == (~arith_uint256(0) >> 10)); BOOST_CHECK(SysParamsTest().RequireRPCPassword() == true); BOOST_CHECK(SysParamsTest().DataDir() == "testnet"); BOOST_CHECK(SysParamsTest().NetworkID() == CBaseParams::TESTNET); BOOST_CHECK_MESSAGE(SysParamsMain().RPCPort() == 18356, "" << SysParamsMain().RPCPort()); } BOOST_AUTO_TEST_CASE(chain_regtest) { // BOOST_CHECK( // SysParamsReg().HashGenesisBlock() // == uint256("b3c285730fee7d92791cd71fa0f7bb9dbb8d5f0da39029f0d284935f39afacae")); BOOST_CHECK(SysParamsReg().MessageStart()[0] == 0xfa); BOOST_CHECK(SysParamsReg().MessageStart()[1] == 0x3c); BOOST_CHECK(SysParamsReg().MessageStart()[2] == 0x1d); BOOST_CHECK(SysParamsReg().MessageStart()[3] == 0x2f); BOOST_CHECK_MESSAGE(SysParamsMain().AlertKey() == ParseHex("02f8f48123e5cf8ead7e5d09828209acee41b2d41920350a36535532decf28d19a"), "" << HexStr(SysParamsMain().AlertKey())); BOOST_CHECK(SysParamsReg().GetDefaultPort() == 11666); // BOOST_CHECK(SysParamsReg().ProofOfWorkLimit() == (~arith_uint256(0) >> 6)); BOOST_CHECK(SysParamsReg().SubsidyHalvingInterval() == 150); BOOST_CHECK(SysParamsReg().RequireRPCPassword() == false); BOOST_CHECK(SysParamsReg().DataDir() == "regtest"); BOOST_CHECK(SysParamsReg().NetworkID() == CBaseParams::REGTEST); BOOST_CHECK_MESSAGE(SysParamsMain().RPCPort() == 18356, "" << SysParamsMain().RPCPort()); } BOOST_AUTO_TEST_SUITE_END()
36.00823
174
0.7064
[ "vector" ]
dc0cd4c8b538efba327f421ea2b916bc9817787e
8,010
cc
C++
test/pc/e2e/peer_configurer.cc
hjybdrs/webrtcRepo
9427b51d6ff50af73c217cb725b1c59b9d701796
[ "BSD-3-Clause" ]
null
null
null
test/pc/e2e/peer_configurer.cc
hjybdrs/webrtcRepo
9427b51d6ff50af73c217cb725b1c59b9d701796
[ "BSD-3-Clause" ]
null
null
null
test/pc/e2e/peer_configurer.cc
hjybdrs/webrtcRepo
9427b51d6ff50af73c217cb725b1c59b9d701796
[ "BSD-3-Clause" ]
1
2021-11-09T03:15:47.000Z
2021-11-09T03:15:47.000Z
/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/pc/e2e/peer_configurer.h" #include <set> #include "test/testsupport/file_utils.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { using AudioConfig = PeerConnectionE2EQualityTestFixture::AudioConfig; using VideoConfig = PeerConnectionE2EQualityTestFixture::VideoConfig; using RunParams = PeerConnectionE2EQualityTestFixture::RunParams; using VideoGeneratorType = PeerConnectionE2EQualityTestFixture::VideoGeneratorType; using VideoCodecConfig = PeerConnectionE2EQualityTestFixture::VideoCodecConfig; std::string VideoConfigSourcePresenceToString( const VideoConfig& video_config, bool has_user_provided_generator) { char buf[1024]; rtc::SimpleStringBuilder builder(buf); builder << "video_config.generator=" << video_config.generator.has_value() << "; video_config.input_file_name=" << video_config.input_file_name.has_value() << "; video_config.screen_share_config=" << video_config.screen_share_config.has_value() << "; video_config.capturing_device_index=" << video_config.capturing_device_index.has_value() << "; has_user_provided_generator=" << has_user_provided_generator << ";"; return builder.str(); } } // namespace void SetDefaultValuesForMissingParams( RunParams* run_params, std::vector<std::unique_ptr<PeerConfigurerImpl>>* peers) { int video_counter = 0; int audio_counter = 0; std::set<std::string> video_labels; std::set<std::string> audio_labels; for (size_t i = 0; i < peers->size(); ++i) { auto* peer = peers->at(i).get(); auto* p = peer->params(); for (size_t j = 0; j < p->video_configs.size(); ++j) { VideoConfig& video_config = p->video_configs[j]; std::unique_ptr<test::FrameGeneratorInterface>& video_generator = (*peer->video_generators())[j]; if (!video_config.generator && !video_config.input_file_name && !video_config.screen_share_config && !video_config.capturing_device_index && !video_generator) { video_config.generator = VideoGeneratorType::kDefault; } if (!video_config.stream_label) { std::string label; do { label = "_auto_video_stream_label_" + std::to_string(video_counter); ++video_counter; } while (!video_labels.insert(label).second); video_config.stream_label = label; } } if (p->audio_config) { if (!p->audio_config->stream_label) { std::string label; do { label = "_auto_audio_stream_label_" + std::to_string(audio_counter); ++audio_counter; } while (!audio_labels.insert(label).second); p->audio_config->stream_label = label; } } } if (run_params->video_codecs.empty()) { run_params->video_codecs.push_back( VideoCodecConfig(cricket::kVp8CodecName)); } } void ValidateParams( const RunParams& run_params, const std::vector<std::unique_ptr<PeerConfigurerImpl>>& peers) { RTC_CHECK_GT(run_params.video_encoder_bitrate_multiplier, 0.0); std::set<std::string> video_labels; std::set<std::string> audio_labels; int media_streams_count = 0; bool has_simulcast = false; for (size_t i = 0; i < peers.size(); ++i) { Params* p = peers[i]->params(); if (p->audio_config) { media_streams_count++; } media_streams_count += p->video_configs.size(); // Validate that each video config has exactly one of |generator|, // |input_file_name| or |screen_share_config| set. Also validate that all // video stream labels are unique. for (size_t j = 0; j < p->video_configs.size(); ++j) { VideoConfig& video_config = p->video_configs[j]; RTC_CHECK(video_config.stream_label); bool inserted = video_labels.insert(video_config.stream_label.value()).second; RTC_CHECK(inserted) << "Duplicate video_config.stream_label=" << video_config.stream_label.value(); int input_sources_count = 0; if (video_config.generator) ++input_sources_count; if (video_config.input_file_name) ++input_sources_count; if (video_config.screen_share_config) ++input_sources_count; if (video_config.capturing_device_index) ++input_sources_count; if ((*peers[i]->video_generators())[j]) ++input_sources_count; // TODO(titovartem) handle video_generators case properly RTC_CHECK_EQ(input_sources_count, 1) << VideoConfigSourcePresenceToString( video_config, (*peers[i]->video_generators())[j] != nullptr); if (video_config.screen_share_config) { if (video_config.screen_share_config->slides_yuv_file_names.empty()) { if (video_config.screen_share_config->scrolling_params) { // If we have scrolling params, then its |source_width| and // |source_heigh| will be used as width and height of video input, // so we have to validate it against width and height of default // input. RTC_CHECK_EQ(video_config.screen_share_config->scrolling_params ->source_width, kDefaultSlidesWidth); RTC_CHECK_EQ(video_config.screen_share_config->scrolling_params ->source_height, kDefaultSlidesHeight); } else { RTC_CHECK_EQ(video_config.width, kDefaultSlidesWidth); RTC_CHECK_EQ(video_config.height, kDefaultSlidesHeight); } } if (video_config.screen_share_config->scrolling_params) { RTC_CHECK_LE( video_config.screen_share_config->scrolling_params->duration, video_config.screen_share_config->slide_change_interval); RTC_CHECK_GE( video_config.screen_share_config->scrolling_params->source_width, video_config.width); RTC_CHECK_GE( video_config.screen_share_config->scrolling_params->source_height, video_config.height); } } if (video_config.simulcast_config) { has_simulcast = true; RTC_CHECK(!video_config.max_encode_bitrate_bps) << "Setting max encode bitrate is not implemented for simulcast."; RTC_CHECK(!video_config.min_encode_bitrate_bps) << "Setting min encode bitrate is not implemented for simulcast."; } } if (p->audio_config) { bool inserted = audio_labels.insert(p->audio_config->stream_label.value()).second; RTC_CHECK(inserted) << "Duplicate audio_config.stream_label=" << p->audio_config->stream_label.value(); // Check that if mode input file name specified only if mode is kFile. if (p->audio_config.value().mode == AudioConfig::Mode::kGenerated) { RTC_CHECK(!p->audio_config.value().input_file_name); } if (p->audio_config.value().mode == AudioConfig::Mode::kFile) { RTC_CHECK(p->audio_config.value().input_file_name); RTC_CHECK( test::FileExists(p->audio_config.value().input_file_name.value())) << p->audio_config.value().input_file_name.value() << " doesn't exist"; } } } if (has_simulcast) { RTC_CHECK_EQ(run_params.video_codecs.size(), 1) << "Only 1 video codec is supported when simulcast is enabled in at " << "least 1 video config"; } RTC_CHECK_GT(media_streams_count, 0) << "No media in the call."; } } // namespace webrtc_pc_e2e } // namespace webrtc
39.458128
80
0.661174
[ "vector" ]
dc0fa5ee66ee6945a8a4ccbf00a2c2fedb2111b0
8,953
cpp
C++
mcs/psc_tests/tamarin-redux/utils/sharkprof/log2s.cpp
sushihangover/PlayScript
a2b7c04e176ddb0ddbc16999e5a5902a1e15b563
[ "Apache-2.0" ]
20
2015-07-14T07:30:28.000Z
2021-11-12T07:41:34.000Z
avmplus/utils/sharkprof/log2s.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
83
2015-07-16T01:31:41.000Z
2016-01-13T02:15:47.000Z
avmplus/utils/sharkprof/log2s.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
10
2015-06-14T14:39:59.000Z
2021-11-12T07:41:35.000Z
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <inttypes.h> #include <stdio.h> #include <sys/mman.h> #include <stdarg.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <ctype.h> #include <dlfcn.h> #include <string> #include <vector> #include <map> #include <algorithm> static void warn(const char *tmpl, ...) { va_list ap; va_start(ap, tmpl); vfprintf(stderr, tmpl, ap); fputs("\n", stderr); va_end(ap); } static void fatal(const char *tmpl, ...) { va_list ap; va_start(ap, tmpl); vfprintf(stderr, tmpl, ap); fputs("\n", stderr); va_end(ap); exit(-1); } struct Chunk { uint32_t tag; uint32_t size; char data[0]; }; struct DebugInfo { const Chunk *info; uint64_t pc() const { return ((uint64_t *) info->data)[0]; } uint32_t tag() const { return info->tag; } std::string file() const { if (tag() != 'file') fatal("DebugInfo::file() called on non-file debug info"); return std::string(info->data + sizeof(uint64_t), info->size - sizeof(uint64_t)); } uint64_t line() const { if (tag() != 'line' ) fatal("DebugInfo::line() called on non-linedebug info"); return ((uint64_t *) info->data)[1]; } bool operator<(const DebugInfo &other) const { int64_t pcPad = pc() - other.pc(); if (pcPad) return pcPad < 0; if (tag() == 'file' && other.tag() != 'file') return true; return false; } }; struct MethBlock { const Chunk *meth; const Chunk *block; const Chunk *code; uint64_t start() const { return ((uint64_t *) block->data)[0]; } uint64_t end() const { return ((uint64_t *) block->data)[1]; } std::string name() const { return std::string(meth->data, meth->size); } const void *codeBytes() const { return code ? code->data : NULL; } const uint32_t codeLen() const { return code ? code->size : 0; } bool operator<(const MethBlock &other) const { return start() < other.start(); } }; static std::string quote(const std::string &s) { #ifdef __MACH__ std::string result = "\""; std::string::const_iterator i = s.begin(), e = s.end(); for (; i != e; i++) { if (*i != '\\' && isprint(*i)) result += *i; else { char buf[8]; sprintf(buf, "\\%03o", *i); result += buf; } } result += "\""; return result; #else #error foo #endif } int main(int argc, char **argv) { if (argc != 2) fatal("usage: %s inputLog", argv[0]); int fd = open(argv[1], O_RDONLY); if (fd < 0) fatal("couldn't open %s", argv[1]); off_t len = lseek(fd, 0, SEEK_END); const void *cur = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); const void *end = (char *) cur + len; if (cur == MAP_FAILED) fatal("couldn't mmap %s", argv[1]); const Chunk *base = NULL; const Chunk *meth = NULL; std::vector<MethBlock> blocks; std::vector<DebugInfo> debugInfos; int pad_count = 0; while (cur < end) { const Chunk &chunk = *(const Chunk *) cur; switch (chunk.tag) { default: warn("unknown tag %08x", chunk.tag); break; case 'base': base = &chunk; break; case 'meth': meth = &chunk; break; case 'blok': { if (!meth) fatal("'blok' tag without 'meth'"); MethBlock block; block.meth = meth; block.block = &chunk; block.code = NULL; blocks.push_back(block); } break; case 'code': { if (blocks.size() <= 0) fatal("'code' chunk without 'blok'"); blocks.back().code = &chunk; } break; case 'file': case 'line': { DebugInfo info = { &chunk }; debugInfos.push_back(info); } break; } cur = chunk.data + chunk.size; } printf(".text\n"); #ifdef __MACH__ printf(".align 12\n"); #else printf(".align 4096\n"); #endif printf(".globl __jitStart\n"); printf(".globl _jitStart\n"); printf("__jitStart:\n"); printf("_jitStart:\n"); printf(".align 0\n"); std::sort(blocks.begin(), blocks.end()); std::sort(debugInfos.begin(), debugInfos.end()); std::map<std::string, int> namesSeen; std::vector<MethBlock>::const_iterator i, e; std::vector<DebugInfo>::const_iterator di, de; if (!base) fatal("no 'base' found"); uint64_t textOffs = 0x1000; uint64_t textLen = 256 * 1024 * 1024; if (base->size <= sizeof(uint64_t)) fatal("base info too short"); char path[4096]; int path_len = base->size - sizeof(uint64_t); if (path_len >= sizeof(path)) fatal("path to base library too long"); memcpy(path, base->data + sizeof(uint64_t), path_len); path[path_len] = 0; void *hdl = dlopen(path, RTLD_NOW); if (!hdl) fatal("couldn't get info from base library %s", path); char *jit_start = (char*) dlsym(hdl, "_jitStart"); if (!jit_start) fatal("couldn't find _jitStart in base library"); Dl_info dlInfo; if (dladdr(jit_start, &dlInfo)) { if ((jit_start - (char *) dlInfo.dli_fbase) != textOffs) warn("_jitStart at unexpected location"); } else { warn("couldn't validate _jitStart location"); } char *jit_end = (char*) dlsym(hdl, "_jitEnd"); if (!jit_end) fatal("couldn't find _jitEnd in base library"); textLen = jit_end - jit_start; dlclose(hdl); uint64_t curAddr = *(uint64_t *) base->data + textOffs; uint64_t endAddr = curAddr + textLen; int dbgFile = 0; di = debugInfos.begin(); de = debugInfos.end(); for (i = blocks.begin(), e = blocks.end(); i != e; ++i) { int curDbgFile = 0; uint64_t block_start = i->start(); //### uint64_t block_end = i->end(); //### std::string name = i->name(); int seen = namesSeen[name]++; if (seen) { char buf[16]; sprintf(buf, " (%d)", seen); name += buf; } uint64_t pad = block_start - curAddr; if (pad) { printf("pad%d:\n", pad_count++); printf(".fill %lld,1,0xcc\n", pad); } curAddr += pad; while (di != de && di->pc() < curAddr) { warn("dropped debug info at %llx", di->pc()); di++; } printf("%s:\n", quote(name).c_str()); const void *code = i->codeBytes(); if (code) { uint32_t codeLen = i->codeLen(); if (codeLen != block_end - block_start) { printf("FAIL\n"); } while (codeLen) { while (di != de && di->pc() == curAddr) { switch (di->tag()) { default: warn("unknown debug tag %08x", di->tag()); break; case 'file': printf(".file %d %s\n", curDbgFile = ++dbgFile, quote(di->file()).c_str()); break; case 'line': if (curDbgFile) printf(".loc %d %lld 0\n", dbgFile, di->line()); break; } di++; } printf(".byte "); int nextDebug = (di == de) ? codeLen : di->pc() - curAddr; int nextDebugHere = (nextDebug > codeLen) ? codeLen : nextDebug; int atOnce = (nextDebugHere < 12) ? nextDebugHere : 12; while (atOnce--) { printf("0x%02x%s", *(const unsigned char *) code, atOnce ? ", " : "\n"); code = (const char *) code + 1; codeLen--; curAddr++; } } } } uint64_t endPad = endAddr - curAddr; if (endPad) { printf("pad%d:\n", pad_count++); printf(".fill %lld,1,0xcc\n", endPad); } printf(".globl __jitEnd\n"); printf(".globl _jitEnd\n"); printf("__jitEnd:\n"); printf("_jitEnd:\n"); return 0; }
24.067204
80
0.492907
[ "vector" ]
dc1368c58df84bdac84317339624d7b2788757fe
807
cpp
C++
test/snippet/range/view/convert.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
4
2018-03-09T09:37:51.000Z
2020-07-28T04:52:01.000Z
test/snippet/range/view/convert.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
test/snippet/range/view/convert.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
1
2018-03-09T09:37:54.000Z
2018-03-09T09:37:54.000Z
#include <seqan3/range/view/convert.hpp> #include <seqan3/alphabet/nucleotide/dna15.hpp> #include <seqan3/alphabet/nucleotide/dna5.hpp> #include <seqan3/std/ranges> using namespace seqan3; int main() { { //! [int_to_bool] // convert from int to bool std::vector<int> vec{7, 5, 0, 5, 0, 0, 4, 8, -3}; // pipe notation auto v = vec | view::convert<bool>; // == [1, 1, 0, 1, 0, 0, 1, 1, 1]; // function notation and immediate conversion to vector again std::vector<bool> v2(view::convert<bool>(vec)); // combinability auto v3 = vec | view::convert<bool> | std::view::reverse; // == [1, 1, 1, 0, 0, 1, 0, 1, 1]; //! [int_to_bool] (void) v; (void) v2; (void) v3; } { //! [15_to_5] dna15_vector vec2{"ACYGTN"_dna15}; auto v4 = vec2 | view::convert<dna5>; // == "ACNGTN"_dna5 //! [15_to_5] (void) v4; } }
20.692308
92
0.635688
[ "vector" ]
dc150296600f90b9b1d26666b54c50de05a8dae6
3,067
cc
C++
mindspore/lite/tools/converter/adapter/dpico/infer/dpico_recurrent_infer.cc
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/lite/tools/converter/adapter/dpico/infer/dpico_recurrent_infer.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/lite/tools/converter/adapter/dpico/infer/dpico_recurrent_infer.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 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 "infer/dpico_recurrent_infer.h" #include <iostream> #include <vector> #include <memory> #include "utils/log_adapter.h" #include "common/infer_util.h" #include "common/op_enum.h" #include "include/errorcode.h" #include "include/registry/register_kernel_interface.h" using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; namespace mindspore { namespace kernel { namespace { constexpr size_t kGateNum2 = 2; } // namespace std::shared_ptr<KernelInterface> DpicoRecurrentInferCreater() { std::shared_ptr<KernelInterface> infer = std::make_shared<DpicoRecurrentInterface>(); if (infer == nullptr) { MS_LOG(ERROR) << "make shared failed, infer is nullptr."; return nullptr; } return infer; } Status DpicoRecurrentInterface::Infer(std::vector<mindspore::MSTensor> *inputs, std::vector<mindspore::MSTensor> *outputs, const schema::Primitive *primitive, const kernel::Kernel *kernel) { auto status = dpico::CheckCustomInputOutput(inputs, outputs, primitive); if (status != RET_OK) { MS_LOG(ERROR) << "Check custom input output failed."; return kLiteError; } auto param = primitive->value_as_Custom(); if (param == nullptr) { MS_LOG(ERROR) << "param is nullptr"; return kLiteError; } if (param->type() == nullptr) { MS_LOG(ERROR) << "param->type() is nullptr"; return kLiteError; } if (inputs->size() < dpico::kDims3) { MS_LOG(ERROR) << "inputs size is invalid: " << inputs->size(); return kLiteError; } const auto &input = (*inputs)[0]; const auto &hidden_weight = (*inputs)[dpico::kInputIndex2]; auto &output = (*outputs)[0]; std::vector<int64_t> output_shape(input.Shape()); if (output_shape.size() != dpico::kDims3) { MS_LOG(ERROR) << "output_shape should be 3 dims, which is " << output_shape.size(); return kLiteError; } if (param->type()->str() != "BiLstm") { output_shape[0] = 1; // bidirectional ? 2 : 1 } else { output_shape[0] = kGateNum2; // bidirectional ? 2 : 1 } output_shape[dpico::kAxis2] = hidden_weight.Shape().at(0); output.SetShape(output_shape); return kSuccess; } REGISTER_CUSTOM_KERNEL_INTERFACE(DPICO, Rnn, DpicoRecurrentInferCreater) REGISTER_CUSTOM_KERNEL_INTERFACE(DPICO, Gru, DpicoRecurrentInferCreater) REGISTER_CUSTOM_KERNEL_INTERFACE(DPICO, BiLstm, DpicoRecurrentInferCreater) } // namespace kernel } // namespace mindspore
35.252874
116
0.698076
[ "shape", "vector" ]
dc15d0cb24e0a8df7052043643065db18ab4ab1a
886
cpp
C++
Algorithms/Sorting/Easy/Insertion-Sort-Part-1.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
Algorithms/Sorting/Easy/Insertion-Sort-Part-1.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
Algorithms/Sorting/Easy/Insertion-Sort-Part-1.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void printArray (const vector <int>& arr) { for (int i = 0; i < arr.size(); i++) { cout << arr.at(i); if (i != arr.size()-1) cout << ' '; } cout << endl; } void insertionSort1(int n, vector <int> arr) { int index = n-2; int e = arr.at(n-1); while (index >= 0) { if (arr.at(index) > e) { arr.at(index+1) = arr.at(index); printArray(arr); } else { arr.at(index+1) = e; printArray(arr); break; } if (index == 0) { arr.at(0) = e; printArray(arr); } index--; } } int main() { int n; cin >> n; vector<int> arr(n); for(int arr_i = 0; arr_i < n; arr_i++){ cin >> arr[arr_i]; } insertionSort1(n, arr); return 0; }
19.688889
46
0.430023
[ "vector" ]
dc1acd9e3ba09fd25567cec91e780c95b4307f27
2,543
hpp
C++
include/UnityEngine/Networking/UnityWebRequestMultimedia.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequestMultimedia.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequestMultimedia.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Networking namespace UnityEngine::Networking { // Forward declaring type: UnityWebRequest class UnityWebRequest; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: AudioType struct AudioType; } // Completed forward declares // Type namespace: UnityEngine.Networking namespace UnityEngine::Networking { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Networking.UnityWebRequestMultimedia // [TokenAttribute] Offset: FFFFFFFF class UnityWebRequestMultimedia : public ::Il2CppObject { public: // Creating value type constructor for type: UnityWebRequestMultimedia UnityWebRequestMultimedia() noexcept {} // static public UnityEngine.Networking.UnityWebRequest GetAudioClip(System.String uri, UnityEngine.AudioType audioType) // Offset: 0x1E4099C static UnityEngine::Networking::UnityWebRequest* GetAudioClip(::Il2CppString* uri, UnityEngine::AudioType audioType); }; // UnityEngine.Networking.UnityWebRequestMultimedia #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Networking::UnityWebRequestMultimedia*, "UnityEngine.Networking", "UnityWebRequestMultimedia"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::Networking::UnityWebRequestMultimedia::GetAudioClip // Il2CppName: GetAudioClip template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Networking::UnityWebRequest* (*)(::Il2CppString*, UnityEngine::AudioType)>(&UnityEngine::Networking::UnityWebRequestMultimedia::GetAudioClip)> { static const MethodInfo* get() { static auto* uri = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* audioType = &::il2cpp_utils::GetClassFromName("UnityEngine", "AudioType")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Networking::UnityWebRequestMultimedia*), "GetAudioClip", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{uri, audioType}); } };
50.86
227
0.745576
[ "vector" ]
dc1c70159bc76c64062522c1de97951c3f66bb31
7,527
cpp
C++
depends/libfqfft/libfqfft/tests/evaluation_domain_test.cpp
alittlehorse/osprey
22f290a7de3413a847e3dc33c96328752cc37f47
[ "MIT" ]
5
2021-03-04T08:28:38.000Z
2021-04-20T11:50:40.000Z
depends/libfqfft/libfqfft/tests/evaluation_domain_test.cpp
alittlehorse/osprey
22f290a7de3413a847e3dc33c96328752cc37f47
[ "MIT" ]
null
null
null
depends/libfqfft/libfqfft/tests/evaluation_domain_test.cpp
alittlehorse/osprey
22f290a7de3413a847e3dc33c96328752cc37f47
[ "MIT" ]
1
2021-05-22T15:50:15.000Z
2021-05-22T15:50:15.000Z
/** ***************************************************************************** * @author This file is part of libfqfft, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #include <memory> #include <vector> #include <gtest/gtest.h> #include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp> #include <stdint.h> #include <depends/libfqfft/libfqfft/evaluation_domain/domains/arithmetic_sequence_domain.hpp> #include <depends/libfqfft/libfqfft/evaluation_domain/domains/basic_radix2_domain.hpp> #include <depends/libfqfft/libfqfft/evaluation_domain/domains/extended_radix2_domain.hpp> #include <depends/libfqfft/libfqfft/evaluation_domain/domains/geometric_sequence_domain.hpp> #include <depends/libfqfft/libfqfft/evaluation_domain/domains/step_radix2_domain.hpp> #include <depends/libfqfft/libfqfft/polynomial_arithmetic/naive_evaluate.hpp> #include <depends/libfqfft/libfqfft/tools/exceptions.hpp> namespace libfqfft { /** * Note: Templatized type referenced with TypeParam (instead of canonical FieldT) * https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#typed-tests */ template <typename T> class EvaluationDomainTest : public ::testing::Test { protected: virtual void SetUp() { libff::mnt4_pp::init_public_params(); } }; typedef ::testing::Types<libff::Fr<libff::mnt4_pp>, libff::Double> FieldT; /* List Extend Here */ TYPED_TEST_CASE(EvaluationDomainTest, FieldT); TYPED_TEST(EvaluationDomainTest, FFT) { const size_t m = 4; std::vector<TypeParam> f = { 2, 5, 3, 8 }; std::shared_ptr<evaluation_domain<TypeParam> > domain; for (int key = 0; key < 5; key++) { try { if (key == 0) domain.reset(new basic_radix2_domain<TypeParam>(m)); else if (key == 1) domain.reset(new extended_radix2_domain<TypeParam>(m)); else if (key == 2) domain.reset(new step_radix2_domain<TypeParam>(m)); else if (key == 3) domain.reset(new geometric_sequence_domain<TypeParam>(m)); else if (key == 4) domain.reset(new arithmetic_sequence_domain<TypeParam>(m)); std::vector<TypeParam> a(f); domain->FFT(a); std::vector<TypeParam> idx(m); for (size_t i = 0; i < m; i++) { idx[i] = domain->get_domain_element(i); } for (size_t i = 0; i < m; i++) { TypeParam e = evaluate_polynomial(m, f, idx[i]); EXPECT_TRUE(e == a[i]); } } catch(DomainSizeException &e) { printf("%s - skipping\n", e.what()); } catch(InvalidSizeException &e) { printf("%s - skipping\n", e.what()); } } } TYPED_TEST(EvaluationDomainTest, InverseFFTofFFT) { const size_t m = 4; std::vector<TypeParam> f = { 2, 5, 3, 8 }; std::shared_ptr<evaluation_domain<TypeParam> > domain; for (int key = 0; key < 5; key++) { try { if (key == 0) domain.reset(new basic_radix2_domain<TypeParam>(m)); else if (key == 1) domain.reset(new extended_radix2_domain<TypeParam>(m)); else if (key == 2) domain.reset(new step_radix2_domain<TypeParam>(m)); else if (key == 3) domain.reset(new geometric_sequence_domain<TypeParam>(m)); else if (key == 4) domain.reset(new arithmetic_sequence_domain<TypeParam>(m)); std::vector<TypeParam> a(f); domain->FFT(a); domain->iFFT(a); for (size_t i = 0; i < m; i++) { EXPECT_TRUE(f[i] == a[i]); } } catch(const DomainSizeException &e) { printf("%s - skipping\n", e.what()); } catch(const InvalidSizeException &e) { printf("%s - skipping\n", e.what()); } } } TYPED_TEST(EvaluationDomainTest, InverseCosetFFTofCosetFFT) { const size_t m = 4; std::vector<TypeParam> f = { 2, 5, 3, 8 }; TypeParam coset = TypeParam::multiplicative_generator; std::shared_ptr<evaluation_domain<TypeParam> > domain; for (int key = 0; key < 3; key++) { try { if (key == 0) domain.reset(new basic_radix2_domain<TypeParam>(m)); else if (key == 1) domain.reset(new extended_radix2_domain<TypeParam>(m)); else if (key == 2) domain.reset(new step_radix2_domain<TypeParam>(m)); else if (key == 3) domain.reset(new geometric_sequence_domain<TypeParam>(m)); else if (key == 4) domain.reset(new arithmetic_sequence_domain<TypeParam>(m)); std::vector<TypeParam> a(f); domain->cosetFFT(a, coset); domain->icosetFFT(a, coset); for (size_t i = 0; i < m; i++) { EXPECT_TRUE(f[i] == a[i]); } } catch(const DomainSizeException &e) { printf("%s - skipping\n", e.what()); } catch(const InvalidSizeException &e) { printf("%s - skipping\n", e.what()); } } } TYPED_TEST(EvaluationDomainTest, LagrangeCoefficients) { const size_t m = 8; TypeParam t = TypeParam(10); std::shared_ptr<evaluation_domain<TypeParam> > domain; for (int key = 0; key < 5; key++) { try { if (key == 0) domain.reset(new basic_radix2_domain<TypeParam>(m)); else if (key == 1) domain.reset(new extended_radix2_domain<TypeParam>(m)); else if (key == 2) domain.reset(new step_radix2_domain<TypeParam>(m)); else if (key == 3) domain.reset(new geometric_sequence_domain<TypeParam>(m)); else if (key == 4) domain.reset(new arithmetic_sequence_domain<TypeParam>(m)); std::vector<TypeParam> a; a = domain->evaluate_all_lagrange_polynomials(t); std::vector<TypeParam> d(m); for (size_t i = 0; i < m; i++) { d[i] = domain->get_domain_element(i); } for (size_t i = 0; i < m; i++) { TypeParam e = evaluate_lagrange_polynomial(m, d, t, i); printf("%ld == %ld\n", e.as_ulong(), a[i].as_ulong()); EXPECT_TRUE(e == a[i]); } } catch(const DomainSizeException &e) { printf("%s - skipping\n", e.what()); } catch(const InvalidSizeException &e) { printf("%s - skipping\n", e.what()); } } } TYPED_TEST(EvaluationDomainTest, ComputeZ) { const size_t m = 8; TypeParam t = TypeParam(10); std::shared_ptr<evaluation_domain<TypeParam> > domain; for (int key = 0; key < 5; key++) { try { if (key == 0) domain.reset(new basic_radix2_domain<TypeParam>(m)); else if (key == 1) domain.reset(new extended_radix2_domain<TypeParam>(m)); else if (key == 2) domain.reset(new step_radix2_domain<TypeParam>(m)); else if (key == 3) domain.reset(new geometric_sequence_domain<TypeParam>(m)); else if (key == 4) domain.reset(new arithmetic_sequence_domain<TypeParam>(m)); TypeParam a; a = domain->compute_vanishing_polynomial(t); TypeParam Z = TypeParam::one(); for (size_t i = 0; i < m; i++) { Z *= (t - domain->get_domain_element(i)); } EXPECT_TRUE(Z == a); } catch(const DomainSizeException &e) { printf("%s - skipping\n", e.what()); } catch(const InvalidSizeException &e) { printf("%s - skipping\n", e.what()); } } } } // libfqfft
31.493724
99
0.588149
[ "vector" ]
dc21348c603a176cec30fe094d6fad6683c4853b
17,709
cpp
C++
src/PolylineSegmentedPath.cpp
cgrebeld/opensteerpy
25adfc50bed808d516ab30656d4a86634f70c532
[ "MIT" ]
3
2015-02-22T02:27:53.000Z
2019-06-25T21:05:31.000Z
src/PolylineSegmentedPath.cpp
onedayitwillmake/OpenSteerMirror
51a614bb5c62ff7e02514e55a7148cd4d67c67a1
[ "Unlicense", "MIT" ]
null
null
null
src/PolylineSegmentedPath.cpp
onedayitwillmake/OpenSteerMirror
51a614bb5c62ff7e02514e55a7148cd4d67c67a1
[ "Unlicense", "MIT" ]
null
null
null
/** * OpenSteer -- Steering Behaviors for Autonomous Characters * * Copyright (c) 2002-2005, Sony Computer Entertainment America * Original author: Craig Reynolds <craig_reynolds@playstation.sony.com> * * 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. * * * @author Bjoern Knafla <bknafla@uni-kassel.de> */ #include "OpenSteer/PolylineSegmentedPath.h" // Include std::accumulate #include <numeric> // Include std::swap, std::adjacent_find #include <algorithm> // Include assert #include <cassert> // Include OpenSteer::Vec3 #include "OpenSteer/Vec3.h" // Include OpenSteer::mapPointToPathway, OpenSteer::mapDistanceToPointOnPathCenterLine #include "OpenSteer/QueryPathAlike.h" // Include OpenSteer::PointToPathMapping, OpenSteer::PathDistanceToPointMapping, OpenSteer::PointToPathDistanceMapping #include "OpenSteer/QueryPathAlikeMappings.h" // Include OpenSteer::HasNoRadius #include "OpenSteer/QueryPathAlikeUtilities.h" // Include OpenSteer::clamp, OpenSteer::shrinkToFit #include "OpenSteer/Utilities.h" namespace { typedef OpenSteer::SegmentedPath::size_type size_type; typedef std::vector< OpenSteer::Vec3 > Vec3Container; typedef std::vector< float > FloatContainer; /** * Recalculates the segment tangent and length for segment @a segmentIndex. * * @attention @a segmentTangents and @a segmentLengths must have the right * size. */ void updateSegmentTangentAndLength( size_type segmentIndex, Vec3Container const& points , Vec3Container& segmentTangents, FloatContainer& segmentLengths ) { assert( ( ( segmentIndex + 1 ) < points.size() ) && "Not enough points for segment segmentIndex." ); assert( segmentIndex < segmentTangents.size() && "segmentIndex out of range." ); assert( segmentTangents.size() == segmentLengths.size() && "segmentTangents and segmentLengths must have the same size." ); OpenSteer::Vec3 tangent = points[ segmentIndex + 1 ] - points[ segmentIndex ]; float const length = tangent.length(); assert( ! OpenSteer::isZero( length ) && "Segments must have lengths greater than 0." ); tangent /= length; segmentTangents[ segmentIndex ] = tangent; segmentLengths[ segmentIndex] = length; } /** * Helper function to calucate the segment tangent and lengths * in the given range. * * @param points points defining the path. * @param segmentTangents container to store the calculated segment * tangents. Must have the right size. * @param segmentLengths container to store the calculated segment lengths. * Must have the right size. * @param firstChangedPointIndex the first point that changed. Segments have * to be updated starting with it. * @param numOfPoints number of points that changed beginning with * @a startIndex. * @param isCyclic Is the path cyclic or not. * */ void updateTangentsAndLengths( Vec3Container const& points , Vec3Container& segmentTangents, FloatContainer& segmentLengths, size_type firstChangedPointIndex, size_type numOfPoints, bool isCyclic ) { assert( 0 < numOfPoints && "Only call if points have really changed." ); assert( 1 < points.size() && "Two points are needed for a segment." ); assert( points.size() == segmentTangents.size() + 1 && "Two points are needed for one segment, therefore there must be one segment less than points." ); assert( segmentTangents.size() == segmentLengths.size() && "segmentTangents and segmentLengths must have the same size." ); // Other assertions aren't tested because the function should only be // called by other functions that guarantee correctness of the // parameters. // The segment with end point @a firstChangedPointIndex has also // changed. Beware from range underflow by subtraction. size_type firstSegmentIndex = firstChangedPointIndex; if ( 0 < firstSegmentIndex ) { firstSegmentIndex -= 1; } // The last segment to update has the last changed point as its start // point. This only holds true if the last changed point isn't the last // point. // lastSegmentIndex is one greater than the real last segment to update // like the last iterators in the stl. size_type lastSegmentIndex = firstChangedPointIndex + numOfPoints; lastSegmentIndex = OpenSteer::clamp( lastSegmentIndex, static_cast< size_t >( 0 ), segmentTangents.size() ); for ( size_type i = firstSegmentIndex; i < lastSegmentIndex; ++i ) { updateSegmentTangentAndLength( i, points, segmentTangents, segmentLengths ); } // If path is cyclic and the first point changed and the cycle closing // segment hasn't been updated update it now. if ( isCyclic && ( 0 == firstSegmentIndex ) && ! ( lastSegmentIndex == segmentTangents.size() ) ) { updateSegmentTangentAndLength( segmentTangents.size() - 1, points, segmentTangents, segmentLengths ); } } /** * Checks that no adjacent points are equal. Checks the first and last * point if the path is cyclic, too. */ template< typename Iterator > bool adjacentPathPointsDifferent( Iterator first, Iterator last, bool closedCycle ) { assert( last - first > 1 && "A path needs at least two waypoints." ); if ( last != std::adjacent_find( first, last ) ) { return false; } if ( closedCycle ) { Iterator before_last( first ); std::advance( before_last, last - first - 1 ); return *first == *before_last; } return true; } } // anonymous namespace OpenSteer::PolylineSegmentedPath::PolylineSegmentedPath() : points_( 0 ), segmentTangents_( 0 ), segmentLengths_( 0 ), closedCycle_( false ) { } OpenSteer::PolylineSegmentedPath::PolylineSegmentedPath( size_type numOfPoints, Vec3 const newPoints[], bool closedCycle ) : points_( 0 ), segmentTangents_( 0 ), segmentLengths_( 0 ), closedCycle_( closedCycle ) { setPath( numOfPoints, newPoints, closedCycle ); } OpenSteer::PolylineSegmentedPath::PolylineSegmentedPath( PolylineSegmentedPath const& other ) : SegmentedPath( other ), points_( other.points_ ), segmentTangents_( other.segmentTangents_ ), segmentLengths_( other.segmentLengths_ ), closedCycle_( other.closedCycle_ ) { // Nothing to do. } OpenSteer::PolylineSegmentedPath::~PolylineSegmentedPath() { // Nothing to do. } OpenSteer::PolylineSegmentedPath& OpenSteer::PolylineSegmentedPath::operator=( PolylineSegmentedPath other ) { swap( other ); return *this; } void OpenSteer::PolylineSegmentedPath::swap( PolylineSegmentedPath& other ) { points_.swap( other.points_ ); segmentTangents_.swap( other.segmentTangents_ ); segmentLengths_.swap( other.segmentLengths_ ); std::swap( closedCycle_, other.closedCycle_ ); } void OpenSteer::PolylineSegmentedPath::setPath( size_type numOfPoints, Vec3 const newPoints[], bool closedCycle ) { assert( 1 < numOfPoints && "Path must have at least two distinct points." ); // While testing say that no cyclus is used because the first point hasn't // been copied to the back. assert( adjacentPathPointsDifferent( newPoints, newPoints + numOfPoints, false ) && "Adjacent path points must be different." ); closedCycle_ = closedCycle; size_type numberOfPoints = numOfPoints; if ( closedCycle_ ) { ++numberOfPoints; } points_.reserve( numberOfPoints ); segmentTangents_.resize( numberOfPoints - 1 ); segmentLengths_.resize( numberOfPoints - 1 ); points_.assign( newPoints, newPoints + numOfPoints ); if ( closedCycle_ ) { points_.push_back( points_[ 0 ] ); } updateTangentsAndLengths( points_ , segmentTangents_, segmentLengths_, 0, numOfPoints, closedCycle_ ); shrinkToFit( points_ ); shrinkToFit( segmentTangents_ ); shrinkToFit( segmentLengths_ ); } void OpenSteer::PolylineSegmentedPath::movePoints( size_type startIndex, size_type numOfPoints, Vec3 const newPoints[] ) { assert( ( startIndex < ( pointCount() - ( isCyclic() ? 1 : 0 ) ) ) && "startIndex must be inside index range." ); assert( ( ( startIndex + numOfPoints ) <= ( pointCount() - ( isCyclic() ? 1 : 0 ) ) ) && "The max. index of a point to set must be inside the index range." ); // Update the point positions. // @todo Remove this line size_type const pathPointCount = pointCount(); for ( size_type i = 0; i < numOfPoints; ++i ) { points_[ startIndex + i ] = newPoints[ i ]; } // If the first point is changed and the path is cyclic also change the // last point, which is just a copy of the first point. if ( isCyclic() && ( 0 == startIndex ) ) { points_.back() = points_.front(); } // Recalculate the tangents and lengths. updateTangentsAndLengths( points_, segmentTangents_, segmentLengths_, startIndex, numOfPoints, isCyclic() ); assert( adjacentPathPointsDifferent( points_.begin(), points_.end(), isCyclic() ) && "Adjacent path points must be different." ); } bool OpenSteer::PolylineSegmentedPath::isValid() const { return pointCount() > 1; } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::mapPointToPath (const Vec3& point, Vec3& tangent, float& outside) const { PointToPathMapping mapping; mapPointToPathAlike( *this, point, mapping ); tangent = mapping.tangent; outside = mapping.distancePointToPath; return mapping.pointOnPathCenterLine; } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::mapPathDistanceToPoint (float pathDistance) const { PathDistanceToPointMapping mapping; mapDistanceToPathAlike( *this, pathDistance, mapping ); return mapping.pointOnPathCenterLine; } float OpenSteer::PolylineSegmentedPath::mapPointToPathDistance (const Vec3& point) const { PointToPathDistanceMapping mapping; mapPointToPathAlike( *this, point, mapping ); return mapping.distanceOnPath; } bool OpenSteer::PolylineSegmentedPath::isCyclic() const { return closedCycle_; } float OpenSteer::PolylineSegmentedPath::length() const { return std::accumulate( segmentLengths_.begin(), segmentLengths_.end(), 0.0f ); } OpenSteer::SegmentedPath::size_type OpenSteer::PolylineSegmentedPath::pointCount() const { return points_.size(); } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::point( size_type pointIndex ) const { assert( pointIndex < pointCount() && "pointIndex out of range." ); return points_[ pointIndex ]; } OpenSteer::PolylineSegmentedPath::size_type OpenSteer::PolylineSegmentedPath::segmentCount() const { return segmentTangents_.size(); } float OpenSteer::PolylineSegmentedPath::segmentLength( size_type segmentIndex ) const { assert( segmentIndex < segmentCount() && "segmentIndex out of range." ); return segmentLengths_[ segmentIndex ]; } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::segmentStart( size_type segmentIndex ) const { assert( segmentIndex < segmentCount() && "segmentIndex out of range." ); assert( segmentIndex < pointCount() && "The max. index of a point must be inside range." ); return points_[ segmentIndex ]; } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::segmentEnd( size_type segmentIndex ) const { assert( segmentIndex < segmentCount() && "segmentIndex out of range." ); assert( segmentIndex + 1< pointCount() && "The max. index of a point must be inside range." ); return points_[ segmentIndex + 1 ]; } float OpenSteer::PolylineSegmentedPath::mapPointToSegmentDistance( size_type segmentIndex, Vec3 const& point ) const { assert( segmentIndex < segmentCount() && "segmentIndex is out of range." ); Vec3 const segmentStartToPoint( point - points_[ segmentIndex ] ); float const distance = segmentStartToPoint.dot( segmentTangents_[ segmentIndex ] ); return clamp( distance, 0.0f, segmentLengths_[ segmentIndex ] ); } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::mapSegmentDistanceToPoint( size_type segmentIndex, float segmentDistance ) const { assert( segmentIndex < segmentCount() && "segmentIndex is out of range." ); float const segmentLength = segmentLengths_[ segmentIndex ]; /* * bk: remove behavior that treats negative numbers as distances beginning * from the end of the segment if ( 0.0f > segmentDistance ) { segmentDistance += segmentLength; } */ segmentDistance = clamp( segmentDistance, 0.0f, segmentLength ); return segmentTangents_[ segmentIndex ] * segmentDistance + points_[ segmentIndex ]; } OpenSteer::Vec3 OpenSteer::PolylineSegmentedPath::mapSegmentDistanceToTangent( size_type segmentIndex, float ) const { assert( segmentIndex < segmentCount() && "segmentIndex is out of range." ); return segmentTangents_[ segmentIndex ]; } void OpenSteer::PolylineSegmentedPath::mapDistanceToSegmentPointAndTangent( size_type segmentIndex, float segmentDistance, Vec3& pointOnPath, Vec3& tangent ) const { assert( segmentIndex < segmentCount() && "segmentIndex is out of range." ); float const segmentLength = segmentLengths_[ segmentIndex ]; /* * bk: remove behavior that treats negative numbers as distances beginning * from the end of the segment if ( 0.0f > segmentDistance ) { segmentDistance += segmentLength; } */ segmentDistance = clamp( segmentDistance, 0.0f, segmentLength ); pointOnPath = segmentTangents_[ segmentIndex ] * segmentDistance + points_[ segmentIndex ]; tangent = segmentTangents_[ segmentIndex ]; } void OpenSteer::PolylineSegmentedPath::mapPointToSegmentDistanceAndPointAndTangent( size_type segmentIndex, Vec3 const& point, float& distance, Vec3& pointOnPath, Vec3& tangent ) const { assert( segmentIndex < segmentCount() && "segmentIndex is out of range." ); Vec3 const segmentStartPoint = points_[ segmentIndex ]; Vec3 const segmentStartToPoint( point - segmentStartPoint ); tangent = segmentTangents_[ segmentIndex ]; distance = segmentStartToPoint.dot( tangent ); distance = clamp( distance, 0.0f, segmentLengths_[ segmentIndex ] ); pointOnPath = tangent * distance + segmentStartPoint; }
34.386408
176
0.61737
[ "vector" ]
dc266a8b49d924b67df6ddf4cda2d77005d2c0cc
6,484
cpp
C++
src/lib/TableFunction.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
7
2020-12-16T08:23:31.000Z
2022-01-15T22:56:26.000Z
src/lib/TableFunction.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
null
null
null
src/lib/TableFunction.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
2
2020-12-16T08:23:34.000Z
2022-01-10T21:05:54.000Z
/* * TableFunction.cpp * * Author: * Oleg Kalashev * * Copyright (c) 2020 Institute for Nuclear Research, RAS * * 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 "PrecisionTests.h" #include "TableFunction.h" namespace Utils { template<typename X> X LogScaleX<X>::ToScale(X aX) { ASSERT(aX>=0); return aX>0?log(aX):-1000; } template<typename X> X LogScaleX<X>::FromScale(X aXprime) { return exp(aXprime); } template<typename X> IScale<X>* LogScaleX<X>::Clone() const { return new LogScaleX(); } template class LogScaleX<double>; template class LogScaleX<long double>; template<typename X> void TableFunctionX<X>::Init() { ASSERT(m_x.size()==m_y.size() && m_x.size()>1); fXmin = m_x[0]; fXmax = m_x[m_x.size()-1]; } template<typename X> TableFunctionX<X>::TableFunctionX(const std::vector<X>& _x, const std::vector<X>& _y, X _leftVal, X _rightVal): m_x(_x), m_y(_y), m_leftVal(_leftVal), m_rightVal(_rightVal) { Init(); } template<typename X> TableFunctionX<X>::TableFunctionX(const std::vector<X>& _x, const std::vector<X>& _y, IScale<X>* aXscale, IScale<X>* aYscale, X _leftVal, X _rightVal): fCloneX(_x), fCloneY(_y), m_x(fCloneX), m_y(fCloneY), m_leftVal(_leftVal), m_rightVal(_rightVal), fXscale(aXscale), fYscale(aYscale) { Init(); int iMax = _x.size(); for(int i=0; i<iMax; i++) { if(aXscale) fCloneX[i] = aXscale->ToScale(_x[i]); if(aYscale) fCloneY[i] = aYscale->ToScale(_y[i]); } } template<typename X> TableFunctionX<X>::TableFunctionX(TableReaderX<X>* aReader, X _leftVal, X _rightVal): m_x(aReader->getColumn(0)), m_y(aReader->getColumn(1)), m_leftVal(_leftVal), m_rightVal(_rightVal), fTable(aReader) { Init(); } template<typename X> TableFunctionX<X>::TableFunctionX(const TableFunctionX<X>& aTableFunction): fCloneX(aTableFunction.m_x), fCloneY(aTableFunction.m_y), m_x(fCloneX), m_y(fCloneY), m_leftVal(aTableFunction.m_leftVal), m_rightVal(aTableFunction.m_rightVal), fXscale(aTableFunction.fXscale==0 ? 0 : aTableFunction.fXscale->Clone()), fYscale(aTableFunction.fYscale==0 ? 0 : aTableFunction.fYscale->Clone()), fXmin(aTableFunction.fXmin), fXmax(aTableFunction.fXmax) { } template<typename X> int TableFunctionX<X>::FindLeftX(const std::vector<X>&aSet, X xValue) { int right = aSet.size() - 1; ASSERT(right>=1); if((xValue > aSet[right]) || xValue < aSet[0]) return -1; int left = 0; for(int i=(left+right)/2;right-left>1;i=(left+right)/2) { if(xValue > aSet[i]) left=i; else right=i; } ASSERT((right - left) == 1); return left; } template<typename X> int TableFunctionX<X>::FindLeftX(X xValue) const { return FindLeftX(m_x, xValue); } template<typename X> X TableFunctionX<X>::f(X _x) const { if(_x<fXmin) return m_leftVal; if(_x>fXmax) return m_rightVal; X scaledX = fXscale ? fXscale->ToScale(_x) : _x; X scaledY = f_scaled(scaledX); return fYscale ? fYscale->FromScale(scaledY) : scaledY; } template<typename X> void TableFunctionX<X>::SetAutoLimits() { m_leftVal = fYscale ? fYscale->FromScale(m_y[0]) : m_y[0]; m_rightVal = fYscale ? fYscale->FromScale(m_y[m_y.size()-1]) : m_y[m_y.size()-1]; } template<typename X> X TableFunctionX<X>::Xmin() const { return m_leftVal == 0. ? fXmin : -DBL_MAX; } template<typename X> X TableFunctionX<X>::Xmax() const { return m_rightVal == 0. ? fXmax : DBL_MAX; } template<typename X> bool TableFunctionX<X>::InTableRange(X aArg) const { return aArg>=fXmin && aArg<=fXmax; } template<typename X> void TableFunctionX<X>::Print(std::ostream& aOut, X aXcoef, X aYcoef) { int iMax = m_x.size(); aOut << "# " << "leftVal=" << aYcoef*m_leftVal << " ; rightVal=" << aYcoef*m_rightVal << " ; Xmin=" << aXcoef*Xmin() << " ; Xmax=" << aXcoef*Xmax() << "\n"; for(int i=0; i<iMax; i++) { X xScaled = m_x[i]; X yScaled = m_y[i]; X x = fXscale ? fXscale->FromScale(xScaled) : xScaled; X y = fYscale ? fYscale->FromScale(yScaled) : yScaled; aOut << aXcoef*x << "\t" << aYcoef*y << "\t" << xScaled << "\t" << yScaled << "\n"; } } template class TableFunctionX<double>; template class TableFunctionX<long double>; template<typename X> X LinearFuncX<X>::f_scaled(X _x) const { int i = TableFunctionX<X>::FindLeftX(_x); if(i<0) return (_x < this->m_x[0])?this->m_leftVal:this->m_rightVal; X x1 = this->m_x[i]; X y1 = this->m_y[i]; X y2 = this->m_y[i+1]; X x2 = this->m_x[i+1]; return y1+(y2-y1)/(x2-x1)*(_x - x1); } template class LinearFuncX<double>; template class LinearFuncX<long double>; GSLTableFunc::~GSLTableFunc() { if(fSpline) gsl_spline_free (fSpline); if(fAcc) gsl_interp_accel_free (fAcc); } double GSLTableFunc::f_scaled(double _x) const { return gsl_spline_eval (fSpline, _x, fAcc); } void GSLTableFunc::Init(const gsl_interp_type * aInterpType) { fAcc = gsl_interp_accel_alloc (); fSpline = gsl_spline_alloc (aInterpType, m_x.size()); try{ gsl_spline_init (fSpline, &m_x[0], &m_y[0], m_x.size()); } catch(Exception* ex) { std::cerr << "GSLTableFunc::Init() error\n input data:\n"; Print(std::cerr); throw ex; } } #ifdef USE_MPFR template<> mpfr::mpreal LogScaleX<mpfr::mpreal>::FromScale(mpfr::mpreal aXprime) { return mpfr::exp(aXprime); } template<> mpfr::mpreal LogScaleX<mpfr::mpreal>::ToScale(mpfr::mpreal aX) { ASSERT(aX>=0); return aX>0?mpfr::log(aX):-1000; } template class TableFunctionX<mpfr::mpreal>; template class LinearFuncX<mpfr::mpreal>; #endif } /* namespace Utils */
25.229572
172
0.694479
[ "vector" ]
dc287789f4320368026c9e311d09799060fd385f
9,428
cpp
C++
src/MPC.cpp
philippmarcus/CarND-MPC-Project
078d93263e65ee1e000918e4b454eaed5cf7c2e3
[ "MIT" ]
null
null
null
src/MPC.cpp
philippmarcus/CarND-MPC-Project
078d93263e65ee1e000918e4b454eaed5cf7c2e3
[ "MIT" ]
null
null
null
src/MPC.cpp
philippmarcus/CarND-MPC-Project
078d93263e65ee1e000918e4b454eaed5cf7c2e3
[ "MIT" ]
null
null
null
#include "MPC.h" #include <cppad/cppad.hpp> #include <cppad/ipopt/solve.hpp> #include <iostream> #include <string> #include <vector> #include <exception> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "helpers.h" using CppAD::AD; using Eigen::VectorXd; /** * TODO: Set the timestep length and duration */ size_t N = 20; double dt = 0.1; // start positions for the state variables uint x_start = 0; uint y_start = x_start + N; uint v_start = y_start + N; uint psi_start = v_start + N; uint cte_start = psi_start + N; uint epsi_start = cte_start + N; // Start positions for the actuators uint delta_start = epsi_start + N; uint a_start = delta_start + N - 1; // This value assumes the model presented in the classroom is used. // // It was obtained by measuring the radius formed by running the vehicle in the // simulator around in a circle with a constant steering angle and velocity on // a flat terrain. // // Lf was tuned until the the radius formed by the simulating the model // presented in the classroom matched the previous radius. // // This is the length from front to CoG that has a similar radius. const double Lf = 2.67; AD<double> v_ref = 50; class FG_eval { public: // Fitted polynomial coefficients VectorXd coeffs; FG_eval(VectorXd coeffs) { this->coeffs = coeffs; } typedef CPPAD_TESTVECTOR(AD<double>) ADvector; void operator()(ADvector& fg, const ADvector& vars) { /** * TODO: implement MPC * `fg` is a vector of the cost constraints, `vars` is a vector of variable * values (state & actuators) * NOTE: You'll probably go back and forth between this function and * the Solver function below. */ // Define the cost function fg[0] = 0; // Cost for CTE, psi error and velocity for (int t = 0; t < N; ++t) { fg[0] += 20. * CppAD::pow(vars[cte_start + t], 2); fg[0] += 20. * CppAD::pow(vars[epsi_start + t], 2); fg[0] += 1.5 * CppAD::pow(vars[v_start + t] - v_ref, 2); // 0.0001 worked without latency } // Punish changes in the steering angle - was not needed without latency for (int t=1; t < N; ++t) { fg[0] += 600. * CppAD::pow(vars[delta_start + t] - vars[delta_start + t - 1], 2); fg[0] += 20. * CppAD::pow(vars[delta_start + t - 1], 2); } // Initial constraints fg[1 + x_start] = vars[x_start]; fg[1 + y_start] = vars[y_start]; fg[1 + psi_start] = vars[psi_start]; fg[1 + v_start] = vars[v_start]; fg[1 + cte_start] = vars[cte_start]; fg[1 + epsi_start] = vars[epsi_start]; // Set up the constraints for(int t = 1; t < N; ++t){ // Values for t (leading +1 needed as fg vector starts with cost at fg[0]) CppAD::AD<double> x0 = vars[x_start + t - 1]; CppAD::AD<double> y0 = vars[y_start + t - 1]; CppAD::AD<double> v0 = vars[v_start + t - 1]; CppAD::AD<double> psi0 = vars[psi_start + t - 1]; CppAD::AD<double> cte0 = vars[cte_start + t - 1]; CppAD::AD<double> epsi0 = vars[epsi_start + t - 1]; CppAD::AD<double> delta0 = vars[delta_start + t - 1]; CppAD::AD<double> a0 = vars[a_start + t - 1]; // Values for t+1 CppAD::AD<double> x1 = vars[x_start + t]; CppAD::AD<double> y1 = vars[y_start + t]; CppAD::AD<double> v1 = vars[v_start + t]; CppAD::AD<double> psi1 = vars[psi_start + t]; CppAD::AD<double> cte1 = vars[cte_start + t]; CppAD::AD<double> epsi1 = vars[epsi_start + t]; // Function value and its derivative AD<double> f0 = coeffs[0] + coeffs[1] * x0 + coeffs[2] * x0*x0 + coeffs[3] * x0*x0*x0; AD<double> f0_diff = coeffs[1]+ 2* coeffs[2] * x0 + 3 * coeffs[3] * x0*x0; AD<double> psides0 = CppAD::atan(f0_diff); // Defining constraint values to compare with the prev. defined ones // As we defined the contraints to be 0, the solver needs to // finde such delta and a values that the following fg values // match 0 for all states after the initial one. fg[1 + x_start + t] = x1 - (x0 + v0 * CppAD::cos(psi0) * dt); fg[1 + y_start + t] = y1 - (y0 + v0 * CppAD::sin(psi0) * dt); fg[1 + v_start + t] = v1 - (v0 + a0 * dt); fg[1 + psi_start + t] = psi1 - (psi0 - (v0/Lf) * delta0 * dt); fg[1 + cte_start + t] = cte1 - ((f0 - y0) + (v0 * CppAD::sin(epsi0) * dt)); fg[1 + epsi_start + t] = epsi1 - ((psi0 - psides0) - (v0/Lf) * delta0 * dt); } } }; // // MPC class definition implementation. // MPC::MPC() { size_t n_vars = N * 6 + (N-1) * 2; has_prev_vars_ = false; prev_vars_ = CppAD::vector<double>(n_vars); } MPC::~MPC() {} std::vector<double> MPC::Solve(const VectorXd &state, const VectorXd &coeffs) { bool ok = true; typedef CPPAD_TESTVECTOR(double) Dvector; // Read in the initial state double x = state(0); double y = state(1); double v = state(2); double psi = state(3); double cte = state(4); double epsi = state(5); /** * Set the number of model variables (includes both states and inputs). * For example: If the state is a 4 element vector, the actuators is a 2 * element vector and there are 10 timesteps. The number of variables is: * 4 * 10 + 2 * 9 */ size_t n_vars = N * 6 + (N-1) * 2; /** * Set the number of constraints */ size_t n_constraints = N * 6; // Initial value of the independent variables. // SHOULD BE 0 besides initial state. Dvector vars(n_vars); for (int i = 0; i < n_vars; ++i) { vars[i] = 0.0; } if (has_prev_vars_) { vars = prev_vars_; } // Initial values - additionally required by a constraint vars[x_start] = x; vars[y_start] = y; vars[v_start] = v; vars[psi_start] = psi; vars[cte_start] = cte; vars[epsi_start] = epsi; Dvector vars_lowerbound(n_vars); Dvector vars_upperbound(n_vars); /** * Set lower and upper limits for variables. */ // Standard initialization for all values - overwrite psi later for (int t = 0; t < n_vars; ++t) { // ATTENTION: This does not work with std::numeric_limits<double>::max()/min() vars_lowerbound[t] = -1.0e19; vars_upperbound[t] = 1.0e19; } // Delta and 'a' have a shorter length for(int t=0; t<N-1; ++t) { vars_lowerbound[delta_start + t] = -deg2rad(25); vars_upperbound[delta_start + t] = deg2rad(25); vars_lowerbound[a_start + t] = -1.; vars_upperbound[a_start + t] = 1.; } // Lower and upper limits for the constraints // Should be 0 besides initial state. Dvector constraints_lowerbound(n_constraints); Dvector constraints_upperbound(n_constraints); for (int i = 0; i < n_constraints; ++i) { // Helps the solver in steep curves constraints_lowerbound[i] = -0.01; constraints_upperbound[i] = 0.01; } // Lower bounds for initial state differ constraints_lowerbound[x_start] = x; constraints_lowerbound[y_start] = y; constraints_lowerbound[v_start] = v; constraints_lowerbound[psi_start] = psi; constraints_lowerbound[cte_start] = cte; constraints_lowerbound[epsi_start] = epsi; // Upper bounds for initial state differ constraints_upperbound[x_start] = x; constraints_upperbound[y_start] = y; constraints_upperbound[v_start] = v; constraints_upperbound[psi_start] = psi; constraints_upperbound[cte_start] = cte; constraints_upperbound[epsi_start] = epsi; // object that computes objective and constraints FG_eval fg_eval(coeffs); // NOTE: You don't have to worry about these options // options for IPOPT solver std::string options; // Uncomment this if you'd like more print information options += "Integer print_level 0\n"; // NOTE: Setting sparse to true allows the solver to take advantage // of sparse routines, this makes the computation MUCH FASTER. If you can // uncomment 1 of these and see if it makes a difference or not but if you // uncomment both the computation time should go up in orders of magnitude. options += "Sparse true forward\n"; options += "Sparse true reverse\n"; // NOTE: Currently the solver has a maximum time limit of 0.5 seconds. // Change this as you see fit. options += "Numeric max_cpu_time 0.5\n"; // place to return solution CppAD::ipopt::solve_result<Dvector> solution; // solve the problem CppAD::ipopt::solve<Dvector, FG_eval>( options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound, constraints_upperbound, fg_eval, solution); // Check some of the solution values ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success; // Cost auto cost = solution.obj_value; std::cout << "Cost " << cost << std::endl; /** * Return the first actuator values. The variables can be accessed with * `solution.x[i]`. * * {...} is shorthand for creating a vector, so auto x1 = {1.0,2.0} * creates a 2 element double vector. */ // Create the output vector std::vector<double> result; result.push_back(solution.x[delta_start]); result.push_back(solution.x[a_start]); // Add x and y values of the predicted optimal sequence for (int t = 0; t < N; ++t) { result.push_back(solution.x[x_start + t]); result.push_back(solution.x[y_start + t]); } // Save the variable solution for init of next round prev_vars_ = vars; has_prev_vars_ = true; // Return the output vector return result; }
32.622837
96
0.642978
[ "object", "vector", "model" ]
dc2934dfd4432a4a141db6421ac629d8c29efd20
1,744
cpp
C++
src/game/server/cplane.cpp
vxsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
14
2021-02-16T14:13:50.000Z
2022-03-17T18:29:19.000Z
src/game/server/cplane.cpp
undbsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
7
2021-08-06T18:40:37.000Z
2022-03-09T18:05:08.000Z
src/game/server/cplane.cpp
undbsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
2
2021-08-05T16:03:03.000Z
2021-11-26T00:11:27.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "game.h" #include "cplane.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //========================================================= // Plane //========================================================= CPlane::CPlane ( void ) { m_fInitialized = FALSE; } //========================================================= // InitializePlane - Takes a normal for the plane and a // point on the plane and //========================================================= void CPlane::InitializePlane ( const Vector &vecNormal, const Vector &vecPoint ) { m_vecNormal = vecNormal; m_flDist = DotProduct ( m_vecNormal, vecPoint ); m_fInitialized = TRUE; } //========================================================= // PointInFront - determines whether the given vector is // in front of the plane. //========================================================= bool CPlane::PointInFront ( const Vector &vecPoint ) { float flFace; if ( !m_fInitialized ) { return FALSE; } flFace = DotProduct ( m_vecNormal, vecPoint ) - m_flDist; if ( flFace >= 0 ) { return TRUE; } return FALSE; } //========================================================= //========================================================= float CPlane::PointDist ( const Vector &vecPoint ) { float flDist; if ( !m_fInitialized ) { return FALSE; } flDist = DotProduct ( m_vecNormal, vecPoint ) - m_flDist; return flDist; }
24.222222
81
0.427752
[ "vector" ]
dc295c4738fca60aca3f0d8e957113de671c405f
4,439
cpp
C++
libs/numeric/odeint/test/rosenbrock4_mp.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
libs/numeric/odeint/test/rosenbrock4_mp.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
libs/numeric/odeint/test/rosenbrock4_mp.cpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
[ "BSL-1.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* [auto_generated] libs/numeric/odeint/test/rosenbrock4.cpp [begin_description] This file tests the Rosenbrock 4 stepper and its controller and dense output stepper. [end_description] Copyright 2009-2012 Karsten Ahnert Copyright 2009-2012 Mario Mulansky 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) */ // disable checked iterator warning for msvc #include <boost/config.hpp> #ifdef BOOST_MSVC #pragma warning(disable:4996) #endif #define BOOST_TEST_MODULE odeint_rosenbrock4 #include <utility> #include <iostream> #include <boost/test/unit_test.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/numeric/odeint/stepper/rosenbrock4.hpp> #include <boost/numeric/odeint/stepper/rosenbrock4_controller.hpp> #include <boost/numeric/odeint/stepper/rosenbrock4_dense_output.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace boost::unit_test; using namespace boost::numeric::odeint; typedef boost::multiprecision::cpp_dec_float_50 value_type; typedef boost::numeric::ublas::vector< value_type > state_type; typedef boost::numeric::ublas::matrix< value_type > matrix_type; struct sys { void operator()( const state_type &x , state_type &dxdt , const value_type &t ) const { dxdt( 0 ) = x( 0 ) + 2 * x( 1 ); dxdt( 1 ) = x( 1 ); } }; struct jacobi { void operator()( const state_type &x , matrix_type &jacobi , const value_type &t , state_type &dfdt ) const { jacobi( 0 , 0 ) = 1; jacobi( 0 , 1 ) = 2; jacobi( 1 , 0 ) = 0; jacobi( 1 , 1 ) = 1; dfdt( 0 ) = 0.0; dfdt( 1 ) = 0.0; } }; BOOST_AUTO_TEST_SUITE( rosenbrock4_test ) BOOST_AUTO_TEST_CASE( test_rosenbrock4_stepper ) { typedef rosenbrock4< value_type > stepper_type; stepper_type stepper; typedef stepper_type::state_type state_type; typedef stepper_type::value_type stepper_value_type; typedef stepper_type::deriv_type deriv_type; typedef stepper_type::time_type time_type; state_type x( 2 ) , xerr( 2 ); x(0) = 0.0; x(1) = 1.0; stepper.do_step( std::make_pair( sys() , jacobi() ) , x , static_cast<value_type>(0.0) , static_cast<value_type>(0.1) , xerr ); stepper.do_step( std::make_pair( sys() , jacobi() ) , x , static_cast<value_type>(0.0) , static_cast<value_type>(0.1) ); // using std::abs; // value_type eps = 1E-12; // // // compare with analytic solution of above system // BOOST_CHECK_SMALL( abs( x(0) - 20.0/81.0 ) , eps ); // BOOST_CHECK_SMALL( abs( x(1) - 10.0/9.0 ) , eps ); } BOOST_AUTO_TEST_CASE( test_rosenbrock4_controller ) { typedef rosenbrock4_controller< rosenbrock4< value_type > > stepper_type; stepper_type stepper; typedef stepper_type::state_type state_type; typedef stepper_type::value_type stepper_value_type; typedef stepper_type::deriv_type deriv_type; typedef stepper_type::time_type time_type; state_type x( 2 ); x( 0 ) = 0.0 ; x(1) = 1.0; value_type t = 0.0 , dt = 0.01; stepper.try_step( std::make_pair( sys() , jacobi() ) , x , t , dt ); } BOOST_AUTO_TEST_CASE( test_rosenbrock4_dense_output ) { typedef rosenbrock4_dense_output< rosenbrock4_controller< rosenbrock4< value_type > > > stepper_type; typedef rosenbrock4_controller< rosenbrock4< value_type > > controlled_stepper_type; controlled_stepper_type c_stepper; stepper_type stepper( c_stepper ); typedef stepper_type::state_type state_type; typedef stepper_type::value_type stepper_value_type; typedef stepper_type::deriv_type deriv_type; typedef stepper_type::time_type time_type; state_type x( 2 ); x( 0 ) = 0.0 ; x(1) = 1.0; stepper.initialize( x , 0.0 , 0.1 ); std::pair< value_type , value_type > tr = stepper.do_step( std::make_pair( sys() , jacobi() ) ); stepper.calc_state( 0.5 * ( tr.first + tr.second ) , x ); } BOOST_AUTO_TEST_CASE( test_rosenbrock4_copy_dense_output ) { typedef rosenbrock4_controller< rosenbrock4< value_type > > controlled_stepper_type; typedef rosenbrock4_dense_output< controlled_stepper_type > stepper_type; controlled_stepper_type c_stepper; stepper_type stepper( c_stepper ); stepper_type stepper2( stepper ); } BOOST_AUTO_TEST_SUITE_END()
30.826389
111
0.700834
[ "vector" ]
dc2b18c6379a50883a3fac6ffd62aac00074a4dd
2,230
cpp
C++
python/py_caffe_module/_bp_test.cpp
HughKu/caffe-retrieval
20085014a7422445cd45d53c3e7b5742d3a242c9
[ "MIT" ]
1
2021-02-21T19:10:32.000Z
2021-02-21T19:10:32.000Z
python/py_caffe_module/_bp_test.cpp
HughKu/caffe-retrieval
20085014a7422445cd45d53c3e7b5742d3a242c9
[ "MIT" ]
null
null
null
python/py_caffe_module/_bp_test.cpp
HughKu/caffe-retrieval
20085014a7422445cd45d53c3e7b5742d3a242c9
[ "MIT" ]
null
null
null
#include <Python.h> // NOLINT(build/include_alpha) // Produce deprecation warnings (needs to come before arrayobject.h inclusion). #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <boost/make_shared.hpp> #include <boost/python.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <numpy/arrayobject.h> // these need to be included after boost on OS X #include <string> // NOLINT(build/include_order) #include <vector> // NOLINT(build/include_order) // Temporary solution for numpy < 1.7 versions: old macro, no promises. // You're strongly advised to upgrade to >= 1.7. #ifndef NPY_ARRAY_C_CONTIGUOUS #define NPY_ARRAY_C_CONTIGUOUS NPY_C_CONTIGUOUS #define PyArray_SetBaseObject(arr, x) (PyArray_BASE(arr) = (x)) #endif namespace bp = boost::python; bp::object main_raw(bp::tuple args, bp::dict kwargs){ if (bp::len(kwargs) > 0) { throw std::runtime_error("main_raw takes no kwargs"); } for (int i=0; i<bp::len(args); ++i) { std::string arg = bp::extract<std::string>(args[i]); printf("arg-%d is %s\n", i, arg.c_str()); } // We need to explicitly return None to use bp::raw_function. return bp::object(); } template <typename Dtype> class World { public: World(std::string msg, Dtype value): msg(msg), value(value) { printf("%s/%f is initialized.\n", this->msg.c_str(), this->value); } // string property void setString(std::string msg) { this->msg = msg; } std::string getString() { return this->msg; } // value property void setValue(int value) { this->value = value; } int getValue() {return this->value; } private: // class members std::string msg; Dtype value; }; typedef float Dtype; BOOST_PYTHON_MODULE(_bp_test) { bp::class_<World<Dtype> >("World", bp::init<std::string, Dtype>()) .add_property("msg", &World<Dtype>::getString, &World<Dtype>::setString) .add_property("val", &World<Dtype>::getValue, &World<Dtype>::setValue) ; bp::def("main", bp::raw_function(&main_raw)); // boost python expects a void (missing) return value, while import_array // returns NULL for python3. import_array1() forces a void return value. import_array1(); }
32.318841
134
0.69417
[ "object", "vector" ]
dc2b6787f481887ec6487e575ba0821dfd2551fe
2,362
cpp
C++
libtcod-1.5.1-mingw32/libtcod-1.5.1/src/gui/slider.cpp
KitRobinson/rogue
aeb4df46d8d228a56b21669aa74302a3db136092
[ "bzip2-1.0.6" ]
1
2015-05-19T08:12:49.000Z
2015-05-19T08:12:49.000Z
libtcod32-1.5.2/src/gui/slider.cpp
fillest/7drl2013
96d291dce08a85d3871713c99f3a036de482d6ca
[ "MIT" ]
null
null
null
libtcod32-1.5.2/src/gui/slider.cpp
fillest/7drl2013
96d291dce08a85d3871713c99f3a036de482d6ca
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <math.h> #include "libtcod.hpp" #include "gui.hpp" Slider::Slider(int x,int y,int w, float min, float max, const char *label, const char *tip) : TextBox(x,y,w,10,label,NULL,tip),min(min),max(max),value((min+max)*0.5f),sensitivity(1.0f), onArrows(false),drag(false),fmt(NULL),cbk(NULL),data(NULL) { valueToText(); this->w+=2; } Slider::~Slider() { if ( fmt ) free(fmt); } void Slider::setFormat(const char *fmt) { if ( this->fmt ) free(this->fmt); if ( fmt ) this->fmt = TCOD_strdup(fmt); else fmt=NULL; valueToText(); } void Slider::render() { w-=2; TextBox::render(); w+=2; con->setDefaultBackground((onArrows || drag) ? backFocus : back); con->setDefaultForeground((onArrows || drag) ? foreFocus : fore); con->rect(x+w-2,y,2,1,TCOD_BKGND_SET); con->setChar(x+w-2,y,TCOD_CHAR_ARROW_W); con->setChar(x+w-1,y,TCOD_CHAR_ARROW_E); } void Slider::update(TCOD_key_t k) { float oldValue=value; TextBox::update(k); textToValue(); if ( mouse.cx >= x+w-2 && mouse.cx < x+w && mouse.cy == y ) onArrows=true; else onArrows=false; if ( drag ) { if ( dragy == -1 ) { dragx = mouse.x; dragy = mouse.y; } else { float mdx = (float)((mouse.x-dragx)*sensitivity) / (con->getWidth()*8); float mdy = (float)((mouse.y-dragy)*sensitivity) / (con->getHeight()*8); float oldValue=value; if ( fabs(mdy) > fabs(mdx) ) mdx=-mdy; value = dragValue+(max-min)*mdx; value=CLAMP(min,max,value); if ( value != oldValue ) { valueToText(); textToValue(); } } } if ( value != oldValue && cbk ) { cbk(this,value,data); } } void Slider::valueToText() { char tmp[128]; sprintf(tmp, fmt ? fmt : "%.2f",value); setText(tmp); } void Slider::textToValue() { #ifdef TCOD_VISUAL_STUDIO value=(float)atof(txt); #else char *endptr; float f=strtof(txt,&endptr); if ( f != 0.0f || endptr != txt ) value=f; #endif } void Slider::setValue(float value) { this->value=CLAMP(min,max,value); valueToText(); } void Slider::onButtonPress() { if ( onArrows ) { drag=true; dragy=-1; dragValue=value; TCODMouse::showCursor(false); } } void Slider::onButtonRelease() { if ( drag ) { drag=false; TCODMouse::move((x+w-2)*8,y*8); TCODMouse::showCursor(true); } }
23.156863
95
0.607959
[ "render" ]
dc2b68b266eec27219aaf1950a6b8cf749464ccc
17,903
cpp
C++
src/OrbitGl/Batcher.cpp
mfkiwl/orbit
59324e837ead5f4d47a7ee3fd8159cfdc7c2603e
[ "BSD-2-Clause" ]
null
null
null
src/OrbitGl/Batcher.cpp
mfkiwl/orbit
59324e837ead5f4d47a7ee3fd8159cfdc7c2603e
[ "BSD-2-Clause" ]
null
null
null
src/OrbitGl/Batcher.cpp
mfkiwl/orbit
59324e837ead5f4d47a7ee3fd8159cfdc7c2603e
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2020 The Orbit 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 "Batcher.h" #include <GteVector.h> #include <GteVector2.h> #include <glad/glad.h> #include <math.h> #include <stddef.h> #include "DisplayFormats/DisplayFormats.h" #include "Introspection/Introspection.h" #include "OrbitBase/Logging.h" void Batcher::AddLine(Vec2 from, Vec2 to, float z, const Color& color, std::unique_ptr<PickingUserData> user_data) { Color picking_color = PickingId::ToColor(PickingType::kLine, user_data_.size(), batcher_id_); AddLine(from, to, z, color, picking_color, std::move(user_data)); } void Batcher::AddLine(Vec2 from, Vec2 to, float z, const Color& color, std::shared_ptr<Pickable> pickable) { CHECK(picking_manager_ != nullptr); Color picking_color = picking_manager_->GetPickableColor(pickable, batcher_id_); AddLine(from, to, z, color, picking_color, nullptr); } void Batcher::AddVerticalLine(Vec2 pos, float size, float z, const Color& color, std::unique_ptr<PickingUserData> user_data) { AddLine(pos, pos + Vec2(0, size), z, color, std::move(user_data)); } void Batcher::AddVerticalLine(Vec2 pos, float size, float z, const Color& color, std::shared_ptr<Pickable> pickable) { CHECK(picking_manager_ != nullptr); Color picking_color = picking_manager_->GetPickableColor(pickable, batcher_id_); AddLine(pos, pos + Vec2(0, size), z, color, picking_color, nullptr); } static void MoveLineToPixelCenterIfHorizontal(Line& line) { if (line.start_point[1] != line.end_point[1]) return; line.start_point[1] += 0.5f; line.end_point[1] += 0.5f; } void Batcher::AddLine(Vec2 from, Vec2 to, float z, const Color& color, const Color& picking_color, std::unique_ptr<PickingUserData> user_data) { Line line; line.start_point = Vec3(floorf(from[0]), floorf(from[1]), z); line.end_point = Vec3(floorf(to[0]), floorf(to[1]), z); // TODO(b/195386885) This is a hack to address the issue that some horizontal lines in the graph // tracks are missing. We need a better solution for this issue. MoveLineToPixelCenterIfHorizontal(line); auto& buffer = primitive_buffers_by_layer_[z]; buffer.line_buffer.lines_.emplace_back(line); buffer.line_buffer.colors_.push_back_n(color, 2); buffer.line_buffer.picking_colors_.push_back_n(picking_color, 2); user_data_.push_back(std::move(user_data)); } void Batcher::AddBox(const Box& box, const std::array<Color, 4>& colors, std::unique_ptr<PickingUserData> user_data) { Color picking_color = PickingId::ToColor(PickingType::kBox, user_data_.size(), batcher_id_); AddBox(box, colors, picking_color, std::move(user_data)); } void Batcher::AddBox(const Box& box, const Color& color, std::unique_ptr<PickingUserData> user_data) { std::array<Color, 4> colors; colors.fill(color); AddBox(box, colors, std::move(user_data)); } void Batcher::AddBox(const Box& box, const Color& color, std::shared_ptr<Pickable> pickable) { CHECK(picking_manager_ != nullptr); Color picking_color = picking_manager_->GetPickableColor(pickable, batcher_id_); std::array<Color, 4> colors; colors.fill(color); AddBox(box, colors, picking_color, nullptr); } void Batcher::AddShadedBox(Vec2 pos, Vec2 size, float z, const Color& color) { AddShadedBox(pos, size, z, color, std::unique_ptr<PickingUserData>(), ShadingDirection::kLeftToRight); } void Batcher::AddShadedBox(Vec2 pos, Vec2 size, float z, const Color& color, ShadingDirection shading_direction) { AddShadedBox(pos, size, z, color, std::unique_ptr<PickingUserData>(), shading_direction); } void Batcher::AddShadedBox(Vec2 pos, Vec2 size, float z, const Color& color, std::unique_ptr<PickingUserData> user_data, ShadingDirection shading_direction) { std::array<Color, 4> colors; GetBoxGradientColors(color, &colors, shading_direction); Box box(pos, size, z); AddBox(box, colors, std::move(user_data)); } static std::vector<Triangle> GetUnitArcTriangles(float angle_0, float angle_1, uint32_t num_sides) { std::vector<Triangle> triangles; const Vec3 origin(0, 0, 0); float increment_radians = std::fabs(angle_1 - angle_0) / static_cast<float>(num_sides); Vec3 last_point(cosf(angle_0), sinf(angle_0), 0); for (uint32_t i = 1; i <= num_sides; ++i) { float angle = angle_0 + static_cast<float>(i) * increment_radians; Vec3 current_point(cosf(angle), sinf(angle), 0); triangles.emplace_back(Triangle(origin, last_point, current_point)); last_point = current_point; } return triangles; } static void AddRoundedCornerTriangles(Batcher* batcher, const std::vector<Triangle> unit_triangles, Vec2 pos, float radius, float z, const Color& color) { for (auto& unit_triangle : unit_triangles) { Triangle triangle = unit_triangle; triangle.vertices[1] *= radius; triangle.vertices[2] *= radius; for (size_t i = 0; i < 3; ++i) { triangle.vertices[i][0] += pos[0]; triangle.vertices[i][1] += pos[1]; triangle.vertices[i][2] = z; } batcher->AddTriangle(triangle, color); } } void Batcher::AddBottomLeftRoundedCorner(Vec2 pos, float radius, float z, const Color& color) { static auto unit_triangles = GetUnitArcTriangles(kPiFloat, 1.5f * kPiFloat, kNumArcSides); AddRoundedCornerTriangles(this, unit_triangles, pos, radius, z, color); } void Batcher::AddTopLeftRoundedCorner(Vec2 pos, float radius, float z, const Color& color) { static auto unit_triangles = GetUnitArcTriangles(0.5f * kPiFloat, kPiFloat, kNumArcSides); AddRoundedCornerTriangles(this, unit_triangles, pos, radius, z, color); } void Batcher::AddTopRightRoundedCorner(Vec2 pos, float radius, float z, const Color& color) { static auto unit_triangles = GetUnitArcTriangles(0, 0.5f * kPiFloat, kNumArcSides); AddRoundedCornerTriangles(this, unit_triangles, pos, radius, z, color); } void Batcher::AddBottomRightRoundedCorner(Vec2 pos, float radius, float z, const Color& color) { static auto unit_triangles = GetUnitArcTriangles(-0.5f * kPiFloat, 0, kNumArcSides); AddRoundedCornerTriangles(this, unit_triangles, pos, radius, z, color); } void Batcher::AddRoundedBox(Vec2 pos, Vec2 size, float z, float radius, const Color& color, float margin) { const Vec2 extra_margin(margin, margin); pos -= extra_margin; size += 2.f * extra_margin; Box left_box(Vec2(pos[0], pos[1] + radius), Vec2(radius, size[1] - 2 * radius), z); Box middle_box(Vec2(pos[0] + radius, pos[1]), Vec2(size[0] - 2 * radius, size[1]), z); Box right_box(Vec2(pos[0] + size[0] - radius, pos[1] + radius), Vec2(radius, size[1] - 2 * radius), z); AddBox(left_box, color); AddBox(middle_box, color); AddBox(right_box, color); Vec2 bottom_left_pos(pos[0] + radius, pos[1] + radius); Vec2 top_left_pos(pos[0] + radius, pos[1] + size[1] - radius); Vec2 top_right_pos(pos[0] + size[0] - radius, pos[1] + size[1] - radius); Vec2 bottom_right_pos(pos[0] + size[0] - radius, pos[1] + radius); AddBottomLeftRoundedCorner(bottom_left_pos, radius, z, color); AddTopLeftRoundedCorner(top_left_pos, radius, z, color); AddTopRightRoundedCorner(top_right_pos, radius, z, color); AddBottomRightRoundedCorner(bottom_right_pos, radius, z, color); } void Batcher::AddShadedBox(Vec2 pos, Vec2 size, float z, const Color& color, std::shared_ptr<Pickable> pickable, ShadingDirection shading_direction) { std::array<Color, 4> colors; GetBoxGradientColors(color, &colors, shading_direction); Color picking_color = picking_manager_->GetPickableColor(pickable, batcher_id_); Box box(pos, size, z); AddBox(box, colors, picking_color, nullptr); } void Batcher::AddBox(const Box& box, const std::array<Color, 4>& colors, const Color& picking_color, std::unique_ptr<PickingUserData> user_data) { Box rounded_box = box; for (size_t v = 0; v < 4; ++v) { rounded_box.vertices[v][0] = floorf(rounded_box.vertices[v][0]); rounded_box.vertices[v][1] = floorf(rounded_box.vertices[v][1]); } float layer_z_value = rounded_box.vertices[0][2]; auto& buffer = primitive_buffers_by_layer_[layer_z_value]; buffer.box_buffer.boxes_.emplace_back(rounded_box); buffer.box_buffer.colors_.push_back(colors); buffer.box_buffer.picking_colors_.push_back_n(picking_color, 4); user_data_.push_back(std::move(user_data)); } void Batcher::AddTriangle(const Triangle& triangle, const Color& color, std::unique_ptr<PickingUserData> user_data) { Color picking_color = PickingId::ToColor(PickingType::kTriangle, user_data_.size(), batcher_id_); AddTriangle(triangle, color, picking_color, std::move(user_data)); } void Batcher::AddTriangle(const Triangle& triangle, const Color& color, std::shared_ptr<Pickable> pickable) { CHECK(picking_manager_ != nullptr); Color picking_color = picking_manager_->GetPickableColor(pickable, batcher_id_); AddTriangle(triangle, color, picking_color, nullptr); } void Batcher::AddTriangle(const Triangle& triangle, const Color& color, const Color& picking_color, std::unique_ptr<PickingUserData> user_data) { std::array<Color, 3> colors; colors.fill(color); AddTriangle(triangle, colors, picking_color, std::move(user_data)); } // Draw a shaded trapezium with two sides parallel to the x-axis or y-axis. void Batcher::AddShadedTrapezium(const Vec3& top_left, const Vec3& bottom_left, const Vec3& bottom_right, const Vec3& top_right, const Color& color, std::unique_ptr<PickingUserData> user_data, ShadingDirection shading_direction) { std::array<Color, 4> colors; // top_left, bottom_left, bottom_right, top_right. GetBoxGradientColors(color, &colors, shading_direction); Color picking_color = PickingId::ToColor(PickingType::kTriangle, user_data_.size(), batcher_id_); Triangle triangle_1{top_left, bottom_left, top_right}; std::array<Color, 3> colors_1{colors[0], colors[1], colors[2]}; AddTriangle(triangle_1, colors_1, picking_color, std::make_unique<PickingUserData>(*user_data)); Triangle triangle_2{bottom_left, bottom_right, top_right}; std::array<Color, 3> colors_2{colors[1], colors[2], colors[3]}; AddTriangle(triangle_2, colors_2, picking_color, std::move(user_data)); } void Batcher::AddTriangle(const Triangle& triangle, const std::array<Color, 3>& colors, const Color& picking_color, std::unique_ptr<PickingUserData> user_data) { Triangle rounded_tri = triangle; for (auto& vertice : rounded_tri.vertices) { vertice[0] = floorf(vertice[0]); vertice[1] = floorf(vertice[1]); } float layer_z_value = rounded_tri.vertices[0][2]; auto& buffer = primitive_buffers_by_layer_[layer_z_value]; buffer.triangle_buffer.triangles_.emplace_back(rounded_tri); buffer.triangle_buffer.colors_.push_back(colors); buffer.triangle_buffer.picking_colors_.push_back_n(picking_color, 3); user_data_.push_back(std::move(user_data)); } void Batcher::AddCircle(Vec2 position, float radius, float z, Color color) { std::vector<Vec2> circle_points_scaled_by_radius; for (auto& point : circle_points) { circle_points_scaled_by_radius.emplace_back(radius * point); } position = Vec2(floorf(position[0]), floorf(position[1])); Vec3 prev_point(position[0], position[1] - radius, z); Vec3 point_0 = Vec3(position[0], position[1], z); for (size_t i = 0; i < circle_points_scaled_by_radius.size(); ++i) { Vec3 new_point(position[0] + circle_points_scaled_by_radius[i][0], position[1] - circle_points_scaled_by_radius[i][1], z); Vec3 point_1 = Vec3(prev_point[0], prev_point[1], z); Vec3 point_2 = Vec3(new_point[0], new_point[1], z); Triangle triangle(point_0, point_1, point_2); AddTriangle(triangle, color); prev_point = new_point; } } const PickingUserData* Batcher::GetUserData(PickingId id) const { CHECK(id.element_id >= 0); CHECK(id.batcher_id == batcher_id_); switch (id.type) { case PickingType::kInvalid: return nullptr; case PickingType::kBox: case PickingType::kTriangle: case PickingType::kLine: CHECK(id.element_id < user_data_.size()); return user_data_[id.element_id].get(); case PickingType::kPickable: return nullptr; case PickingType::kCount: UNREACHABLE(); } UNREACHABLE(); } PickingUserData* Batcher::GetUserData(PickingId id) { return const_cast<PickingUserData*>(static_cast<const Batcher*>(this)->GetUserData(id)); } const orbit_client_protos::TimerInfo* Batcher::GetTimerInfo(PickingId id) const { const PickingUserData* data = GetUserData(id); if (data && data->timer_info_) { return data->timer_info_; } return nullptr; } void Batcher::GetBoxGradientColors(const Color& color, std::array<Color, 4>* colors, ShadingDirection shading_direction) { const float kGradientCoeff = 0.94f; Vec3 dark = Vec3(color[0], color[1], color[2]) * kGradientCoeff; Color dark_color = Color(static_cast<uint8_t>(dark[0]), static_cast<uint8_t>(dark[1]), static_cast<uint8_t>(dark[2]), color[3]); switch (shading_direction) { case ShadingDirection::kLeftToRight: (*colors)[0] = dark_color; (*colors)[1] = dark_color; (*colors)[2] = color; (*colors)[3] = color; break; case ShadingDirection::kRightToLeft: (*colors)[0] = color; (*colors)[1] = color; (*colors)[2] = dark_color; (*colors)[3] = dark_color; break; case ShadingDirection::kTopToBottom: (*colors)[0] = dark_color; (*colors)[1] = color; (*colors)[2] = color; (*colors)[3] = dark_color; break; case ShadingDirection::kBottomToTop: (*colors)[0] = color; (*colors)[1] = dark_color; (*colors)[2] = dark_color; (*colors)[3] = color; break; } } void Batcher::ResetElements() { for (auto& [unused_layer, buffer] : primitive_buffers_by_layer_) { buffer.Reset(); } } void Batcher::StartNewFrame() { ResetElements(); user_data_.clear(); } std::vector<float> Batcher::GetLayers() const { std::vector<float> layers; for (auto& [layer, _] : primitive_buffers_by_layer_) { layers.push_back(layer); } return layers; }; void Batcher::DrawLayer(float layer, bool picking) const { ORBIT_SCOPE_FUNCTION; if (!primitive_buffers_by_layer_.count(layer)) return; glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT); if (picking) { glDisable(GL_BLEND); } else { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glDisable(GL_CULL_FACE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_TEXTURE_2D); DrawBoxBuffer(layer, picking); DrawLineBuffer(layer, picking); DrawTriangleBuffer(layer, picking); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glPopAttrib(); } void Batcher::Draw(bool picking) const { for (auto& [layer, unused_buffer] : primitive_buffers_by_layer_) { DrawLayer(layer, picking); } } void Batcher::DrawBoxBuffer(float layer, bool picking) const { auto& box_buffer = primitive_buffers_by_layer_.at(layer).box_buffer; const Block<Box, BoxBuffer::NUM_BOXES_PER_BLOCK>* box_block = box_buffer.boxes_.root(); const Block<Color, BoxBuffer::NUM_BOXES_PER_BLOCK * 4>* color_block; color_block = !picking ? box_buffer.colors_.root() : box_buffer.picking_colors_.root(); while (box_block != nullptr) { if (auto num_elems = box_block->size()) { glVertexPointer(3, GL_FLOAT, sizeof(Vec3), box_block->data()); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Color), color_block->data()); glDrawArrays(GL_QUADS, 0, num_elems * 4); } box_block = box_block->next(); color_block = color_block->next(); } } void Batcher::DrawLineBuffer(float layer, bool picking) const { auto& line_buffer = primitive_buffers_by_layer_.at(layer).line_buffer; const Block<Line, LineBuffer::NUM_LINES_PER_BLOCK>* line_block = line_buffer.lines_.root(); const Block<Color, LineBuffer::NUM_LINES_PER_BLOCK * 2>* color_block; color_block = !picking ? line_buffer.colors_.root() : line_buffer.picking_colors_.root(); while (line_block != nullptr) { if (auto num_elems = line_block->size()) { glVertexPointer(3, GL_FLOAT, sizeof(Vec3), line_block->data()); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Color), color_block->data()); glDrawArrays(GL_LINES, 0, num_elems * 2); } line_block = line_block->next(); color_block = color_block->next(); } } void Batcher::DrawTriangleBuffer(float layer, bool picking) const { auto& triangle_buffer = primitive_buffers_by_layer_.at(layer).triangle_buffer; const Block<Triangle, TriangleBuffer::NUM_TRIANGLES_PER_BLOCK>* triangle_block = triangle_buffer.triangles_.root(); const Block<Color, TriangleBuffer::NUM_TRIANGLES_PER_BLOCK * 3>* color_block; color_block = !picking ? triangle_buffer.colors_.root() : triangle_buffer.picking_colors_.root(); while (triangle_block != nullptr) { if (int num_elems = triangle_block->size()) { glVertexPointer(3, GL_FLOAT, sizeof(Vec3), triangle_block->data()); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Color), color_block->data()); glDrawArrays(GL_TRIANGLES, 0, num_elems * 3); } triangle_block = triangle_block->next(); color_block = color_block->next(); } }
38.584052
100
0.699268
[ "vector" ]
dc2c3e6af6be04cee6e4e69bfcd3113c67f80dfd
7,296
cc
C++
src/core/crypto/impl/cryptopp/util/compression.cc
byterubpay/kovri
8ed2e7fc26c12bcdd343b6f8b0ba36d8ad8097a8
[ "BSD-3-Clause" ]
653
2015-11-17T22:50:10.000Z
2022-03-30T17:43:10.000Z
src/core/crypto/impl/cryptopp/util/compression.cc
byterubpay/kovri
8ed2e7fc26c12bcdd343b6f8b0ba36d8ad8097a8
[ "BSD-3-Clause" ]
593
2015-11-17T16:40:58.000Z
2019-12-06T22:07:32.000Z
src/core/crypto/impl/cryptopp/util/compression.cc
byterubpay/kovri
8ed2e7fc26c12bcdd343b6f8b0ba36d8ad8097a8
[ "BSD-3-Clause" ]
150
2015-11-17T16:13:55.000Z
2022-03-07T06:07:57.000Z
/** // * Copyright (c) 2015-2017, The Kovri I2P Router Project // * // * All rights reserved. // * // * Redistribution and use in source and binary forms, with or without modification, are // * permitted provided that the following conditions are met: // * // * 1. Redistributions of source code must retain the above copyright notice, this list of // * conditions and the following disclaimer. // * // * 2. 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. // * // * 3. Neither the name of the copyright holder 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 // * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // */ #include "core/crypto/util/compression.h" #include <cryptopp/crc.h> #include <cryptopp/gzip.h> #include <cryptopp/zinflate.h> #include "core/util/log.h" namespace kovri { namespace core { /// @class DeflateDecompressorImpl /// @brief RFC 1951 DEFLATE Decompressor class DeflateDecompressor::DeflateDecompressorImpl { public: std::size_t Put( std::uint8_t* buffer, std::size_t length) { std::size_t unprocessed_bytes; unprocessed_bytes = m_Inflator.Put(buffer, length); // Signal the end of messages to the object m_Inflator.MessageEnd(); return unprocessed_bytes; } std::size_t Get( std::uint8_t* buffer, std::size_t length) { return m_Inflator.Get(buffer, length); } std::size_t MaxRetrievable() { return m_Inflator.MaxRetrievable(); } bool Verify( std::uint8_t* hash, std::uint8_t* data, std::size_t length) { return CryptoPP::CRC32().VerifyDigest(hash, data, length); } private: CryptoPP::Inflator m_Inflator; }; DeflateDecompressor::DeflateDecompressor() : m_DeflateDecompressorPimpl( std::make_unique<DeflateDecompressorImpl>()) {} DeflateDecompressor::~DeflateDecompressor() {} std::size_t DeflateDecompressor::Put( std::uint8_t* buffer, std::size_t length) { return m_DeflateDecompressorPimpl->Put(buffer, length); } std::size_t DeflateDecompressor::Get( std::uint8_t* buffer, std::size_t length) { return m_DeflateDecompressorPimpl->Get(buffer, length); } std::size_t DeflateDecompressor::MaxRetrievable() { return m_DeflateDecompressorPimpl->MaxRetrievable(); } bool DeflateDecompressor::Verify( std::uint8_t* hash, std::uint8_t* data, std::size_t length) { return m_DeflateDecompressorPimpl->Verify(hash, data, length); } /// @class GzipImpl /// @brief RFC 1952 GZIP Compressor class Gzip::GzipImpl { public: unsigned int GetMinDeflateLevel() { return CryptoPP::Gzip::MIN_DEFLATE_LEVEL; } unsigned int GetDefaultDeflateLevel() { return CryptoPP::Gzip::DEFAULT_DEFLATE_LEVEL; } unsigned int GetMaxDeflateLevel() { return CryptoPP::Gzip::MAX_DEFLATE_LEVEL; } void SetDeflateLevel( unsigned int deflate_level) { m_Gzip.SetDeflateLevel(deflate_level); } std::size_t Put( const std::uint8_t* buffer, std::size_t length) { std::size_t unprocessed_bytes; unprocessed_bytes = m_Gzip.Put(buffer, length); m_Gzip.MessageEnd(); return unprocessed_bytes; } std::size_t Get( std::uint8_t* buffer, std::size_t length) { return m_Gzip.Get(buffer, length); } std::size_t MaxRetrievable() { return m_Gzip.MaxRetrievable(); } private: CryptoPP::Gzip m_Gzip; }; Gzip::Gzip() : m_GzipPimpl( std::make_unique<GzipImpl>()) {} Gzip::~Gzip() {} std::size_t Gzip::GetMinDeflateLevel() { return m_GzipPimpl->GetMinDeflateLevel(); } std::size_t Gzip::GetDefaultDeflateLevel() { return m_GzipPimpl->GetDefaultDeflateLevel(); } std::size_t Gzip::GetMaxDeflateLevel() { return m_GzipPimpl->GetMaxDeflateLevel(); } void Gzip::SetDeflateLevel( std::size_t level) { m_GzipPimpl->SetDeflateLevel(level); } std::size_t Gzip::Put( const std::uint8_t* buffer, std::size_t length) { return m_GzipPimpl->Put(buffer, length); } std::size_t Gzip::Get( std::uint8_t* buffer, std::size_t length) { return m_GzipPimpl->Get(buffer, length); } std::size_t Gzip::MaxRetrievable() { return m_GzipPimpl->MaxRetrievable(); } /// @class GunzipImpl /// @brief RFC 1952 GZIP Decompressor class Gunzip::GunzipImpl { public: std::size_t Put( const std::uint8_t* buffer, std::size_t length) { std::size_t unprocessed_bytes; unprocessed_bytes = m_Gunzip.Put(buffer, length); m_Gunzip.MessageEnd(); return unprocessed_bytes; } std::size_t Get( std::uint8_t* buffer, std::size_t length) { return m_Gunzip.Get(buffer, length); } std::size_t MaxRetrievable() { return m_Gunzip.MaxRetrievable(); } private: CryptoPP::Gunzip m_Gunzip; }; Gunzip::Gunzip() : m_GunzipPimpl( std::make_unique<GunzipImpl>()) {} Gunzip::~Gunzip() {} std::size_t Gunzip::Put( const std::uint8_t* buffer, std::size_t length) { return m_GunzipPimpl->Put(buffer, length); } std::size_t Gunzip::Get( std::uint8_t* buffer, std::size_t length) { return m_GunzipPimpl->Get(buffer, length); } std::size_t Gunzip::MaxRetrievable() { return m_GunzipPimpl->MaxRetrievable(); } } // namespace core } // namespace kovri
30.527197
96
0.59937
[ "object" ]
dc37be6675b63de5d1b92b1840bc31fdc9fc975b
17,295
cpp
C++
libs/openFrameworks/utils/ofUtils.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
2
2015-12-01T16:33:43.000Z
2016-04-07T03:43:32.000Z
libs/openFrameworks/utils/ofUtils.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
null
null
null
libs/openFrameworks/utils/ofUtils.cpp
eraly5555/Hub
e890f841f16988c642cf6390fa31c3c5ae82773d
[ "MIT" ]
3
2020-02-17T14:36:18.000Z
2021-08-09T12:02:59.000Z
#include "ofUtils.h" #include "ofImage.h" #include "ofTypes.h" #include "ofGraphics.h" #include "ofAppRunner.h" #include "Poco/String.h" #include "Poco/LocalDateTime.h" #include "Poco/DateTimeFormatter.h" #include <cctype> // for toupper #include <algorithm> #ifdef TARGET_WIN32 #include <algorithm> // for std::replace #ifndef _MSC_VER #include <unistd.h> // this if for MINGW / _getcwd #endif #endif #ifdef TARGET_ANDROID // this is needed to be able to use poco 1.3, // will go away as soon as i compile poco 1.4 namespace Poco{ const int Ascii::CHARACTER_PROPERTIES[128]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; }; #endif #if defined(TARGET_OF_IPHONE) || defined(TARGET_OSX ) || defined(TARGET_LINUX) #include <sys/time.h> #endif #ifdef TARGET_OSX #ifndef TARGET_OF_IPHONE #include <mach-o/dyld.h> #include <sys/param.h> // for MAXPATHLEN #endif #endif #ifdef TARGET_WIN32 #include <mmsystem.h> #ifdef _MSC_VER #include <direct.h> #endif #endif static bool enableDataPath = true; static unsigned long startTime = ofGetSystemTime(); // better at the first frame ?? (currently, there is some delay from static init, to running. static unsigned long startTimeMicros = ofGetSystemTimeMicros(); //-------------------------------------- int ofGetElapsedTimeMillis(){ return (int)(ofGetSystemTime() - startTime); } //-------------------------------------- unsigned long ofGetElapsedTimeMicros(){ return (int)(ofGetSystemTimeMicros() - startTimeMicros); } //-------------------------------------- float ofGetElapsedTimef(){ return ((float) ((int)(ofGetSystemTime() - startTime)) / 1000.0f); } //-------------------------------------- void ofResetElapsedTimeCounter(){ startTime = ofGetSystemTime(); } //======================================= // this is from freeglut, and used internally: /* Platform-dependent time in milliseconds, as an unsigned 32-bit integer. * This value wraps every 49.7 days, but integer overflows cancel * when subtracting an initial start time, unless the total time exceeds * 32-bit, where the GLUT API return value is also overflowed. */ unsigned long ofGetSystemTime( ) { #ifndef TARGET_WIN32 struct timeval now; gettimeofday( &now, NULL ); return now.tv_usec/1000 + now.tv_sec*1000; #else #if defined(_WIN32_WCE) return GetTickCount(); #else return timeGetTime(); #endif #endif } unsigned long ofGetSystemTimeMicros( ) { #ifndef TARGET_WIN32 struct timeval now; gettimeofday( &now, NULL ); return now.tv_usec + now.tv_sec*1000000; #else #if defined(_WIN32_WCE) return GetTickCount()*1000; #else return timeGetTime()*1000; #endif #endif } //-------------------------------------------------- unsigned int ofGetUnixTime(){ return (unsigned int)time(NULL); } //default ofGetTimestampString returns in this format: 2011-01-15-18-29-35-299 //-------------------------------------------------- string ofGetTimestampString(){ string timeFormat = "%Y-%m-%d-%H-%M-%S-%i"; Poco::LocalDateTime now; return Poco::DateTimeFormatter::format(now, timeFormat); } //specify the string format - eg: %Y-%m-%d-%H-%M-%S-%i ( 2011-01-15-18-29-35-299 ) //-------------------------------------------------- string ofGetTimestampString(string timestampFormat){ Poco::LocalDateTime now; return Poco::DateTimeFormatter::format(now, timestampFormat); } //-------------------------------------------------- int ofGetSeconds(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); return local.tm_sec; } //-------------------------------------------------- int ofGetMinutes(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); return local.tm_min; } //-------------------------------------------------- int ofGetHours(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); return local.tm_hour; } //-------------------------------------------------- int ofGetYear(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); int year = local.tm_year + 1900; return year; } //-------------------------------------------------- int ofGetMonth(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); int month = local.tm_mon + 1; return month; } //-------------------------------------------------- int ofGetDay(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); return local.tm_mday; } //-------------------------------------------------- int ofGetWeekday(){ time_t curr; tm local; time(&curr); local =*(localtime(&curr)); return local.tm_wday; } //-------------------------------------------------- void ofEnableDataPath(){ enableDataPath = true; } //-------------------------------------------------- void ofDisableDataPath(){ enableDataPath = false; } //-------------------------------------------------- //use ofSetDataPathRoot() to override this #if defined TARGET_OSX static string dataPathRoot = "../../../data/"; #elif defined TARGET_ANDROID static string dataPathRoot = "sdcard/"; #else static string dataPathRoot = "data/"; #endif //-------------------------------------------------- void ofSetDataPathRoot(string newRoot){ string newPath = ""; #ifdef TARGET_OSX #ifndef TARGET_OF_IPHONE char path[MAXPATHLEN]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size) == 0){ //printf("executable path is %s\n", path); string pathStr = string(path); //theo: check this with having '/' as a character in a folder name - OSX treats the '/' as a ':' //checked with spaces too! vector < string> pathBrokenUp = ofSplitString( pathStr, "/"); newPath = ""; for(int i = 0; i < pathBrokenUp.size()-1; i++){ newPath += pathBrokenUp[i]; newPath += "/"; } //cout << newPath << endl; // some sanity checks here //system( "pwd" ); chdir ( newPath.c_str() ); //system("pwd"); }else{ ofLog(OF_LOG_FATAL_ERROR, "buffer too small; need size %u\n", size); } #endif #endif dataPathRoot = newRoot; } //-------------------------------------------------- string ofToDataPath(string path, bool makeAbsolute){ if( enableDataPath ){ //check if absolute path has been passed or if data path has already been applied //do we want to check for C: D: etc ?? like substr(1, 2) == ':' ?? if( path.length()==0 || (path.substr(0,1) != "/" && path.substr(1,1) != ":" && path.substr(0,dataPathRoot.length()) != dataPathRoot)){ path = dataPathRoot+path; } if(makeAbsolute && (path.length()==0 || path.substr(0,1) != "/")){ #if !defined( TARGET_OF_IPHONE) & !defined(TARGET_ANDROID) #ifndef TARGET_WIN32 char currDir[1024]; path = "/"+path; path = getcwd(currDir, 1024)+path; #else char currDir[1024]; path = "\\"+path; path = _getcwd(currDir, 1024)+path; std::replace( path.begin(), path.end(), '/', '\\' ); // fix any unixy paths... #endif #else //do we need iphone specific code here? #endif } } return path; } //---------------------------------------- template <> string ofToHex(const string& value) { ostringstream out; // how many bytes are in the string int numBytes = value.size(); for(int i = 0; i < numBytes; i++) { // print each byte as a 2-character wide hex value out << setfill('0') << setw(2) << hex << (unsigned int) value[i]; } return out.str(); } //---------------------------------------- string ofToHex(const char* value) { // this function is necessary if you want to print a string // using a syntax like ofToHex("test") return ofToHex((string) value); } //---------------------------------------- int ofToInt(const string& intString) { int x = 0; istringstream cur(intString); cur >> x; return x; } //---------------------------------------- int ofHexToInt(const string& intHexString) { int x = 0; istringstream cur(intHexString); cur >> hex >> x; return x; } //---------------------------------------- char ofHexToChar(const string& charHexString) { int x = 0; istringstream cur(charHexString); cur >> hex >> x; return (char) x; } //---------------------------------------- float ofHexToFloat(const string& floatHexString) { int x = 0; istringstream cur(floatHexString); cur >> hex >> x; return *((float*) &x); } //---------------------------------------- string ofHexToString(const string& stringHexString) { stringstream out; stringstream stream(stringHexString); // a hex string has two characters per byte int numBytes = stringHexString.size() / 2; for(int i = 0; i < numBytes; i++) { string curByte; // grab two characters from the hex string stream >> setw(2) >> curByte; // prepare to parse the two characters stringstream curByteStream(curByte); int cur = 0; // parse the two characters as a hex-encoded int curByteStream >> hex >> cur; // add the int as a char to our output stream out << (char) cur; } return out.str(); } //---------------------------------------- float ofToFloat(const string& floatString) { float x = 0; istringstream cur(floatString); cur >> x; return x; } //---------------------------------------- bool ofToBool(const string& boolString) { static const string trueString = "true"; static const string falseString = "false"; string lower = Poco::toLower(boolString); if(lower == trueString) { return true; } if(lower == falseString) { return false; } bool x = false; istringstream cur(lower); cur >> x; return x; } //---------------------------------------- char ofToChar(const string& charString) { char x = '\0'; istringstream cur(charString); cur >> x; return x; } //---------------------------------------- template <> string ofToBinary(const string& value) { stringstream out; int numBytes = value.size(); for(int i = 0; i < numBytes; i++) { bitset<8> bitBuffer(value[i]); out << bitBuffer; } return out.str(); } //---------------------------------------- string ofToBinary(const char* value) { // this function is necessary if you want to print a string // using a syntax like ofToBinary("test") return ofToBinary((string) value); } //---------------------------------------- int ofBinaryToInt(const string& value) { const int intSize = sizeof(int) * 8; bitset<intSize> binaryString(value); return (int) binaryString.to_ulong(); } //---------------------------------------- char ofBinaryToChar(const string& value) { const int charSize = sizeof(char) * 8; bitset<charSize> binaryString(value); return (char) binaryString.to_ulong(); } //---------------------------------------- float ofBinaryToFloat(const string& value) { const int floatSize = sizeof(float) * 8; bitset<floatSize> binaryString(value); unsigned long result = binaryString.to_ulong(); // this line means: // 1 take the address of the unsigned long // 2 pretend it is the address of a float // 3 then use it as a float // this is a bit-for-bit 'typecast' return *((float*) &result); } //---------------------------------------- string ofBinaryToString(const string& value) { ostringstream out; stringstream stream(value); bitset<8> byteString; int numBytes = value.size() / 8; for(int i = 0; i < numBytes; i++) { stream >> byteString; out << (char) byteString.to_ulong(); } return out.str(); } //-------------------------------------------------- vector <string> ofSplitString(const string & source, const string & delimiter, bool ignoreEmpty, bool trim) { vector<string> result; if (delimiter.empty()) { result.push_back(source); return result; } string::const_iterator substart = source.begin(), subend; while (true) { subend = search(substart, source.end(), delimiter.begin(), delimiter.end()); string sub(substart, subend); if(trim) { Poco::trimInPlace(sub); } if (!ignoreEmpty || !sub.empty()) { result.push_back(sub); } if (subend == source.end()) { break; } substart = subend + delimiter.size(); } return result; } //-------------------------------------------------- string ofJoinString(vector <string> stringElements, const string & delimiter){ string resultString = ""; int numElements = stringElements.size(); for(int k = 0; k < numElements; k++){ if( k < numElements-1 ){ resultString += stringElements[k] + delimiter; } else { resultString += stringElements[k]; } } return resultString; } //-------------------------------------------------- void ofStringReplace(string& input, string searchStr, string replaceStr){ size_t uPos = 0; size_t uFindLen = searchStr.length(); size_t uReplaceLen = replaceStr.length(); if( uFindLen == 0 ){ return; } for( ;(uPos = input.find( searchStr, uPos )) != std::string::npos; ){ input.replace( uPos, uFindLen, replaceStr ); uPos += uReplaceLen; } } //-------------------------------------------------- bool ofIsStringInString(string haystack, string needle){ return ( strstr(haystack.c_str(), needle.c_str() ) != NULL ); } //-------------------------------------------------- string ofToLower(const string & src){ string dst(src); transform(src.begin(),src.end(),dst.begin(),::tolower); return dst; } //-------------------------------------------------- string ofToUpper(const string & src){ string dst(src); transform(src.begin(),src.end(),dst.begin(),::toupper); return dst; } //-------------------------------------------------- string ofVAArgsToString(const char * format, ...){ // variadic args to string: // http://www.codeproject.com/KB/string/string_format.aspx static char aux_buffer[10000]; string retStr(""); if (NULL != format){ va_list marker; // initialize variable arguments va_start(marker, format); // Get formatted string length adding one for NULL size_t len = vsprintf(aux_buffer, format, marker) + 1; // Reset variable arguments va_end(marker); if (len > 0) { va_list args; // initialize variable arguments va_start(args, format); // Create a char vector to hold the formatted string. vector<char> buffer(len, '\0'); vsprintf(&buffer[0], format, args); retStr = &buffer[0]; va_end(args); } } return retStr; } string ofVAArgsToString(const char * format, va_list args){ // variadic args to string: // http://www.codeproject.com/KB/string/string_format.aspx char aux_buffer[10000]; string retStr(""); if (NULL != format){ // Get formatted string length adding one for NULL vsprintf(aux_buffer, format, args); retStr = aux_buffer; } return retStr; } //-------------------------------------------------- void ofLaunchBrowser(string url){ // http://support.microsoft.com/kb/224816 //make sure it is a properly formatted url if(url.substr(0,7) != "http://"){ ofLog(OF_LOG_WARNING, "ofLaunchBrowser: url must begin http://"); return; } //---------------------------- #ifdef TARGET_WIN32 //---------------------------- #if (_MSC_VER) // microsoft visual studio yaks about strings, wide chars, unicode, etc ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #else ShellExecute(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif //---------------------------- #endif //---------------------------- //-------------------------------------- #ifdef TARGET_OSX //-------------------------------------- // ok gotta be a better way then this, // this is what I found... string commandStr = "open "+url; system(commandStr.c_str()); //---------------------------- #endif //---------------------------- //-------------------------------------- #ifdef TARGET_LINUX //-------------------------------------- string commandStr = "xdg-open "+url; int ret = system(commandStr.c_str()); if(ret!=0) ofLog(OF_LOG_ERROR,"ofLaunchBrowser: couldn't open browser"); //---------------------------- #endif //---------------------------- } //-------------------------------------------------- string ofGetVersionInfo(){ string version; stringstream sstr; sstr << "of version: " << OF_VERSION << endl; return sstr.str(); } //---- new to 006 //from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413 //-------------------------------------------------- void ofSaveScreen(string filename) { ofImage screen; screen.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_COLOR); screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); screen.saveImage(filename); } //-------------------------------------------------- void ofSaveViewport(string filename) { // because ofSaveScreen doesn't related to viewports ofImage screen; ofRectangle view = ofGetCurrentViewport(); screen.allocate(view.width, view.height, OF_IMAGE_COLOR); screen.grabScreen(0, 0, view.width, view.height); screen.saveImage(filename); } //-------------------------------------------------- int saveImageCounter = 0; void ofSaveFrame(bool bUseViewport){ string fileName = ofToString(saveImageCounter) + ".png"; if (bUseViewport){ ofSaveViewport(fileName); } else { ofSaveScreen(fileName); } saveImageCounter++; }
25.622222
301
0.568951
[ "vector", "transform" ]
dc42713917ad648769ccce60a852dc11a1a086cf
668
cpp
C++
src/apps/haikudepot/server/dumpexportpkg/DumpExportPkgCategory.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
1
2021-08-31T01:47:13.000Z
2021-08-31T01:47:13.000Z
src/apps/haikudepot/server/dumpexportpkg/DumpExportPkgCategory.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/apps/haikudepot/server/dumpexportpkg/DumpExportPkgCategory.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
/* * Generated Model Object * source json-schema : dumpexport.json * generated at : 2017-12-07T23:22:17.118616 */ #include "DumpExportPkgCategory.h" DumpExportPkgCategory::DumpExportPkgCategory() { fCode = NULL; } DumpExportPkgCategory::~DumpExportPkgCategory() { if (fCode != NULL) { delete fCode; } } BString* DumpExportPkgCategory::Code() { return fCode; } void DumpExportPkgCategory::SetCode(BString* value) { fCode = value; } void DumpExportPkgCategory::SetCodeNull() { if (!CodeIsNull()) { delete fCode; fCode = NULL; } } bool DumpExportPkgCategory::CodeIsNull() { return fCode == NULL; }
12.603774
47
0.66018
[ "object", "model" ]
dc44900af8c230c3f33533c0051bd7f93f0507f5
1,200
cpp
C++
3-26/classdemo5.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
3-26/classdemo5.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
3-26/classdemo5.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
/******************** Overloadable operators + - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ -- % & ^ ! | ~ &= ^= |= && || %= [] () , ->* -> new delete new[] delete[] **********************/ #include <iostream> using namespace std; class CVector { public: int x,y; CVector () {};//default constructor CVector (int a,int b) : x(a), y(b) {}//overloaded constructor CVector operator + (const CVector&);//this is a prototype of a function of return type Cvector that takes an argument CVector }; CVector CVector::operator+ (const CVector& param) { CVector temp; temp.x = x + param.x; //adds the x of the object to the x of the object passed to the function and stores it in the x of the temp object temp.y = y + param.y; return temp; } int main () { CVector A (3,1);//declares vector A=(3,1) CVector B (1,2);//declares vector B=() CVector result[2]; result[0] = A + B; result[1] = A.operator+(B); cout << result[0].x << "," << result[0].y << endl; cout << result[1].x << "," << result[1].y << endl; cin.get(); return 0; }
31.578947
139
0.490833
[ "object", "vector" ]
dc475d73c26a2751c7bd7a85ed1a99125b83435a
430
cpp
C++
0/80. Remove Duplicates from Sorted Array II.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
0/80. Remove Duplicates from Sorted Array II.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
1
2021-12-25T10:33:23.000Z
2022-02-16T00:34:05.000Z
0/80. Remove Duplicates from Sorted Array II.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
class Solution { public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); if(!n) return 0; int j = 0, last = nums[0], count = 0; for(int i = 0; i < n; ++i) { if(nums[i] != last) { last = nums[i]; count = 0; } if(++count <= 2) nums[j++] = nums[i]; } return j; } };
22.631579
45
0.360465
[ "vector" ]
dc51866d0858693ceb2d5d4160fb282c3522ca49
11,595
cpp
C++
Engine/Source/Editor/DetailCustomizations/Private/FbxImportUIDetails.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Editor/DetailCustomizations/Private/FbxImportUIDetails.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Editor/DetailCustomizations/Private/FbxImportUIDetails.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "DetailCustomizationsPrivatePCH.h" #include "FbxImportUIDetails.h" #include "Factories/FbxAnimSequenceImportData.h" #include "STextComboBox.h" #include "Engine/StaticMesh.h" #define LOCTEXT_NAMESPACE "FbxImportUIDetails" FFbxImportUIDetails::FFbxImportUIDetails() { CachedDetailBuilder = nullptr; LODGroupNames.Reset(); UStaticMesh::GetLODGroups(LODGroupNames); for (int32 GroupIndex = 0; GroupIndex < LODGroupNames.Num(); ++GroupIndex) { LODGroupOptions.Add(MakeShareable(new FString(LODGroupNames[GroupIndex].GetPlainNameString()))); } } TSharedRef<IDetailCustomization> FFbxImportUIDetails::MakeInstance() { return MakeShareable( new FFbxImportUIDetails ); } void FFbxImportUIDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder ) { CachedDetailBuilder = &DetailBuilder; TArray<TWeakObjectPtr<UObject>> EditingObjects; DetailBuilder.GetObjectsBeingCustomized(EditingObjects); check(EditingObjects.Num() == 1); ImportUI = Cast<UFbxImportUI>(EditingObjects[0].Get()); // Handle mesh category IDetailCategoryBuilder& MeshCategory = DetailBuilder.EditCategory("Mesh", FText::GetEmpty(), ECategoryPriority::Important); IDetailCategoryBuilder& TransformCategory = DetailBuilder.EditCategory("Transform"); TArray<TSharedRef<IPropertyHandle>> CategoryDefaultProperties; TArray<TSharedPtr<IPropertyHandle>> ExtraProperties; // Grab and hide per-type import options TSharedRef<IPropertyHandle> StaticMeshDataProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, StaticMeshImportData)); TSharedRef<IPropertyHandle> SkeletalMeshDataProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, SkeletalMeshImportData)); TSharedRef<IPropertyHandle> AnimSequenceDataProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, AnimSequenceImportData)); DetailBuilder.HideProperty(StaticMeshDataProp); DetailBuilder.HideProperty(SkeletalMeshDataProp); DetailBuilder.HideProperty(AnimSequenceDataProp); MeshCategory.GetDefaultProperties(CategoryDefaultProperties); switch(ImportUI->MeshTypeToImport) { case FBXIT_StaticMesh: CollectChildPropertiesRecursive(StaticMeshDataProp, ExtraProperties); break; case FBXIT_SkeletalMesh: if(ImportUI->bImportMesh) { CollectChildPropertiesRecursive(SkeletalMeshDataProp, ExtraProperties); } else { ImportUI->MeshTypeToImport = FBXIT_Animation; } break; default: break; } EFBXImportType ImportType = ImportUI->MeshTypeToImport; if(ImportType != FBXIT_Animation) { TSharedRef<IPropertyHandle> ImportSkeletalProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, bImportAsSkeletal)); ImportSkeletalProp->SetOnPropertyValueChanged(FSimpleDelegate::CreateSP(this, &FFbxImportUIDetails::MeshImportModeChanged)); MeshCategory.AddProperty(ImportSkeletalProp); } TSharedRef<IPropertyHandle> ImportMeshProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, bImportMesh)); if(ImportUI->OriginalImportType == FBXIT_SkeletalMesh && ImportType != FBXIT_StaticMesh) { ImportMeshProp->SetOnPropertyValueChanged(FSimpleDelegate::CreateSP(this, &FFbxImportUIDetails::ImportMeshToggleChanged)); MeshCategory.AddProperty(ImportMeshProp); } else { DetailBuilder.HideProperty(ImportMeshProp); } for(TSharedRef<IPropertyHandle> Handle : CategoryDefaultProperties) { FString MetaData = Handle->GetMetaData(TEXT("ImportType")); if(!IsImportTypeMetaDataValid(ImportType, MetaData)) { DetailBuilder.HideProperty(Handle); } } for(TSharedPtr<IPropertyHandle> Handle : ExtraProperties) { FString ImportTypeMetaData = Handle->GetMetaData(TEXT("ImportType")); FString CategoryMetaData = Handle->GetMetaData(TEXT("ImportCategory")); if(IsImportTypeMetaDataValid(ImportType, ImportTypeMetaData)) { // Decide on category if(!CategoryMetaData.IsEmpty()) { // Populate custom categories. IDetailCategoryBuilder& CustomCategory = DetailBuilder.EditCategory(*CategoryMetaData); CustomCategory.AddProperty(Handle); } else { // No override, add to default mesh category IDetailPropertyRow& PropertyRow = MeshCategory.AddProperty(Handle); UProperty* Property = Handle->GetProperty(); if (Property != nullptr) { if (Property->GetFName() == GET_MEMBER_NAME_CHECKED(UFbxStaticMeshImportData, StaticMeshLODGroup)) { SetStaticMeshLODGroupWidget(PropertyRow, Handle); } if (Property->GetFName() == GET_MEMBER_NAME_CHECKED(UFbxStaticMeshImportData, VertexOverrideColor)) { // Cache the VertexColorImportOption property VertexColorImportOptionHandle = StaticMeshDataProp->GetChildHandle(GET_MEMBER_NAME_CHECKED(UFbxStaticMeshImportData, VertexColorImportOption)); PropertyRow.IsEnabled(TAttribute<bool>(this, &FFbxImportUIDetails::GetVertexOverrideColorEnabledState)); } } } } } // Animation Category IDetailCategoryBuilder& AnimCategory = DetailBuilder.EditCategory("Animation", FText::GetEmpty(), ECategoryPriority::Important); CategoryDefaultProperties.Empty(); AnimCategory.GetDefaultProperties(CategoryDefaultProperties); for(TSharedRef<IPropertyHandle> Handle : CategoryDefaultProperties) { FString MetaData = Handle->GetMetaData(TEXT("ImportType")); if(!IsImportTypeMetaDataValid(ImportType, MetaData)) { DetailBuilder.HideProperty(Handle); } } if(ImportType == FBXIT_Animation || ImportType == FBXIT_SkeletalMesh) { ExtraProperties.Empty(); CollectChildPropertiesRecursive(AnimSequenceDataProp, ExtraProperties); // Before we add the import data properties we need to re-add any properties we want to appear above them in the UI TSharedRef<IPropertyHandle> ImportAnimProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, bImportAnimations)); // If we're importing an animation file we really don't need to ask this DetailBuilder.HideProperty(ImportAnimProp); if(ImportType == FBXIT_Animation) { ImportUI->bImportAnimations = true; } else { AnimCategory.AddProperty(ImportAnimProp); } for(TSharedPtr<IPropertyHandle> Handle : ExtraProperties) { FString CategoryMetaData = Handle->GetMetaData(TEXT("ImportCategory")); if(Handle->GetProperty()->GetOuter() == UFbxAnimSequenceImportData::StaticClass() && CategoryMetaData.IsEmpty()) { // Add to default anim category if no override specified IDetailPropertyRow& PropertyRow = AnimCategory.AddProperty(Handle); } else if(ImportType == FBXIT_Animation && !CategoryMetaData.IsEmpty()) { // Override category is available IDetailCategoryBuilder& CustomCategory = DetailBuilder.EditCategory(*CategoryMetaData); CustomCategory.AddProperty(Handle); } } } else { // Hide animation options CategoryDefaultProperties.Empty(); AnimCategory.GetDefaultProperties(CategoryDefaultProperties); for(TSharedRef<IPropertyHandle> Handle : CategoryDefaultProperties) { DetailBuilder.HideProperty(Handle); } } // Material Category IDetailCategoryBuilder& MaterialCategory = DetailBuilder.EditCategory("Material"); if(ImportType == FBXIT_Animation) { // In animation-only mode, hide the material display CategoryDefaultProperties.Empty(); MaterialCategory.GetDefaultProperties(CategoryDefaultProperties); for(TSharedRef<IPropertyHandle> Handle : CategoryDefaultProperties) { DetailBuilder.HideProperty(Handle); } } else { TSharedRef<IPropertyHandle> TextureDataProp = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UFbxImportUI, TextureImportData)); DetailBuilder.HideProperty(TextureDataProp); ExtraProperties.Empty(); CollectChildPropertiesRecursive(TextureDataProp, ExtraProperties); for(TSharedPtr<IPropertyHandle> Handle : ExtraProperties) { // We ignore base import data for this window. if(Handle->GetProperty()->GetOuter() == UFbxTextureImportData::StaticClass()) { MaterialCategory.AddProperty(Handle); } } } } void FFbxImportUIDetails::SetStaticMeshLODGroupWidget(IDetailPropertyRow& PropertyRow, const TSharedPtr<IPropertyHandle>& Handle) { TSharedPtr<SWidget> NameWidget; TSharedPtr<SWidget> ValueWidget; FDetailWidgetRow Row; PropertyRow.GetDefaultWidgets(NameWidget, ValueWidget, Row); FName InitialValue; ensure(Handle->GetValue(InitialValue) == FPropertyAccess::Success); int32 GroupIndex = LODGroupNames.Find(InitialValue); check(GroupIndex != INDEX_NONE); StaticMeshLODGroupPropertyHandle = Handle; TWeakPtr<IPropertyHandle> HandlePtr = Handle; const bool bShowChildren = true; PropertyRow.CustomWidget(bShowChildren) .NameContent() .MinDesiredWidth(Row.NameWidget.MinWidth) .MaxDesiredWidth(Row.NameWidget.MaxWidth) [ NameWidget.ToSharedRef() ] .ValueContent() .MinDesiredWidth(Row.ValueWidget.MinWidth) .MaxDesiredWidth(Row.ValueWidget.MaxWidth) .VAlign(VAlign_Center) [ SNew(STextComboBox) .Font(IDetailLayoutBuilder::GetDetailFont()) .OptionsSource(&LODGroupOptions) .InitiallySelectedItem(LODGroupOptions[GroupIndex]) .OnSelectionChanged(this, &FFbxImportUIDetails::OnLODGroupChanged, HandlePtr) ]; } void FFbxImportUIDetails::OnLODGroupChanged(TSharedPtr<FString> NewValue, ESelectInfo::Type SelectInfo, TWeakPtr<IPropertyHandle> HandlePtr) { TSharedPtr<IPropertyHandle> Handle = HandlePtr.Pin(); if (Handle.IsValid()) { int32 GroupIndex = LODGroupOptions.Find(NewValue); check(GroupIndex != INDEX_NONE); ensure(Handle->SetValue(LODGroupNames[GroupIndex]) == FPropertyAccess::Success); } } bool FFbxImportUIDetails::GetVertexOverrideColorEnabledState() const { uint8 VertexColorImportOption; check(VertexColorImportOptionHandle.IsValid()) ensure(VertexColorImportOptionHandle->GetValue(VertexColorImportOption) == FPropertyAccess::Success); return (VertexColorImportOption == EVertexColorImportOption::Override); } void FFbxImportUIDetails::CollectChildPropertiesRecursive(TSharedPtr<IPropertyHandle> Node, TArray<TSharedPtr<IPropertyHandle>>& OutProperties) { uint32 NodeNumChildren = 0; Node->GetNumChildren(NodeNumChildren); for(uint32 ChildIdx = 0 ; ChildIdx < NodeNumChildren ; ++ChildIdx) { TSharedPtr<IPropertyHandle> ChildHandle = Node->GetChildHandle(ChildIdx); CollectChildPropertiesRecursive(ChildHandle, OutProperties); if(ChildHandle->GetProperty()) { OutProperties.AddUnique(ChildHandle); } } } bool FFbxImportUIDetails::IsImportTypeMetaDataValid(EFBXImportType& ImportType, FString& MetaData) { TArray<FString> Types; MetaData.ParseIntoArray(Types, TEXT("|"), 1); switch(ImportType) { case FBXIT_StaticMesh: return Types.Contains(TEXT("StaticMesh")) || Types.Contains(TEXT("Mesh")); case FBXIT_SkeletalMesh: return Types.Contains(TEXT("SkeletalMesh")) || Types.Contains(TEXT("Mesh")); case FBXIT_Animation: return Types.Contains(TEXT("Animation")); default: return false; } } void FFbxImportUIDetails::MeshImportModeChanged() { if(CachedDetailBuilder) { ImportUI->MeshTypeToImport = ImportUI->MeshTypeToImport == FBXIT_SkeletalMesh ? FBXIT_StaticMesh : FBXIT_SkeletalMesh; ImportUI->bImportMesh = true; CachedDetailBuilder->ForceRefreshDetails(); } } void FFbxImportUIDetails::ImportMeshToggleChanged() { if(CachedDetailBuilder) { if(ImportUI->bImportMesh) { ImportUI->MeshTypeToImport = ImportUI->bImportAsSkeletal ? FBXIT_SkeletalMesh : FBXIT_StaticMesh; } else { ImportUI->MeshTypeToImport = FBXIT_Animation; } CachedDetailBuilder->ForceRefreshDetails(); } } #undef LOCTEXT_NAMESPACE
33.128571
149
0.78508
[ "mesh", "transform" ]
dc53eef0b3e86e47f6af1e58a3a9febecc93809f
5,210
hpp
C++
dart/math/ConfigurationSpace.hpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
dart/math/ConfigurationSpace.hpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
dart/math/ConfigurationSpace.hpp
malasiot/dart-vsim-octomap
d7afcacdcdcf7da688fb61caf1761b1309888ffe
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2011-2017, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DART_MATH_CONFIGURATIONSPACE_HPP_ #define DART_MATH_CONFIGURATIONSPACE_HPP_ #include <Eigen/Dense> #include "dart/math/MathTypes.hpp" #include "dart/math/Geometry.hpp" namespace dart { namespace math { //============================================================================== template <std::size_t Dimension> struct RealVectorSpace { static constexpr std::size_t NumDofs = Dimension; static constexpr int NumDofsEigen = static_cast<int>(Dimension); using TangentSpace = RealVectorSpace<NumDofs>; using Point = Eigen::Matrix<double, NumDofs, 1>; using EuclideanPoint = Eigen::Matrix<double, NumDofs, 1>; using Vector = Eigen::Matrix<double, NumDofs, 1>; using Matrix = Eigen::Matrix<double, NumDofs, NumDofs>; using JacobianMatrix = Eigen::Matrix<double, 6, NumDofs>; }; //============================================================================== // // These namespace-level definitions are required to enable ODR-use of static // constexpr member variables. // // See this StackOverflow answer: http://stackoverflow.com/a/14396189/111426 // template <std::size_t Dimension> constexpr std::size_t RealVectorSpace<Dimension>::NumDofs; template <std::size_t Dimension> constexpr int RealVectorSpace<Dimension>::NumDofsEigen; using NullSpace = RealVectorSpace<0u>; using R1Space = RealVectorSpace<1u>; using R2Space = RealVectorSpace<2u>; using R3Space = RealVectorSpace<3u>; //============================================================================== struct SO3Space { static constexpr std::size_t NumDofs = 3u; static constexpr int NumDofsEigen = 3; using TangentSpace = RealVectorSpace<NumDofs>; using Point = Eigen::Matrix3d; using EuclideanPoint = Eigen::Vector3d; using Vector = Eigen::Vector3d; using Matrix = Eigen::Matrix3d; using JacobianMatrix = Eigen::Matrix<double, 6, NumDofs>; }; //============================================================================== struct SE3Space { static constexpr std::size_t NumDofs = 6u; static constexpr int NumDofsEigen = 6; using TangentSpace = RealVectorSpace<NumDofs>; using Point = Eigen::Isometry3d; using EuclideanPoint = Eigen::Vector6d; using Vector = Eigen::Vector6d; using Matrix = Eigen::Matrix6d; using JacobianMatrix = Eigen::Matrix6d; }; struct MapsToManifoldPoint {}; //============================================================================== template <typename SpaceT> typename SpaceT::Matrix inverse(const typename SpaceT::Matrix& mat); //============================================================================== template <typename SpaceT> typename SpaceT::EuclideanPoint toEuclideanPoint(const typename SpaceT::Point& point); //============================================================================== template <typename SpaceT> typename SpaceT::Point toManifoldPoint(const typename SpaceT::EuclideanPoint& point); //============================================================================== template <typename SpaceT> typename SpaceT::Point integratePosition( const typename SpaceT::Point& pos, const typename SpaceT::Vector& vel, double dt); //============================================================================== template <typename SpaceT> typename SpaceT::Vector integrateVelocity( const typename SpaceT::Vector& vel, const typename SpaceT::Vector& acc, double dt); } // namespace math } // namespace dart #include "dart/math/detail/ConfigurationSpace.hpp" #endif // DART_MATH_CONFIGURATIONSPACE_HPP_
36.690141
80
0.638772
[ "geometry", "vector" ]
dc54caaafeeceead9c0e5b8bc4788db82e4d32e0
2,619
cpp
C++
test/c++/nda_arithmetic.cpp
Wentzell/nda
69106a64799e7942bf4b1b78fdadf3e7c9477c70
[ "Apache-2.0" ]
1
2022-03-08T06:35:19.000Z
2022-03-08T06:35:19.000Z
test/c++/nda_arithmetic.cpp
smile1103/nda
ff2239b910a5964942833e07d282a8cea32cb6fa
[ "Apache-2.0" ]
null
null
null
test/c++/nda_arithmetic.cpp
smile1103/nda
ff2239b910a5964942833e07d282a8cea32cb6fa
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019-2020 Simons Foundation // // 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.txt // // 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. // // Authors: Olivier Parcollet, Nils Wentzell #include "./test_common.hpp" TEST(NDA, ExprTemplate) { //NOLINT nda::array<long, 2> A(2, 3); for (long i = 0; i < 2; ++i) for (long j = 0; j < 3; ++j) A(i, j) = 10 * i + j; nda::array<long, 2> R; R = A + 10; EXPECT_EQ(R, (nda::array<long, 2>{{0 + 10, 1 + 10, 2 + 10}, {10 + 10, 11 + 10, 12 + 10}})); R = A - 10; EXPECT_EQ(R, (nda::array<long, 2>{{0 - 10, 1 - 10, 2 - 10}, {10 - 10, 11 - 10, 12 - 10}})); R = 2 * A; EXPECT_EQ(R, (nda::array<long, 2>{{0, 2, 4}, {20, 22, 24}})); long s = 2; R = s * A; EXPECT_EQ(R, (nda::array<long, 2>{{0, 2, 4}, {20, 22, 24}})); } // ============================================================== TEST(NDA, compound_ops) { //NOLINT nda::array<long, 2> A(2, 3); for (long i = 0; i < 2; ++i) for (long j = 0; j < 3; ++j) A(i, j) = 10 * i + j; auto A2 = A; A *= 2.0; EXPECT_EQ(A, (nda::array<long, 2>{{0, 2, 4}, {20, 22, 24}})); A2 /= 2.0; EXPECT_EQ(A2, (nda::array<long, 2>{{0, 0, 1}, {5, 5, 6}})); nda::array<double, 2> B(A); B /= 4; EXPECT_ARRAY_NEAR(B, (nda::array<double, 2>{{0.0, 0.5, 1.0}, {5.0, 5.5, 6.0}})); } // ============================================================== TEST(Vector, Ops) { //NOLINT nda::array<double, 1> V{1, 2, 3, 4, 5}; V *= 2; EXPECT_ARRAY_NEAR(V, (nda::array<double, 1>{2, 4, 6, 8, 10})); V[range(2, 4)] /= 2.0; EXPECT_ARRAY_NEAR(V, (nda::array<double, 1>{2, 4, 3, 4, 10})); V[range(0, 5, 2)] *= 10; EXPECT_ARRAY_NEAR(V, (nda::array<double, 1>{20, 4, 30, 4, 100})); } // ============================================================== TEST(Vector, Ops2) { //NOLINT nda::array<double, 1> V{1, 2, 3, 4, 5}; auto W = V; W += V; EXPECT_ARRAY_NEAR(V, (nda::array<double, 1>{1, 2, 3, 4, 5})); EXPECT_ARRAY_NEAR(W, (nda::array<double, 1>{2, 4, 6, 8, 10})); W -= V; EXPECT_ARRAY_NEAR(V, (nda::array<double, 1>{1, 2, 3, 4, 5})); EXPECT_ARRAY_NEAR(W, (nda::array<double, 1>{1, 2, 3, 4, 5})); }
27.568421
93
0.521573
[ "vector" ]
dc5988ae3aec4f82df6d5f7921e2134cb1bff05c
44,191
cpp
C++
source/games/sw/src/bunny.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
source/games/sw/src/bunny.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
source/games/sw/src/bunny.cpp
DosFreak/Raze
389f760d45748da28ba758f12be1be2a9ba9b4b2
[ "RSA-MD" ]
null
null
null
//------------------------------------------------------------------------- /* Copyright (C) 1997, 2005 - 3D Realms Entertainment This file is part of Shadow Warrior version 1.2 Shadow Warrior 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. Original Source: 1997 - Frank Maddin and Jim Norwood Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms */ //------------------------------------------------------------------------- #include "ns.h" #include "build.h" #include "names2.h" #include "panel.h" #include "tags.h" #include "ai.h" #include "pal.h" #include "sprite.h" #include "weapon.h" #include "misc.h" BEGIN_SW_NS short Bunny_Count = 0; ANIMATOR DoActorMoveJump; ANIMATOR DoBunnyMoveJump; ANIMATOR DoBunnyQuickJump; DECISION BunnyBattle[] = { {748, InitActorMoveCloser}, {750, InitActorAlertNoise}, {760, InitActorAttackNoise}, {1024, InitActorMoveCloser} }; DECISION BunnyOffense[] = { {600, InitActorMoveCloser}, {700, InitActorAlertNoise}, {1024, InitActorMoveCloser} }; DECISION BunnyBroadcast[] = { {21, InitActorAlertNoise}, {51, InitActorAmbientNoise}, {1024, InitActorDecide} }; DECISION BunnySurprised[] = { {500, InitActorRunAway}, {701, InitActorMoveCloser}, {1024, InitActorDecide} }; DECISION BunnyEvasive[] = { {500, InitActorWanderAround}, {1020, InitActorRunAway}, {1024, InitActorAmbientNoise} }; DECISION BunnyLostTarget[] = { {900, InitActorFindPlayer}, {1024, InitActorWanderAround} }; DECISION BunnyCloseRange[] = { {1024, InitActorAttack }, // {1024, InitActorReposition } }; DECISION BunnyWander[] = { {1024, InitActorReposition} }; PERSONALITY WhiteBunnyPersonality = { BunnyBattle, BunnyOffense, BunnyBroadcast, BunnySurprised, BunnyEvasive, BunnyLostTarget, BunnyCloseRange, BunnyCloseRange }; PERSONALITY BunnyPersonality = { BunnyEvasive, BunnyEvasive, BunnyEvasive, BunnyWander, BunnyWander, BunnyWander, BunnyEvasive, BunnyEvasive }; ATTRIBUTE BunnyAttrib = { {100, 120, 140, 180}, // Speeds {5, 0, -2, -4}, // Tic Adjusts 3, // MaxWeapons; { DIGI_BUNNYAMBIENT, 0, DIGI_BUNNYATTACK, DIGI_BUNNYATTACK, DIGI_BUNNYDIE2, 0, 0,0,0,0 } }; ATTRIBUTE WhiteBunnyAttrib = { {200, 220, 340, 380}, // Speeds {5, 0, -2, -4}, // Tic Adjusts 3, // MaxWeapons; { DIGI_BUNNYAMBIENT, 0, DIGI_BUNNYATTACK, DIGI_BUNNYATTACK, DIGI_BUNNYDIE2, 0, 0,0,0,0 } }; ////////////////////// // // BUNNY RUN // ////////////////////// #define BUNNY_RUN_RATE 10 ANIMATOR DoBunnyMove, NullBunny, DoActorDebris, DoBunnyGrowUp; STATE s_BunnyRun[5][6] = { { {BUNNY_RUN_R0 + 0, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[0][1]}, {BUNNY_RUN_R0 + 1, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[0][2]}, {BUNNY_RUN_R0 + 2, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[0][3]}, {BUNNY_RUN_R0 + 3, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[0][4]}, {BUNNY_RUN_R0 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyRun[0][5]}, {BUNNY_RUN_R0 + 4, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[0][0]}, }, { {BUNNY_RUN_R1 + 0, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[1][1]}, {BUNNY_RUN_R1 + 1, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[1][2]}, {BUNNY_RUN_R1 + 2, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[1][3]}, {BUNNY_RUN_R1 + 3, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[1][4]}, {BUNNY_RUN_R1 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyRun[1][5]}, {BUNNY_RUN_R1 + 4, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[1][0]}, }, { {BUNNY_RUN_R2 + 0, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[2][1]}, {BUNNY_RUN_R2 + 1, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[2][2]}, {BUNNY_RUN_R2 + 2, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[2][3]}, {BUNNY_RUN_R2 + 3, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[2][4]}, {BUNNY_RUN_R2 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyRun[2][5]}, {BUNNY_RUN_R2 + 4, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[2][0]}, }, { {BUNNY_RUN_R3 + 0, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[3][1]}, {BUNNY_RUN_R3 + 1, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[3][2]}, {BUNNY_RUN_R3 + 2, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[3][3]}, {BUNNY_RUN_R3 + 3, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[3][4]}, {BUNNY_RUN_R3 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyRun[3][5]}, {BUNNY_RUN_R3 + 4, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[3][0]}, }, { {BUNNY_RUN_R4 + 0, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[4][1]}, {BUNNY_RUN_R4 + 1, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[4][2]}, {BUNNY_RUN_R4 + 2, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[4][3]}, {BUNNY_RUN_R4 + 3, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[4][4]}, {BUNNY_RUN_R4 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyRun[4][5]}, {BUNNY_RUN_R4 + 4, BUNNY_RUN_RATE | SF_TIC_ADJUST, DoBunnyMove, &s_BunnyRun[4][0]}, } }; STATEp sg_BunnyRun[] = { &s_BunnyRun[0][0], &s_BunnyRun[1][0], &s_BunnyRun[2][0], &s_BunnyRun[3][0], &s_BunnyRun[4][0] }; ////////////////////// // // BUNNY STAND // ////////////////////// #define BUNNY_STAND_RATE 12 ANIMATOR DoBunnyEat; STATE s_BunnyStand[5][3] = { { {BUNNY_STAND_R0 + 0, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[0][1]}, {BUNNY_STAND_R0 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyStand[0][2]}, {BUNNY_STAND_R0 + 4, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[0][0]}, }, { {BUNNY_STAND_R1 + 0, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[1][1]}, {BUNNY_STAND_R1 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyStand[1][2]}, {BUNNY_STAND_R1 + 4, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[1][0]}, }, { {BUNNY_STAND_R2 + 0, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[2][1]}, {BUNNY_STAND_R2 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyStand[2][2]}, {BUNNY_STAND_R2 + 4, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[2][0]}, }, { {BUNNY_STAND_R3 + 0, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[3][1]}, {BUNNY_STAND_R3 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyStand[3][2]}, {BUNNY_STAND_R3 + 4, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[3][0]}, }, { {BUNNY_STAND_R4 + 0, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[4][1]}, {BUNNY_STAND_R4 + 4, SF_QUICK_CALL, DoBunnyGrowUp, &s_BunnyStand[4][2]}, {BUNNY_STAND_R4 + 4, BUNNY_STAND_RATE, DoBunnyEat, &s_BunnyStand[4][0]}, }, }; STATEp sg_BunnyStand[] = { s_BunnyStand[0], s_BunnyStand[1], s_BunnyStand[2], s_BunnyStand[3], s_BunnyStand[4] }; ////////////////////// // // BUNNY GET LAYED // ////////////////////// #define BUNNY_SCREW_RATE 16 ANIMATOR DoBunnyScrew; STATE s_BunnyScrew[5][2] = { { {BUNNY_STAND_R0 + 0, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[0][1]}, {BUNNY_STAND_R0 + 2, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[0][0]}, }, { {BUNNY_STAND_R1 + 0, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[1][1]}, {BUNNY_STAND_R1 + 2, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[1][0]}, }, { {BUNNY_STAND_R2 + 0, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[2][1]}, {BUNNY_STAND_R2 + 2, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[2][0]}, }, { {BUNNY_STAND_R3 + 0, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[3][1]}, {BUNNY_STAND_R3 + 2, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[3][0]}, }, { {BUNNY_STAND_R4 + 0, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[4][1]}, {BUNNY_STAND_R4 + 2, BUNNY_SCREW_RATE, DoBunnyScrew, &s_BunnyScrew[4][0]}, }, }; STATEp sg_BunnyScrew[] = { s_BunnyScrew[0], s_BunnyScrew[1], s_BunnyScrew[2], s_BunnyScrew[3], s_BunnyScrew[4] }; ////////////////////// // // BUNNY SWIPE // ////////////////////// #define BUNNY_SWIPE_RATE 8 ANIMATOR InitActorDecide; ANIMATOR InitBunnySlash; STATE s_BunnySwipe[5][8] = { { {BUNNY_SWIPE_R0 + 0, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[0][1]}, {BUNNY_SWIPE_R0 + 1, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[0][2]}, {BUNNY_SWIPE_R0 + 1, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[0][3]}, {BUNNY_SWIPE_R0 + 2, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[0][4]}, {BUNNY_SWIPE_R0 + 3, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[0][5]}, {BUNNY_SWIPE_R0 + 3, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[0][6]}, {BUNNY_SWIPE_R0 + 3, 0 | SF_QUICK_CALL, InitActorDecide, &s_BunnySwipe[0][7]}, {BUNNY_SWIPE_R0 + 3, BUNNY_SWIPE_RATE, DoBunnyMove, &s_BunnySwipe[0][7]}, }, { {BUNNY_SWIPE_R1 + 0, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[1][1]}, {BUNNY_SWIPE_R1 + 1, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[1][2]}, {BUNNY_SWIPE_R1 + 1, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[1][3]}, {BUNNY_SWIPE_R1 + 2, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[1][4]}, {BUNNY_SWIPE_R1 + 3, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[1][5]}, {BUNNY_SWIPE_R1 + 3, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[1][6]}, {BUNNY_SWIPE_R1 + 3, 0 | SF_QUICK_CALL, InitActorDecide, &s_BunnySwipe[1][7]}, {BUNNY_SWIPE_R1 + 3, BUNNY_SWIPE_RATE, DoBunnyMove, &s_BunnySwipe[1][7]}, }, { {BUNNY_SWIPE_R2 + 0, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[2][1]}, {BUNNY_SWIPE_R2 + 1, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[2][2]}, {BUNNY_SWIPE_R2 + 1, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[2][3]}, {BUNNY_SWIPE_R2 + 2, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[2][4]}, {BUNNY_SWIPE_R2 + 3, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[2][5]}, {BUNNY_SWIPE_R2 + 3, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[2][6]}, {BUNNY_SWIPE_R2 + 3, 0 | SF_QUICK_CALL, InitActorDecide, &s_BunnySwipe[2][7]}, {BUNNY_SWIPE_R2 + 3, BUNNY_SWIPE_RATE, DoBunnyMove, &s_BunnySwipe[2][7]}, }, { {BUNNY_SWIPE_R3 + 0, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[3][1]}, {BUNNY_SWIPE_R3 + 1, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[3][2]}, {BUNNY_SWIPE_R3 + 1, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[3][3]}, {BUNNY_SWIPE_R3 + 2, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[3][4]}, {BUNNY_SWIPE_R3 + 3, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[3][5]}, {BUNNY_SWIPE_R3 + 3, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[3][6]}, {BUNNY_SWIPE_R3 + 3, 0 | SF_QUICK_CALL, InitActorDecide, &s_BunnySwipe[3][7]}, {BUNNY_SWIPE_R3 + 3, BUNNY_SWIPE_RATE, DoBunnyMove, &s_BunnySwipe[3][7]}, }, { {BUNNY_SWIPE_R4 + 0, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[4][1]}, {BUNNY_SWIPE_R4 + 1, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[4][2]}, {BUNNY_SWIPE_R4 + 1, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[4][3]}, {BUNNY_SWIPE_R4 + 2, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[4][4]}, {BUNNY_SWIPE_R4 + 3, BUNNY_SWIPE_RATE, NullBunny, &s_BunnySwipe[4][5]}, {BUNNY_SWIPE_R4 + 3, 0 | SF_QUICK_CALL, InitBunnySlash, &s_BunnySwipe[4][6]}, {BUNNY_SWIPE_R4 + 3, 0 | SF_QUICK_CALL, InitActorDecide, &s_BunnySwipe[4][7]}, {BUNNY_SWIPE_R4 + 3, BUNNY_SWIPE_RATE, DoBunnyMove, &s_BunnySwipe[4][7]}, } }; STATEp sg_BunnySwipe[] = { &s_BunnySwipe[0][0], &s_BunnySwipe[1][0], &s_BunnySwipe[2][0], &s_BunnySwipe[3][0], &s_BunnySwipe[4][0] }; ////////////////////// // // BUNNY HEART - show players heart // ////////////////////// #define BUNNY_HEART_RATE 14 ANIMATOR DoBunnyStandKill; STATE s_BunnyHeart[5][4] = { { {BUNNY_SWIPE_R0 + 0, BUNNY_HEART_RATE, DoBunnyStandKill, &s_BunnyHeart[0][0]}, }, { {BUNNY_SWIPE_R1 + 0, BUNNY_HEART_RATE, DoBunnyStandKill, &s_BunnyHeart[1][0]}, }, { {BUNNY_SWIPE_R2 + 0, BUNNY_HEART_RATE, DoBunnyStandKill, &s_BunnyHeart[2][0]}, }, { {BUNNY_SWIPE_R3 + 0, BUNNY_HEART_RATE, DoBunnyStandKill, &s_BunnyHeart[3][0]}, }, { {BUNNY_SWIPE_R4 + 0, BUNNY_HEART_RATE, DoBunnyStandKill, &s_BunnyHeart[4][0]}, } }; STATEp sg_BunnyHeart[] = { &s_BunnyHeart[0][0], &s_BunnyHeart[1][0], &s_BunnyHeart[2][0], &s_BunnyHeart[3][0], &s_BunnyHeart[4][0] }; ////////////////////// // // BUNNY PAIN // ////////////////////// #define BUNNY_PAIN_RATE 38 ANIMATOR DoBunnyPain; STATE s_BunnyPain[5][1] = { { {BUNNY_SWIPE_R0 + 0, BUNNY_PAIN_RATE, DoBunnyPain, &s_BunnyPain[0][0]}, }, { {BUNNY_SWIPE_R0 + 0, BUNNY_PAIN_RATE, DoBunnyPain, &s_BunnyPain[1][0]}, }, { {BUNNY_SWIPE_R0 + 0, BUNNY_PAIN_RATE, DoBunnyPain, &s_BunnyPain[2][0]}, }, { {BUNNY_SWIPE_R0 + 0, BUNNY_PAIN_RATE, DoBunnyPain, &s_BunnyPain[3][0]}, }, { {BUNNY_SWIPE_R0 + 0, BUNNY_PAIN_RATE, DoBunnyPain, &s_BunnyPain[4][0]}, } }; STATEp sg_BunnyPain[] = { &s_BunnyPain[0][0], &s_BunnyPain[1][0], &s_BunnyPain[2][0], &s_BunnyPain[3][0], &s_BunnyPain[4][0] }; ////////////////////// // // BUNNY JUMP // ////////////////////// #define BUNNY_JUMP_RATE 25 STATE s_BunnyJump[5][6] = { { {BUNNY_RUN_R0 + 1, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[0][1]}, {BUNNY_RUN_R0 + 2, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[0][1]}, }, { {BUNNY_RUN_R1 + 1, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[1][1]}, {BUNNY_RUN_R1 + 2, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[1][1]}, }, { {BUNNY_RUN_R2 + 1, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[2][1]}, {BUNNY_RUN_R2 + 2, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[2][1]}, }, { {BUNNY_RUN_R3 + 1, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[3][1]}, {BUNNY_RUN_R3 + 2, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[3][1]}, }, { {BUNNY_RUN_R4 + 1, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[4][1]}, {BUNNY_RUN_R4 + 2, BUNNY_JUMP_RATE, DoBunnyMoveJump, &s_BunnyJump[4][1]}, } }; STATEp sg_BunnyJump[] = { &s_BunnyJump[0][0], &s_BunnyJump[1][0], &s_BunnyJump[2][0], &s_BunnyJump[3][0], &s_BunnyJump[4][0] }; ////////////////////// // // BUNNY FALL // ////////////////////// #define BUNNY_FALL_RATE 25 STATE s_BunnyFall[5][6] = { { {BUNNY_RUN_R0 + 3, BUNNY_FALL_RATE, DoBunnyMoveJump, &s_BunnyFall[0][0]}, }, { {BUNNY_RUN_R1 + 3, BUNNY_FALL_RATE, DoBunnyMoveJump, &s_BunnyFall[1][0]}, }, { {BUNNY_RUN_R2 + 3, BUNNY_FALL_RATE, DoBunnyMoveJump, &s_BunnyFall[2][0]}, }, { {BUNNY_RUN_R3 + 3, BUNNY_FALL_RATE, DoBunnyMoveJump, &s_BunnyFall[3][0]}, }, { {BUNNY_RUN_R4 + 3, BUNNY_FALL_RATE, DoBunnyMoveJump, &s_BunnyFall[4][0]}, } }; STATEp sg_BunnyFall[] = { &s_BunnyFall[0][0], &s_BunnyFall[1][0], &s_BunnyFall[2][0], &s_BunnyFall[3][0], &s_BunnyFall[4][0] }; ////////////////////// // // BUNNY JUMP ATTACK // ////////////////////// #define BUNNY_JUMP_ATTACK_RATE 35 int DoBunnyBeginJumpAttack(DSWActor* actor); STATE s_BunnyJumpAttack[5][6] = { { {BUNNY_RUN_R0 + 1, BUNNY_JUMP_ATTACK_RATE, NullBunny, &s_BunnyJumpAttack[0][1]}, {BUNNY_RUN_R0 + 1, 0 | SF_QUICK_CALL, DoBunnyBeginJumpAttack, &s_BunnyJumpAttack[0][2]}, {BUNNY_RUN_R0 + 2, BUNNY_JUMP_ATTACK_RATE, DoBunnyMoveJump, &s_BunnyJumpAttack[0][2]}, }, { {BUNNY_RUN_R1 + 1, BUNNY_JUMP_ATTACK_RATE, NullBunny, &s_BunnyJumpAttack[1][1]}, {BUNNY_RUN_R1 + 1, 0 | SF_QUICK_CALL, DoBunnyBeginJumpAttack, &s_BunnyJumpAttack[1][2]}, {BUNNY_RUN_R1 + 2, BUNNY_JUMP_ATTACK_RATE, DoBunnyMoveJump, &s_BunnyJumpAttack[1][2]}, }, { {BUNNY_RUN_R2 + 1, BUNNY_JUMP_ATTACK_RATE, NullBunny, &s_BunnyJumpAttack[2][1]}, {BUNNY_RUN_R2 + 1, 0 | SF_QUICK_CALL, DoBunnyBeginJumpAttack, &s_BunnyJumpAttack[2][2]}, {BUNNY_RUN_R2 + 2, BUNNY_JUMP_ATTACK_RATE, DoBunnyMoveJump, &s_BunnyJumpAttack[2][2]}, }, { {BUNNY_RUN_R3 + 1, BUNNY_JUMP_ATTACK_RATE, NullBunny, &s_BunnyJumpAttack[3][1]}, {BUNNY_RUN_R3 + 1, 0 | SF_QUICK_CALL, DoBunnyBeginJumpAttack, &s_BunnyJumpAttack[3][2]}, {BUNNY_RUN_R3 + 2, BUNNY_JUMP_ATTACK_RATE, DoBunnyMoveJump, &s_BunnyJumpAttack[3][2]}, }, { {BUNNY_RUN_R4 + 1, BUNNY_JUMP_ATTACK_RATE, NullBunny, &s_BunnyJumpAttack[4][1]}, {BUNNY_RUN_R4 + 1, 0 | SF_QUICK_CALL, DoBunnyBeginJumpAttack, &s_BunnyJumpAttack[4][2]}, {BUNNY_RUN_R4 + 2, BUNNY_JUMP_ATTACK_RATE, DoBunnyMoveJump, &s_BunnyJumpAttack[4][2]}, } }; STATEp sg_BunnyJumpAttack[] = { &s_BunnyJumpAttack[0][0], &s_BunnyJumpAttack[1][0], &s_BunnyJumpAttack[2][0], &s_BunnyJumpAttack[3][0], &s_BunnyJumpAttack[4][0] }; ////////////////////// // // BUNNY DIE // ////////////////////// #define BUNNY_DIE_RATE 16 ANIMATOR BunnySpew; STATE s_BunnyDie[] = { {BUNNY_DIE + 0, BUNNY_DIE_RATE, NullBunny, &s_BunnyDie[1]}, {BUNNY_DIE + 0, SF_QUICK_CALL, BunnySpew, &s_BunnyDie[2]}, {BUNNY_DIE + 1, BUNNY_DIE_RATE, NullBunny, &s_BunnyDie[3]}, {BUNNY_DIE + 2, BUNNY_DIE_RATE, NullBunny, &s_BunnyDie[4]}, {BUNNY_DIE + 2, BUNNY_DIE_RATE, NullBunny, &s_BunnyDie[5]}, {BUNNY_DEAD, BUNNY_DIE_RATE, DoActorDebris, &s_BunnyDie[5]}, }; #define BUNNY_DEAD_RATE 8 STATE s_BunnyDead[] = { {BUNNY_DIE + 0, BUNNY_DEAD_RATE, NullAnimator, &s_BunnyDie[1]}, {BUNNY_DIE + 0, SF_QUICK_CALL, BunnySpew, &s_BunnyDie[2]}, {BUNNY_DIE + 1, BUNNY_DEAD_RATE, NullAnimator, &s_BunnyDead[3]}, {BUNNY_DIE + 2, BUNNY_DEAD_RATE, NullAnimator, &s_BunnyDead[4]}, {BUNNY_DEAD, SF_QUICK_CALL, QueueFloorBlood, &s_BunnyDead[5]}, {BUNNY_DEAD, BUNNY_DEAD_RATE, DoActorDebris, &s_BunnyDead[5]}, }; STATEp sg_BunnyDie[] = { s_BunnyDie }; STATEp sg_BunnyDead[] = { s_BunnyDead }; STATE s_BunnyDeathJump[] = { {BUNNY_DIE + 0, BUNNY_DIE_RATE, DoActorDeathMove, &s_BunnyDeathJump[0]} }; STATE s_BunnyDeathFall[] = { {BUNNY_DIE + 1, BUNNY_DIE_RATE, DoActorDeathMove, &s_BunnyDeathFall[0]} }; STATEp sg_BunnyDeathJump[] = { s_BunnyDeathJump }; STATEp sg_BunnyDeathFall[] = { s_BunnyDeathFall }; /* STATEp *Stand[MAX_WEAPONS]; STATEp *Run; STATEp *Jump; STATEp *Fall; STATEp *Crawl; STATEp *Swim; STATEp *Fly; STATEp *Rise; STATEp *Sit; STATEp *Look; STATEp *Climb; STATEp *Pain; STATEp *Death1; STATEp *Death2; STATEp *Dead; STATEp *DeathJump; STATEp *DeathFall; STATEp *CloseAttack[2]; STATEp *Attack[6]; STATEp *Special[2]; */ ACTOR_ACTION_SET BunnyActionSet = { sg_BunnyStand, sg_BunnyRun, sg_BunnyJump, sg_BunnyFall, nullptr, // sg_BunnyCrawl, nullptr, // sg_BunnySwim, nullptr, // sg_BunnyFly, nullptr, // sg_BunnyRise, nullptr, // sg_BunnySit, nullptr, // sg_BunnyLook, nullptr, // climb sg_BunnyPain, sg_BunnyDie, nullptr, sg_BunnyDead, sg_BunnyDeathJump, sg_BunnyDeathFall, {nullptr}, {1024}, {nullptr}, {1024}, {sg_BunnyHeart, sg_BunnyRun}, nullptr, nullptr }; ACTOR_ACTION_SET BunnyWhiteActionSet = { sg_BunnyStand, sg_BunnyRun, sg_BunnyJump, sg_BunnyFall, nullptr, // sg_BunnyCrawl, nullptr, // sg_BunnySwim, nullptr, // sg_BunnyFly, nullptr, // sg_BunnyRise, nullptr, // sg_BunnySit, nullptr, // sg_BunnyLook, nullptr, // climb sg_BunnyPain, // pain sg_BunnyDie, nullptr, sg_BunnyDead, sg_BunnyDeathJump, sg_BunnyDeathFall, {sg_BunnySwipe}, {1024}, // {sg_BunnyJumpAttack, sg_BunnySwipe}, // {800, 1024}, {sg_BunnySwipe}, {1024}, {sg_BunnyHeart, sg_BunnySwipe}, nullptr, nullptr }; int SetupBunny(short SpriteNum) { SPRITEp sp = &sprite[SpriteNum]; USERp u; ANIMATOR DoActorDecide; if (TEST(sp->cstat, CSTAT_SPRITE_RESTORE)) { u = User[SpriteNum].Data(); ASSERT(u); } else { u = SpawnUser(SpriteNum, BUNNY_RUN_R0, s_BunnyRun[0]); u->Health = 10; } Bunny_Count++; //if(Bunny_Count > 20) // { // KillSprite(SpriteNum); // Bunny_Count--; // return(0); // } ChangeState(SpriteNum, s_BunnyRun[0]); u->StateEnd = s_BunnyDie; u->Rot = sg_BunnyRun; //sp->xrepeat = 64; //sp->yrepeat = 64; u->ShellNum = 0; // Not Pregnant right now u->FlagOwner = 0; sp->clipdist = (150) >> 2; if (sp->pal == PALETTE_PLAYER1) { EnemyDefaults(SpriteNum, &BunnyWhiteActionSet, &WhiteBunnyPersonality); u->Attrib = &WhiteBunnyAttrib; sp->xrepeat = 96; sp->yrepeat = 90; sp->clipdist = 200>>2; if (!TEST(sp->cstat, CSTAT_SPRITE_RESTORE)) u->Health = 60; } else if (sp->pal == PALETTE_PLAYER8) // Male Rabbit { EnemyDefaults(SpriteNum, &BunnyActionSet, &BunnyPersonality); u->Attrib = &BunnyAttrib; //sp->xrepeat = 76; //sp->yrepeat = 70; //sp->shade = 0; // darker if (!TEST(sp->cstat, CSTAT_SPRITE_RESTORE)) u->Health = 20; u->Flag1 = 0; } else { // Female Rabbit EnemyDefaults(SpriteNum, &BunnyActionSet, &BunnyPersonality); u->Attrib = &BunnyAttrib; u->spal = sp->pal = PALETTE_PLAYER0; u->Flag1 = SEC(5); //sp->shade = 0; // darker } DoActorSetSpeed(SpriteNum, FAST_SPEED); SET(u->Flags, SPR_XFLIP_TOGGLE); u->zclip = Z(16); u->floor_dist = Z(8); u->ceiling_dist = Z(8); u->lo_step = Z(16); return 0; } int GetBunnyJumpHeight(int jump_speed, int jump_grav) { int jump_iterations; int height; jump_speed = abs(jump_speed); jump_iterations = jump_speed / (jump_grav * ACTORMOVETICS); height = jump_speed * jump_iterations * ACTORMOVETICS; height = DIV256(height); return DIV2(height); } int PickBunnyJumpSpeed(short SpriteNum, int pix_height) { USERp u = User[SpriteNum].Data(); ASSERT(pix_height < 128); u->jump_speed = -600; u->jump_grav = 8; while (true) { if (GetBunnyJumpHeight(u->jump_speed, u->jump_grav) > pix_height + 20) break; u->jump_speed -= 100; ASSERT(u->jump_speed > -3000); } return u->jump_speed; } // // JUMP ATTACK // int DoBunnyBeginJumpAttack(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; SPRITEp psp = User[SpriteNum]->tgt_sp; short tang; tang = getangle(psp->x - sp->x, psp->y - sp->y); if (move_sprite(SpriteNum, bcos(tang, -7), bsin(tang, -7), 0L, u->ceiling_dist, u->floor_dist, CLIPMASK_ACTOR, ACTORMOVETICS)) sp->ang = NORM_ANGLE(sp->ang + 1024) + (RANDOM_NEG(256, 6) >> 6); else sp->ang = NORM_ANGLE(tang + (RANDOM_NEG(256, 6) >> 6)); DoActorSetSpeed(SpriteNum, FAST_SPEED); //u->jump_speed = -800; PickJumpMaxSpeed(SpriteNum, -400); // was -800 SET(u->Flags, SPR_JUMPING); RESET(u->Flags, SPR_FALLING); // set up individual actor jump gravity u->jump_grav = 17; // was 8 // if I didn't do this here they get stuck in the air sometimes DoActorZrange(SpriteNum); DoJump(SpriteNum); return 0; } int DoBunnyMoveJump(DSWActor* actor) { USER* u = actor->u(); SPRITEp sp = u->s(); if (TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { int nx, ny; // Move while jumping nx = MulScale(sp->xvel, bcos(sp->ang), 14); ny = MulScale(sp->xvel, bsin(sp->ang), 14); move_actor(u->SpriteNum, nx, ny, 0L); if (TEST(u->Flags, SPR_JUMPING)) DoActorJump(actor); else DoActorFall(actor); } DoActorZrange(u->SpriteNum); if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { // if (DoBunnyQuickJump(SpriteNum)) // return (0); InitActorDecide(actor); } return 0; } int DoPickCloseBunny(USERp u) { USERp tu; SPRITEp sp = u->s(),tsp; int dist, near_dist = 1000, a,b,c; int i; //short BunnyCount=0, Bunny_Result = -1; // if actor can still see the player int look_height = SPRITEp_TOS(sp); bool ICanSee = false; StatIterator it(STAT_ENEMY); while ((i = it.NextIndex()) >= 0) { tsp = &sprite[i]; tu = User[i].Data(); if (sp == tsp) continue; if (tu->ID != BUNNY_RUN_R0) continue; DISTANCE(tsp->x, tsp->y, sp->x, sp->y, dist, a, b, c); if (dist > near_dist) continue; ICanSee = FAFcansee(sp->x, sp->y, look_height, sp->sectnum, tsp->x, tsp->y, SPRITEp_UPPER(tsp), tsp->sectnum); if (ICanSee && dist < near_dist && tu->ID == BUNNY_RUN_R0) { near_dist = dist; u->tgt_sp = u->lo_sp = tsp; //Bunny_Result = i; return i; } } return -1; } int DoBunnyQuickJump(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; if (u->spal != PALETTE_PLAYER8) return false; if (!u->lo_sp && u->spal == PALETTE_PLAYER8 && MoveSkip4) DoPickCloseBunny(u); // Random Chance of like sexes fighting if (u->lo_sp) { short hit_sprite = short(u->lo_sp - sprite); SPRITEp tsp = u->lo_sp; USERp tu = User[hit_sprite].Data(); if (!tu || tu->ID != BUNNY_RUN_R0) return false; // Not mature enough yet if (sp->xrepeat != 64 || sp->yrepeat != 64) return false; if (tsp->xrepeat != 64 || tsp->yrepeat != 64) return false; // Kill a rival // Only males fight if (tu->spal == sp->pal && RandomRange(1000) > 995) { if (u->spal == PALETTE_PLAYER8 && tu->spal == PALETTE_PLAYER8) { PlaySound(DIGI_BUNNYATTACK, sp, v3df_follow); PlaySound(DIGI_BUNNYDIE2, tsp, v3df_follow); tu->Health = 0; // Blood fountains InitBloodSpray(hit_sprite,true,-1); if (SpawnShrap(hit_sprite, SpriteNum)) { SetSuicide(hit_sprite); } else DoActorDie(hit_sprite, SpriteNum); Bunny_Count--; // Bunny died u->lo_sp = nullptr; return true; } } } // Get layed! if (u->lo_sp && u->spal == PALETTE_PLAYER8) // Only males check this { short hit_sprite = short(u->lo_sp - sprite); SPRITEp tsp = u->lo_sp; USERp tu = User[hit_sprite].Data(); if (!tu || tu->ID != BUNNY_RUN_R0) return false; // Not mature enough to mate yet if (sp->xrepeat != 64 || sp->yrepeat != 64) return false; if (tsp->xrepeat != 64 || tsp->yrepeat != 64) return false; if (tu->ShellNum <= 0 && tu->WaitTics <= 0 && u->WaitTics <= 0) { if (TEST(tsp->extra, SPRX_PLAYER_OR_ENEMY)) { PLAYERp pp = nullptr; if (RandomRange(1000) < 995 && tu->spal != PALETTE_PLAYER0) return false; DoActorPickClosePlayer(SpriteNum); if (User[u->tgt_sp-sprite]->PlayerP) pp = User[u->tgt_sp-sprite]->PlayerP; if (tu->spal != PALETTE_PLAYER0) { if (tu->Flag1 > 0) return false; tu->FlagOwner = 1; // FAG! tu->Flag1 = SEC(10); if (pp) { short choose_snd; int fagsnds[] = {DIGI_FAGRABBIT1,DIGI_FAGRABBIT2,DIGI_FAGRABBIT3}; if (pp == Player+myconnectindex) { choose_snd = STD_RANDOM_RANGE(2<<8)>>8; if (FAFcansee(sp->x,sp->y,SPRITEp_TOS(sp),sp->sectnum,pp->posx, pp->posy, pp->posz, pp->cursectnum) && FACING(sp, u->tgt_sp)) PlayerSound(fagsnds[choose_snd], v3df_doppler|v3df_follow|v3df_dontpan,pp); } } } else { if (pp && RandomRange(1000) > 200) { short choose_snd; int straightsnds[] = {DIGI_RABBITHUMP1,DIGI_RABBITHUMP2, DIGI_RABBITHUMP3,DIGI_RABBITHUMP4}; if (pp == Player+myconnectindex) { choose_snd = STD_RANDOM_RANGE(3<<8)>>8; if (FAFcansee(sp->x,sp->y,SPRITEp_TOS(sp),sp->sectnum,pp->posx, pp->posy, pp->posz, pp->cursectnum) && FACING(sp, u->tgt_sp)) PlayerSound(straightsnds[choose_snd], v3df_doppler|v3df_follow|v3df_dontpan,pp); } } } sp->x = tsp->x; // Mount up little bunny sp->y = tsp->y; sp->ang = tsp->ang; sp->ang = NORM_ANGLE(sp->ang + 1024); HelpMissileLateral(SpriteNum, 2000L); sp->ang = tsp->ang; u->Vis = sp->ang; // Remember angles for later tu->Vis = tsp->ang; NewStateGroup(SpriteNum, sg_BunnyScrew); NewStateGroup(hit_sprite, sg_BunnyScrew); u->WaitTics = tu->WaitTics = SEC(10); // Mate for this long return true; } } } return false; } int NullBunny(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; if (TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { if (TEST(u->Flags, SPR_JUMPING)) DoActorJump(actor); else DoActorFall(actor); } // stay on floor unless doing certain things if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) KeepActorOnFloor(SpriteNum); if (TEST(u->Flags,SPR_SLIDING)) DoActorSlide(actor); DoActorSectorDamage(actor); return 0; } int DoBunnyPain(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; NullBunny(actor); if ((u->WaitTics -= ACTORMOVETICS) <= 0) InitActorDecide(actor); return 0; } int DoBunnyRipHeart(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; SPRITEp tsp = u->tgt_sp; NewStateGroup(SpriteNum, sg_BunnyHeart); u->WaitTics = 6 * 120; // player face bunny tsp->ang = getangle(sp->x - tsp->x, sp->y - tsp->y); return 0; } int DoBunnyStandKill(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; NullBunny(actor); // Growl like the bad ass bunny you are! if (RandomRange(1000) > 800) PlaySound(DIGI_BUNNYATTACK, sp, v3df_none); if ((u->WaitTics -= ACTORMOVETICS) <= 0) NewStateGroup(SpriteNum, sg_BunnyRun); return 0; } void BunnyHatch(short Weapon) { SPRITEp wp = &sprite[Weapon]; USERp wu = User[Weapon].Data(); short New,i; SPRITEp np; USERp nu; #define MAX_BUNNYS 1 short rip_ang[MAX_BUNNYS]; rip_ang[0] = RANDOM_P2(2048); for (i = 0; i < MAX_BUNNYS; i++) { New = COVERinsertsprite(wp->sectnum, STAT_DEFAULT); auto actorNew = &swActors[New]; np = &sprite[New]; memset(np,0,sizeof(SPRITE)); np->sectnum = wp->sectnum; np->statnum = STAT_DEFAULT; np->x = wp->x; np->y = wp->y; np->z = wp->z; np->owner = -1; np->xrepeat = 30; // Baby size np->yrepeat = 24; np->ang = rip_ang[i]; np->pal = 0; SetupBunny(New); nu = User[New].Data(); np->shade = wp->shade; // make immediately active SET(nu->Flags, SPR_ACTIVE); if (RandomRange(1000) > 500) // Boy or Girl? nu->spal = np->pal = PALETTE_PLAYER0; // Girl else { nu->spal = np->pal = PALETTE_PLAYER8; // Boy // Oops, mommy died giving birth to a boy if (RandomRange(1000) > 500) { wu->Health = 0; Bunny_Count--; // Bunny died // Blood fountains InitBloodSpray(Weapon,true,-1); if (SpawnShrap(Weapon, New)) { SetSuicide(Weapon); } else DoActorDie(Weapon, New); } } nu->ShellNum = 0; // Not Pregnant right now NewStateGroup(New, nu->ActorActionSet->Jump); nu->ActorActionFunc = DoActorMoveJump; DoActorSetSpeed(New, FAST_SPEED); PickJumpMaxSpeed(New, -600); SET(nu->Flags, SPR_JUMPING); RESET(nu->Flags, SPR_FALLING); nu->jump_grav = 8; // if I didn't do this here they get stuck in the air sometimes DoActorZrange(New); DoActorJump(actorNew); } } int BunnyHatch2(short Weapon) { SPRITEp wp = &sprite[Weapon]; short New; SPRITEp np; USERp nu; New = COVERinsertsprite(wp->sectnum, STAT_DEFAULT); auto actorNew = &swActors[New]; np = &sprite[New]; memset(np,0,sizeof(SPRITE)); np->sectnum = wp->sectnum; np->statnum = STAT_DEFAULT; np->x = wp->x; np->y = wp->y; np->z = wp->z; np->owner = -1; np->xrepeat = 30; // Baby size np->yrepeat = 24; np->ang = RANDOM_P2(2048); np->pal = 0; SetupBunny(New); nu = User[New].Data(); np->shade = wp->shade; // make immediately active SET(nu->Flags, SPR_ACTIVE); if (RandomRange(1000) > 500) // Boy or Girl? { nu->spal = np->pal = PALETTE_PLAYER0; // Girl nu->Flag1 = SEC(5); } else { nu->spal = np->pal = PALETTE_PLAYER8; // Boy nu->Flag1 = 0; } nu->ShellNum = 0; // Not Pregnant right now NewStateGroup(New, nu->ActorActionSet->Jump); nu->ActorActionFunc = DoActorMoveJump; DoActorSetSpeed(New, FAST_SPEED); if (TEST_BOOL3(wp)) { PickJumpMaxSpeed(New, -600-RandomRange(600)); np->xrepeat = np->yrepeat = 64; np->xvel = 150 + RandomRange(1000); nu->Health = 1; // Easy to pop. Like shootn' skeet. np->ang -= RandomRange(128); np->ang += RandomRange(128); } else PickJumpMaxSpeed(New, -600); SET(nu->Flags, SPR_JUMPING); RESET(nu->Flags, SPR_FALLING); nu->jump_grav = 8; nu->FlagOwner = 0; nu->active_range = 75000; // Set it far // if I didn't do this here they get stuck in the air sometimes DoActorZrange(New); DoActorJump(actorNew); return New; } int DoBunnyMove(DSWActor* actor) { USER* u = actor->u(); auto sp = u->s(); int SpriteNum = u->SpriteNum; // Parental lock crap if (TEST(sp->cstat, CSTAT_SPRITE_INVISIBLE)) RESET(sp->cstat, CSTAT_SPRITE_INVISIBLE); // Turn em' back on // Sometimes they just won't die! if (u->Health <= 0) SetSuicide(SpriteNum); if (u->scale_speed) { DoScaleSprite(actor); } if (TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { if (TEST(u->Flags, SPR_JUMPING)) DoActorJump(actor); else DoActorFall(actor); } // if on a player/enemy sprite jump quickly if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { DoBunnyQuickJump(actor); } if (TEST(u->Flags, SPR_SLIDING)) DoActorSlide(actor); if (u->track >= 0) ActorFollowTrack(SpriteNum, ACTORMOVETICS); else (*u->ActorActionFunc)(actor); // stay on floor unless doing certain things if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) KeepActorOnFloor(SpriteNum); DoActorSectorDamage(actor); if (RandomRange(1000) > 985 && sp->pal != PALETTE_PLAYER1 && u->track < 0) { switch (sector[sp->sectnum].floorpicnum) { case 153: case 154: case 193: case 219: case 2636: case 2689: case 3561: case 3562: case 3563: case 3564: NewStateGroup(SpriteNum,sg_BunnyStand); break; default: sp->ang = NORM_ANGLE(RandomRange(2048 << 6) >> 6); u->jump_speed = -350; DoActorBeginJump(actor); u->ActorActionFunc = DoActorMoveJump; break; } } return 0; } int BunnySpew(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; //InitBloodSpray(SpriteNum,true,-1); InitBloodSpray(SpriteNum,true,-1); return 0; } int DoBunnyEat(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; if (TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { if (TEST(u->Flags, SPR_JUMPING)) DoActorJump(actor); else DoActorFall(actor); } // if on a player/enemy sprite jump quickly if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { DoBunnyQuickJump(actor); } if (TEST(u->Flags, SPR_SLIDING)) DoActorSlide(actor); // stay on floor unless doing certain things if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) KeepActorOnFloor(SpriteNum); DoActorSectorDamage(actor); switch (sector[sp->sectnum].floorpicnum) { case 153: case 154: case 193: case 219: case 2636: case 2689: case 3561: case 3562: case 3563: case 3564: if (RandomRange(1000) > 970) NewStateGroup(SpriteNum,sg_BunnyRun); break; default: NewStateGroup(SpriteNum,sg_BunnyRun); break; } return 0; } int DoBunnyScrew(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; if (TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) { if (TEST(u->Flags, SPR_JUMPING)) DoActorJump(actor); else DoActorFall(actor); } if (TEST(u->Flags, SPR_SLIDING)) DoActorSlide(actor); // stay on floor unless doing certain things if (!TEST(u->Flags, SPR_JUMPING | SPR_FALLING)) KeepActorOnFloor(SpriteNum); DoActorSectorDamage(actor); if (RandomRange(1000) > 990) // Bunny sex sounds { PlaySound(DIGI_BUNNYATTACK, sp, v3df_follow); } u->WaitTics -= ACTORMOVETICS; if ((u->FlagOwner || u->spal == PALETTE_PLAYER0) && u->WaitTics > 0) // Keep Girl still NewStateGroup(SpriteNum,sg_BunnyScrew); if (u->spal == PALETTE_PLAYER0 && u->WaitTics <= 0) // Female has baby { u->Flag1 = SEC(5); // Count down to babies u->ShellNum = 1; // She's pregnant now } if (u->WaitTics <= 0) { RESET(sp->cstat, CSTAT_SPRITE_INVISIBLE); // Turn em' back on u->FlagOwner = 0; NewStateGroup(SpriteNum,sg_BunnyRun); } return 0; } int DoBunnyGrowUp(DSWActor* actor) { USER* u = actor->u(); int SpriteNum = u->SpriteNum; SPRITEp sp = &sprite[SpriteNum]; if (sp->pal == PALETTE_PLAYER1) return 0; // Don't bother white bunnies if ((u->Counter -= ACTORMOVETICS) <= 0) { if ((++sp->xrepeat) > 64) sp->xrepeat = 64; if ((++sp->yrepeat) > 64) sp->yrepeat = 64; u->Counter = 60; } // Don't go homo too much! if (sp->pal != PALETTE_PLAYER0 && u->Flag1 > 0) u->Flag1 -= ACTORMOVETICS; // Gestation period for female rabbits if (sp->pal == PALETTE_PLAYER0 && u->ShellNum > 0) { if ((u->Flag1 -= ACTORMOVETICS) <= 0) { if (Bunny_Count < 20) { PlaySound(DIGI_BUNNYDIE2, sp, v3df_follow); BunnyHatch(SpriteNum); // Baby time } u->ShellNum = 0; // Not pregnent anymore } } return 0; } #include "saveable.h" static saveable_code saveable_bunny_code[] = { SAVE_CODE(SetupBunny), SAVE_CODE(GetBunnyJumpHeight), SAVE_CODE(PickBunnyJumpSpeed), SAVE_CODE(DoBunnyBeginJumpAttack), SAVE_CODE(DoBunnyMoveJump), SAVE_CODE(DoPickCloseBunny), SAVE_CODE(DoBunnyQuickJump), SAVE_CODE(NullBunny), SAVE_CODE(DoBunnyPain), SAVE_CODE(DoBunnyRipHeart), SAVE_CODE(DoBunnyStandKill), SAVE_CODE(BunnyHatch), SAVE_CODE(BunnyHatch2), SAVE_CODE(DoBunnyMove), SAVE_CODE(BunnySpew), SAVE_CODE(DoBunnyEat), SAVE_CODE(DoBunnyScrew), SAVE_CODE(DoBunnyGrowUp), }; static saveable_data saveable_bunny_data[] = { SAVE_DATA(BunnyBattle), SAVE_DATA(BunnyOffense), SAVE_DATA(BunnyBroadcast), SAVE_DATA(BunnySurprised), SAVE_DATA(BunnyEvasive), SAVE_DATA(BunnyLostTarget), SAVE_DATA(BunnyCloseRange), SAVE_DATA(BunnyWander), SAVE_DATA(WhiteBunnyPersonality), SAVE_DATA(BunnyPersonality), SAVE_DATA(WhiteBunnyAttrib), SAVE_DATA(BunnyAttrib), SAVE_DATA(s_BunnyRun), SAVE_DATA(sg_BunnyRun), SAVE_DATA(s_BunnyStand), SAVE_DATA(sg_BunnyStand), SAVE_DATA(s_BunnyScrew), SAVE_DATA(sg_BunnyScrew), SAVE_DATA(s_BunnySwipe), SAVE_DATA(sg_BunnySwipe), SAVE_DATA(s_BunnyHeart), SAVE_DATA(sg_BunnyHeart), SAVE_DATA(s_BunnyPain), SAVE_DATA(sg_BunnyPain), SAVE_DATA(s_BunnyJump), SAVE_DATA(sg_BunnyJump), SAVE_DATA(s_BunnyFall), SAVE_DATA(sg_BunnyFall), SAVE_DATA(s_BunnyJumpAttack), SAVE_DATA(sg_BunnyJumpAttack), SAVE_DATA(s_BunnyDie), SAVE_DATA(sg_BunnyDie), SAVE_DATA(s_BunnyDead), SAVE_DATA(sg_BunnyDead), SAVE_DATA(s_BunnyDeathJump), SAVE_DATA(sg_BunnyDeathJump), SAVE_DATA(s_BunnyDeathFall), SAVE_DATA(sg_BunnyDeathFall), SAVE_DATA(BunnyActionSet), SAVE_DATA(BunnyWhiteActionSet), }; saveable_module saveable_bunny = { // code saveable_bunny_code, SIZ(saveable_bunny_code), // data saveable_bunny_data, SIZ(saveable_bunny_data) }; END_SW_NS
27.094421
153
0.585594
[ "3d" ]
dc622a2d48ee4a64b0fc66507a5d34018e09135a
48,738
cpp
C++
src/C++/Core/cpuComputes.cpp
cesmix-mit/MDP
746e4f4aead5911ddeda77b0d2c117e3b70cc5c4
[ "MIT" ]
1
2021-09-15T03:09:46.000Z
2021-09-15T03:09:46.000Z
src/C++/Core/cpuComputes.cpp
cesmix-mit/MDP
746e4f4aead5911ddeda77b0d2c117e3b70cc5c4
[ "MIT" ]
1
2022-01-24T16:11:07.000Z
2022-01-24T16:11:07.000Z
src/C++/Core/cpuComputes.cpp
cesmix-mit/MDP
746e4f4aead5911ddeda77b0d2c117e3b70cc5c4
[ "MIT" ]
null
null
null
/*************************************************************************** Molecular Dynamics Potentials (MDP) CESMIX-MIT Project Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com) ***************************************************************************/ #ifndef MDP_CPUCOMPUTES #define MDP_CPUCOMPUTES #include <math.h> #include <algorithm> // #define IMGMASK 1023 // #define IMGMAX 512 // #define IMGBITS 10 // #define IMG2BITS 20 // using std::min; // using std::max; #define SWAP(a,b) do { \ tmp = a; a = b; b = tmp; \ } while(0) #define ISWAP(a,b) do { \ itmp = a; a = b; b = itmp; \ } while(0) template <typename T> void cpuPackIntProperty(T *buf, int *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; buf[n + nvalues*i] = (T) prop[m + mvalues*i]; } } template void cpuPackIntProperty(double *buf, int *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template void cpuPackIntProperty(float *buf, int *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template <typename T> void cpuPackIntProperty(T *buf, int *prop, int *type, int *ilist, int n, int nvalues, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; buf[n + nvalues*i] = (T) prop[type[i]]; } } template void cpuPackIntProperty(double *buf, int *prop, int *type, int *ilist, int n, int nvalues, int inum); template void cpuPackIntProperty(float *buf, int *prop, int *type, int *ilist, int n, int nvalues, int inum); template <typename T> void cpuPackFloatProperty(T *buf, T *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; buf[n + nvalues*i] = prop[m + mvalues*i]; } } template void cpuPackFloatProperty(double *buf, double *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template void cpuPackFloatProperty(float *buf, float *prop, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template <typename T> void cpuPackFloatProperty(T *buf, T *prop, T a, T b, int *ilist, int m, int mvalues, int n, int nvalues, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; buf[n + nvalues*i] = a*prop[m + mvalues*i] + b; } } template void cpuPackFloatProperty(double *buf, double *prop, double a, double b, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template void cpuPackFloatProperty(float *buf, float *prop, float a, float b, int *ilist, int m, int mvalues, int n, int nvalues, int inum); template <typename T> void cpuPackFloatProperty(T *buf, T *prop, int *type, int *ilist, int n, int nvalues, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; buf[n + nvalues*i] = prop[type[i]]; } } template void cpuPackFloatProperty(double *buf, double *prop, int *type, int *ilist, int n, int nvalues, int inum); template void cpuPackFloatProperty(float *buf, float *prop, int *type, int *ilist, int n, int nvalues, int inum); template <typename T> T cpuComputeMass(T *amass, T *mass, int *type, int *ilist, int inum) { T masstotal; cpuPackFloatProperty(amass, mass, type, ilist, 0, 1, inum); masstotal = cpuArraySum(amass, inum); return masstotal; } template double cpuComputeMass(double *amass, double *mass, int *type, int *ilist, int inum); template float cpuComputeMass(float *amass, float *mass, int *type, int *ilist, int inum); template <typename T> void cpuComputeXCM(T *xcm, T *x, T *mass, T *box, T masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum) { xcm[0] = xcm[1] = xcm[2] = 0.0; T unwrap[3]; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; cpuUnmap(unwrap, &x[i*dim], box, &image[i*dim], triclinic, dim); xcm[0] += unwrap[0] * massone; xcm[1] += unwrap[1] * massone; if (dim==3) xcm[2] += unwrap[2] * massone; } //MPI_Allreduce(cmone,xcm,3,MPI_DOUBLE,MPI_SUM,world); if (masstotal > 0.0) { xcm[0] /= masstotal; xcm[1] /= masstotal; if (dim==3) xcm[2] /= masstotal; } } template void cpuComputeXCM(double *xcm, double *x, double *mass, double *box, double masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template void cpuComputeXCM(float *xcm, float *x, float *mass, float *box, float masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template <typename T> void cpuComputeVCM(T *vcm, T *v, T *mass, T masstotal, int *ilist, int *type, int dim, int inum) { vcm[0] = vcm[1] = vcm[2] = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; vcm[0] += v[i*dim+0]*massone; vcm[1] += v[i*dim+1]*massone; if (dim==3) vcm[2] += v[i*dim+2]*massone; } //MPI_Allreduce(p,xcm,3,MPI_DOUBLE,MPI_SUM,world); if (masstotal > 0.0) { vcm[0] /= masstotal; vcm[1] /= masstotal; if (dim==3) vcm[2] /= masstotal; } } template void cpuComputeVCM(double *vcm, double *v, double *mass, double masstotal, int *ilist, int *type, int dim, int inum); template void cpuComputeVCM(float *vcm, float *v, float *mass, float masstotal, int *ilist, int *type, int dim, int inum); template <typename T> T cpuComputeGyration(T *xcm, T *x, T *mass, T *box, T masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum) { T unwrap[3]; T rg = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; cpuUnmap(unwrap, &x[i*dim], box, &image[i*dim], triclinic, dim); T dx = unwrap[0] - xcm[0]; T dy = unwrap[1] - xcm[1]; T dz = (dim==3) ? (unwrap[2] - xcm[2]) : 0.0; rg += (dx*dx + dy*dy + dz*dz) * massone; } if (masstotal > 0.0) return sqrt(rg/masstotal); return 0.0; } template double cpuComputeGyration(double *xcm, double *x, double *mass, double *box, double masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template float cpuComputeGyration(float *xcm, float *x, float *mass, float *box, float masstotal, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template <typename T> void cpuComputeAngmom(T *p, T *xcm, T *x, T *v, T *mass, T *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum) { T unwrap[3]; p[0] = p[1] = p[2] = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; cpuUnmap(unwrap, &x[i*dim], box, &image[i*dim], triclinic, dim); T dx = unwrap[0] - xcm[0]; T dy = unwrap[1] - xcm[1]; p[2] += massone * (dx*v[i*dim+1] - dy*v[i*dim+0]); if (dim==3) { T dz = unwrap[2] - xcm[2]; p[0] += massone * (dy*v[i*dim+2] - dz*v[i*dim+1]); p[1] += massone * (dz*v[i*dim+0] - dx*v[i*dim+2]); } } //MPI_Allreduce(p,lmom,3,MPI_DOUBLE,MPI_SUM,world); } template void cpuComputeAngmom(double *p, double *xcm, double *x, double *v, double *mass, double *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template void cpuComputeAngmom(float *p, float *xcm, float *x, float *v, float *mass, float *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template <typename T> void cpuComputeTorque(T *tlocal, T *xcm, T *x, T *f, T *box, int *ilist, int *image, int triclinic, int dim, int inum) { T unwrap[3]; tlocal[0] = tlocal[1] = tlocal[2] = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; cpuUnmap(unwrap, &x[i*dim], box, &image[i*dim], triclinic, dim); T dx = unwrap[0] - xcm[0]; T dy = unwrap[1] - xcm[1]; tlocal[2] += dx*f[i*dim+1] - dy*f[i*dim+0]; if (dim==3) { T dz = unwrap[2] - xcm[2]; tlocal[0] += dy*f[i*dim+2] - dz*f[i*dim+1]; tlocal[1] += dz*f[i*dim+0] - dx*f[i*dim+2]; } } //MPI_Allreduce(tlocal,tq,3,MPI_DOUBLE,MPI_SUM,world); } template void cpuComputeTorque(double *tlocal, double *xcm, double *x, double *f, double *box, int *ilist, int *image, int triclinic, int dim, int inum); template void cpuComputeTorque(float *tlocal, float *xcm, float *x, float *f, float *box, int *ilist, int *image, int triclinic, int dim, int inum); template <typename T> void cpuComputeInertia(T *ione, T *xcm, T *x, T *mass, T *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum) { T unwrap[3]; for (int i = 0; i < dim; i++) for (int j = 0; j < dim; j++) ione[i*dim+j] = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; cpuUnmap(unwrap, &x[i*dim], box, &image[i*dim], triclinic, dim); T dx = unwrap[0] - xcm[0]; T dy = unwrap[1] - xcm[1]; ione[0] += massone * (dy*dy); ione[1] += massone * (dx*dx); ione[2] += massone * (dx*dx + dy*dy); ione[3] -= massone * dx*dy; if (dim==3) { T dz = unwrap[2] - xcm[2]; ione[0] += massone * (dz*dz); ione[1] += massone * (dz*dz); ione[4] -= massone * dy*dz; ione[5] -= massone * dx*dz; } } // ione[1*dim+0] = ione[0*dim+1]; // ione[2*dim+1] = ione[1*dim+2]; // ione[2*dim+0] = ione[0*dim+2]; //MPI_Allreduce(&ione[0],&itensor[0],6,MPI_DOUBLE,MPI_SUM,world); } template void cpuComputeInertia(double *ione, double *xcm, double *x, double *mass, double *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template void cpuComputeInertia(float *ione, float *xcm, float *x, float *mass, float *box, int *ilist, int *type, int *image, int triclinic, int dim, int inum); template <typename T> T cpuComputeNVTEnergy(T *tarray, T *eta, T *eta_mass, T *eta_dot, int mtchain) { T t_target = tarray[3]; T tdof = tarray[5]; T boltz = tarray[6]; T kt = boltz * t_target; T ke_target = tdof * kt; T energy = ke_target * eta[0] + 0.5*eta_mass[0]*eta_dot[0]*eta_dot[0]; for (int ich = 1; ich < mtchain; ich++) energy += kt * eta[ich] + 0.5*eta_mass[ich]*eta_dot[ich]*eta_dot[ich]; return energy; } template double cpuComputeNVTEnergy(double *tarray, double *eta, double *eta_mass, double *eta_dot, int mtchain); template float cpuComputeNVTEnergy(float *tarray, float *eta, float *eta_mass, float *eta_dot, int mtchain); template <typename T> T cpuComputeTempScalar(T *v, T *mass, T tfactor, int *type, int *ilist, int dim, int inum) { T t = 0.0; if (dim==3) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; t += (v[0+dim*i]*v[0+dim*i] + v[1+dim*i]*v[1+dim*i] + v[2+dim*i]*v[2+dim*i]) * mass[type[i]]; } } else if (dim==2) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; t += (v[0+dim*i]*v[0+dim*i] + v[1+dim*i]*v[1+dim*i]) * mass[type[i]]; } } t = tfactor*t; return t; } template double cpuComputeTempScalar(double *v, double *mass, double tfactor, int *type, int *ilist, int dim, int inum); template float cpuComputeTempScalar(float *v, float *mass, float tfactor, int *type, int *ilist, int dim, int inum); template <typename T> void cpuComputeTempSymTensor(T *t, T *v, T *mass, T tfactor, int *type, int *ilist, int dim, int inum) { for (int i = 0; i < 6; i++) t[i] = 0.0; if (dim==3) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; t[0] += massone * v[0+dim*i]*v[0+dim*i]; t[1] += massone * v[1+dim*i]*v[1+dim*i]; t[2] += massone * v[2+dim*i]*v[2+dim*i]; t[3] += massone * v[0+dim*i]*v[1+dim*i]; t[4] += massone * v[0+dim*i]*v[2+dim*i]; t[5] += massone * v[1+dim*i]*v[2+dim*i]; } } else if (dim==2) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T massone = mass[type[i]]; t[0] += massone * v[0+dim*i]*v[0+dim*i]; t[1] += massone * v[1+dim*i]*v[1+dim*i]; t[3] += massone * v[0+dim*i]*v[1+dim*i]; } } for (int i = 0; i < 6; i++) t[i] = tfactor*t[i]; } template void cpuComputeTempSymTensor(double *t, double *v, double *mass, double tfactor, int *type, int *ilist, int dim, int inum); template void cpuComputeTempSymTensor(float *t, float *v, float *mass, float tfactor, int *type, int *ilist, int dim, int inum); template <typename T> T cpuComputePressureScalar(T *virial, T volume, T temp, T tempdof, T boltz, T nktv2p, int dim) { T factor = nktv2p /(dim*volume); if (dim == 3) { return (tempdof * boltz * temp + virial[0] + virial[1] + virial[2]) * factor; } else { return (tempdof * boltz * temp + virial[0] + virial[1]) *factor; } } template double cpuComputePressureScalar(double *virial, double volume, double temp, double tempdof, double boltz, double nktv2p, int dim); template float cpuComputePressureScalar(float *virial, float volume, float temp, float tempdof, float boltz, float nktv2p, int dim); template <typename T> void cpuComputePressureSymTensor(T *vector, T *virial, T *ke_tensor, T volume, T nktv2p, int dim) { T factor = nktv2p /volume; if (dim == 3) { for (int i = 0; i < 6; i++) vector[i] = (ke_tensor[i] + virial[i]) * factor; } else { vector[0] = (ke_tensor[0] + virial[0]) * factor; vector[1] = (ke_tensor[1] + virial[1]) * factor; vector[3] = (ke_tensor[3] + virial[3]) * factor; vector[2] = vector[4] = vector[5] = 0.0; } } template void cpuComputePressureSymTensor(double *vector, double *virial, double *ke_tensor, double volume, double nktv2p, int dim); template void cpuComputePressureSymTensor(float *vector, float *virial, float *ke_tensor, float volume, float nktv2p, int dim); template <typename T> void cpuComputeHeatFlux(T *vector, T *ke, T *pe, T *stress, T *v, T nktv2p, int *ilist, int pressatomflag, int dim, int inum) { T jc[3] = {0.0,0.0,0.0}; T jv[3] = {0.0,0.0,0.0}; T eng; if (pressatomflag == 2) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; eng = pe[i] + ke[i]; jc[0] += eng*v[i*dim+0]; jc[1] += eng*v[i*dim+1]; jc[2] += eng*v[i*dim+2]; // stress[0]: rijx*fijx // stress[1]: rijy*fijy // stress[2]: rijz*fijz // stress[3]: rijx*fijy // stress[4]: rijx*fijz // stress[5]: rijy*fijz // stress[6]: rijy*fijx // stress[7]: rijz*fijx // stress[8]: rijz*fijy // jv[0] = rijx fijx vjx + rijx fijy vjy + rijx fijz vjz jv[0] -= stress[i*9+0]*v[i*dim+0] + stress[i*9+3]*v[i*dim+1] + stress[i*9+4]*v[i*dim+2]; // jv[1] = rijy fijx vjx + rijy fijy vjy + rijy fijz vjz jv[1] -= stress[i*9+6]*v[i*dim+0] + stress[i*9+1]*v[i*dim+1] + stress[i*9+5]*v[i*dim+2]; // jv[2] = rijz fijx vjx + rijz fijy vjy + rijz fijz vjz jv[2] -= stress[i*9+7]*v[i*dim+0] + stress[i*9+8]*v[i*dim+1] + stress[i*9+2]*v[i*dim+2]; } } else { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; eng = pe[i] + ke[i]; jc[0] += eng*v[i*dim+0]; jc[1] += eng*v[i*dim+1]; jc[2] += eng*v[i*dim+2]; jv[0] -= stress[i*6+0]*v[i*dim+0] + stress[i*6+3]*v[i*dim+1] + stress[i*6+4]*v[i*dim+2]; jv[1] -= stress[i*6+3]*v[i*dim+0] + stress[i*6+1]*v[i*dim+1] + stress[i*6+5]*v[i*dim+2]; jv[2] -= stress[i*6+4]*v[i*dim+0] + stress[i*6+5]*v[i*dim+1] + stress[i*6+2]*v[i*dim+2]; } } // convert jv from stress*volume to energy units via nktv2p factor jv[0] /= nktv2p; jv[1] /= nktv2p; jv[2] /= nktv2p; for (int i=0; i<3; i++) { vector[i] = jc[i]+jv[i]; // 1st 3 terms are total heat flux vector[i+3] = jc[i]; // 2nd 3 terms are just conductive portion } } template void cpuComputeHeatFlux(double *vector, double *ke, double *pe, double *stress, double *v, double nktv2p, int *ilist, int pressatomflag, int dim, int inum); template void cpuComputeHeatFlux(float *vector, float *ke, float *pe, float *stress, float *v, float nktv2p, int *ilist, int pressatomflag, int dim, int inum); template <typename T> void cpuComputeKEAtom(T *ke, T *mass, T *v, T mvv2e, int *type, int *ilist, int dim, int inum) { if (dim==3) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; ke[ii] = 0.5 * mvv2e * mass[type[i]] * (v[i*dim+0]*v[i*dim+0] + v[i*dim+1]*v[i*dim+1] + v[i*dim+2]*v[i*dim+2]); } } else { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; ke[ii] = 0.5 * mvv2e * mass[type[i]] * (v[i*dim+0]*v[i*dim+0] + v[i*dim+1]*v[i*dim+1]); } } } template void cpuComputeKEAtom(double *ke, double *mass, double *v, double mvv2e, int *type, int *ilist, int dim, int inum); template void cpuComputeKEAtom(float *ke, float *mass, float *v, float mvv2e, int *type, int *ilist, int dim, int inum); template <typename T> void cpuComputeStressAtom(T *stress, T *mass, T *vatom, T *v, T mvv2e, T nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum) { if (vflag) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; for (int j = 0; j < 6; j++) stress[ii+j*inum] = vatom[i*6+j]; } } else { cpuArraySetValue(stress, (T) 0.0, inum*6); } // zero virial of atoms not in group // only do this after comm since ghost contributions must be included // for (int ii = 0; ii < inum; ii++) // { // int i = ilist[ii]; // stress[i*6+0] = 0.0; // stress[i*6+1] = 0.0; // stress[i*6+2] = 0.0; // stress[i*6+3] = 0.0; // stress[i*6+4] = 0.0; // stress[i*6+5] = 0.0; // } // include kinetic energy term for each atom in group // mvv2e converts mv^2 to energy if (keflag) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T onemass = mvv2e * mass[type[i]]; stress[ii] += onemass*v[i*dim+0]*v[i*dim+0]; stress[ii+inum] += onemass*v[i*dim+1]*v[i*dim+1]; stress[ii+3*inum] += onemass*v[i*dim+0]*v[i*dim+1]; if (dim==3) { stress[ii+2*inum] += onemass*v[i*dim+2]*v[i*dim+2]; stress[ii+4*inum] += onemass*v[i*dim+0]*v[i*dim+2]; stress[ii+5*inum] += onemass*v[i*dim+1]*v[i*dim+2]; } // stress[i*6+0] += onemass*v[i*dim+0]*v[i*dim+0]; // stress[i*6+1] += onemass*v[i*dim+1]*v[i*dim+1]; // stress[i*6+3] += onemass*v[i*dim+0]*v[i*dim+1]; // if (dim==3) { // stress[i*6+2] += onemass*v[i*dim+2]*v[i*dim+2]; // stress[i*6+4] += onemass*v[i*dim+0]*v[i*dim+2]; // stress[i*6+5] += onemass*v[i*dim+1]*v[i*dim+2]; // } } } cpuArrayMultiplyScalar(stress, nktv2p, inum*6); } template void cpuComputeStressAtom(double *stress, double *mass, double *vatom, double *v, double mvv2e, double nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum); template void cpuComputeStressAtom(float *stress, float *mass, float *vatom, float *v, float mvv2e, float nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum); template <typename T> void cpuComputeCentroidStressAtom(T *stress, T *mass, T *cvatom, T *v, T mvv2e, T nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum) { if (vflag) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; for (int j = 0; j < 9; j++) stress[inum*j+ii] = cvatom[i*9+j]; } } else { cpuArraySetValue(stress, (T) 0.0, inum*9); } // zero virial of atoms not in group // only do this after comm since ghost contributions must be included // for (int ii = 0; ii < inum; ii++) // { // int i = ilist[ii]; // stress[i*9+0] = 0.0; // stress[i*9+1] = 0.0; // stress[i*9+2] = 0.0; // stress[i*9+3] = 0.0; // stress[i*9+4] = 0.0; // stress[i*9+5] = 0.0; // stress[i*9+6] = 0.0; // stress[i*9+7] = 0.0; // stress[i*9+8] = 0.0; // } // include kinetic energy term for each atom in group // apply temperature bias is applicable // mvv2e converts mv^2 to energy if (keflag) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T onemass = mvv2e * mass[type[i]]; stress[ii] += onemass*v[i*dim+0]*v[i*dim+0]; stress[ii+inum] += onemass*v[i*dim+1]*v[i*dim+1]; stress[ii+3*inum] += onemass*v[i*dim+0]*v[i*dim+1]; stress[ii+6*inum] += onemass*v[i*dim+1]*v[i*dim+0]; if (dim==3) { stress[ii+2*inum] += onemass*v[i*dim+2]*v[i*dim+2]; stress[ii+4*inum] += onemass*v[i*dim+0]*v[i*dim+2]; stress[ii+5*inum] += onemass*v[i*dim+1]*v[i*dim+2]; stress[ii+7*inum] += onemass*v[i*dim+2]*v[i*dim+0]; stress[ii+8*inum] += onemass*v[i*dim+2]*v[i*dim+1]; } // stress[i*9+0] += onemass*v[i*dim+0]*v[i*dim+0]; // stress[i*9+1] += onemass*v[i*dim+1]*v[i*dim+1]; // stress[i*9+3] += onemass*v[i*dim+0]*v[i*dim+1]; // stress[i*9+6] += onemass*v[i*dim+1]*v[i*dim+0]; // if (dim==3) { // stress[i*9+2] += onemass*v[i*dim+2]*v[i*dim+2]; // stress[i*9+4] += onemass*v[i*dim+0]*v[i*dim+2]; // stress[i*9+5] += onemass*v[i*dim+1]*v[i*dim+2]; // stress[i*9+7] += onemass*v[i*dim+2]*v[i*dim+0]; // stress[i*9+8] += onemass*v[i*dim+2]*v[i*dim+1]; // } } } // convert to stress*volume units = -pressure*volume cpuArrayMultiplyScalar(stress, nktv2p, inum*9); // for (int ii = 0; ii < inum; ii++) // { // int i = ilist[ii]; // stress[i*9+0] *= nktv2p; // stress[i*9+1] *= nktv2p; // stress[i*9+2] *= nktv2p; // stress[i*9+3] *= nktv2p; // stress[i*9+4] *= nktv2p; // stress[i*9+5] *= nktv2p; // stress[i*9+6] *= nktv2p; // stress[i*9+7] *= nktv2p; // stress[i*9+8] *= nktv2p; // } } template void cpuComputeCentroidStressAtom(double *stress, double *mass, double *cvatom, double *v, double mvv2e, double nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum); template void cpuComputeCentroidStressAtom(float *stress, float *mass, float *cvatom, float *v, float mvv2e, float nktv2p, int *type, int *ilist, int vflag, int keflag, int dim, int inum); template <typename T> void cpuComputeDisplaceAtom(T *displace, T *x, T *xoriginal, T *box, int *pbc, int *ilist, int triclinic, int dim, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T dp[3]; dp[0] = x[i*dim+0] - xoriginal[i*dim+0]; dp[1] = x[i*dim+1] - xoriginal[i*dim+1]; dp[2] = (dim==3) ? (x[i*dim+2] - xoriginal[i*dim+2]) : 0.0; cpuMinimumImage(dp, box, pbc, triclinic, dim); displace[ii+0*inum] = dp[0]; displace[ii+1*inum] = dp[1]; displace[ii+2*inum] = dp[2]; displace[ii+3*inum] = sqrt(dp[0]*dp[0] +dp[1]*dp[1] + dp[2]*dp[2]); // displace[i*4+0] = x[i*dim+0] - xoriginal[i*dim+0]; // displace[i*4+1] = x[i*dim+1] - xoriginal[i*dim+1]; // displace[i*4+2] = x[i*dim+2] - xoriginal[i*dim+2]; // cpuMinimumImage(&displace[i*4], box, pbc, triclinic, dim); // displace[i*4+3] = sqrt(displace[i*4+0]*displace[i*4+0] + // displace[i*4+1]*displace[i*4+1] + // displace[i*4+2]*displace[i*4+2]); // } else { // displace[i*4+0] = 0.0; // displace[i*4+1] = 0.0; // displace[i*4+2] = 0.0; // displace[i*4+3] = 0.0; } } template void cpuComputeDisplaceAtom(double *displace, double *x, double *xoriginal, double *box, int *pbc, int *ilist, int triclinic, int dim, int inum); template void cpuComputeDisplaceAtom(float *displace, float *x, float *xoriginal, float *box, int *pbc, int *ilist, int triclinic, int dim, int inum); template <typename T> void cpuSelect3(int k, int n, T *arr, int *iarr, T *arr3) { int dim=3; int i,ir,j,l,mid,ia,itmp; T a,tmp,a3[3]; arr--; iarr--; for (i=0; i<3; i++) arr3--; l = 1; ir = n; for (;;) { if (ir <= l+1) { if (ir == l+1 && arr[ir] < arr[l]) { SWAP(arr[l],arr[ir]); ISWAP(iarr[l],iarr[ir]); SWAP(arr3[dim*l+0],arr3[dim*ir+0]); SWAP(arr3[dim*l+1],arr3[dim*ir+1]); SWAP(arr3[dim*l+2],arr3[dim*ir+2]); //SWAP3(arr3[l],arr3[ir]); } return; } else { mid=(l+ir) >> 1; SWAP(arr[mid],arr[l+1]); ISWAP(iarr[mid],iarr[l+1]); SWAP(arr3[dim*mid+0],arr3[dim*(l+1)+0]); SWAP(arr3[dim*mid+1],arr3[dim*(l+1)+1]); SWAP(arr3[dim*mid+2],arr3[dim*(l+1)+2]); //SWAP3(arr3[mid],arr3[l+1]); if (arr[l] > arr[ir]) { SWAP(arr[l],arr[ir]); ISWAP(iarr[l],iarr[ir]); SWAP(arr3[dim*l+0],arr3[dim*ir+0]); SWAP(arr3[dim*l+1],arr3[dim*ir+1]); SWAP(arr3[dim*l+2],arr3[dim*ir+2]); //SWAP3(arr3[l],arr3[ir]); } if (arr[l+1] > arr[ir]) { SWAP(arr[l+1],arr[ir]); ISWAP(iarr[l+1],iarr[ir]); //SWAP3(arr3[l+1],arr3[ir]); SWAP(arr3[dim*(l+1)+0],arr3[dim*ir+0]); SWAP(arr3[dim*(l+1)+1],arr3[dim*ir+1]); SWAP(arr3[dim*(l+1)+2],arr3[dim*ir+2]); } if (arr[l] > arr[l+1]) { SWAP(arr[l],arr[l+1]); ISWAP(iarr[l],iarr[l+1]); SWAP(arr3[dim*l+0],arr3[dim*(l+1)+0]); SWAP(arr3[dim*l+1],arr3[dim*(l+1)+1]); SWAP(arr3[dim*l+2],arr3[dim*(l+1)+2]); //SWAP3(arr3[l],arr3[l+1]); } i = l+1; j = ir; a = arr[l+1]; ia = iarr[l+1]; a3[0] = arr3[dim*(l+1)+0]; a3[1] = arr3[dim*(l+1)+1]; a3[2] = arr3[dim*(l+1)+2]; for (;;) { do i++; while (arr[i] < a); do j--; while (arr[j] > a); if (j < i) break; SWAP(arr[i],arr[j]); ISWAP(iarr[i],iarr[j]); SWAP(arr3[dim*i+0],arr3[dim*j+0]); SWAP(arr3[dim*i+1],arr3[dim*j+1]); SWAP(arr3[dim*i+2],arr3[dim*j+2]); //SWAP3(arr3[i],arr3[j]); } arr[l+1] = arr[j]; arr[j] = a; iarr[l+1] = iarr[j]; iarr[j] = ia; arr3[dim*(l+1)+0] = arr3[j*dim+0]; arr3[dim*(l+1)+1] = arr3[j*dim+1]; arr3[dim*(l+1)+2] = arr3[j*dim+2]; arr3[j*dim+0] = a3[0]; arr3[j*dim+1] = a3[1]; arr3[j*dim+2] = a3[2]; // arr3[l+1][0] = arr3[j][0]; // arr3[l+1][1] = arr3[j][1]; // arr3[l+1][2] = arr3[j][2]; // arr3[j][0] = a3[0]; // arr3[j][1] = a3[1]; // arr3[j][2] = a3[2]; if (j >= k) ir = j-1; if (j <= k) l = i; } } } template <typename T> T cpuAssociatedLegendre(int l, int m, T x) { if (l < m) return 0.0; T p = 1.0; T pm1 = 0.0; T pm2 = 0.0; if (m != 0) { T msqx = -sqrt(1.0-x*x); for (int i=1; i < m+1; ++i) p *= (2*i-1) * msqx; } for (int i=m+1; i < l+1; ++i) { pm2 = pm1; pm1 = p; p = ((2*i-1)*x*pm1 - (i+m-1)*pm2) / ((T) (i-m)); } return p; } template <typename T> T cpuPolarPrefactor(int l, int m, T MY_4PI, T costheta) { const int mabs = abs(m); T prefactor = 1.0; for (int i=l-mabs+1; i < l+mabs+1; ++i) prefactor *= (T) i; prefactor = sqrt(static_cast<T>(2*l+1)/(MY_4PI*prefactor)) * cpuAssociatedLegendre(l,mabs,costheta); if ((m < 0) && (m % 2)) prefactor = -prefactor; return prefactor; } /* ---------------------------------------------------------------------- associated legendre polynomial sign convention: P(l,l) = (2l-1)!!(-sqrt(1-x^2))^l ------------------------------------------------------------------------- */ template <typename T> void cpuCalcBoop(T *qn, T *rlist, T *cglist, T *qnm_r, T *qnm_i, T MY_EPSILON, T QEPSILON, T MY_4PI, int *qlist, int nqlist, int qmax, int wlflag, int wlhatflag, int qlcompflag, int iqlcomp, int qlcomp, int ncount) { int mmax = 2*qmax+1; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; for(int m = 0; m < 2*l+1; m++) { qnm_r[m+mmax*il] = 0.0; qnm_i[m+mmax*il] = 0.0; } } for(int ineigh = 0; ineigh < ncount; ineigh++) { const T * const r = &rlist[3*ineigh]; T rmag = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); if(rmag <= MY_EPSILON) { return; } T costheta = r[2] / rmag; T expphi_r = r[0]; T expphi_i = r[1]; T rxymag = sqrt(expphi_r*expphi_r+expphi_i*expphi_i); if(rxymag <= MY_EPSILON) { expphi_r = 1.0; expphi_i = 0.0; } else { T rxymaginv = 1.0/rxymag; expphi_r *= rxymaginv; expphi_i *= rxymaginv; } for (int il = 0; il < nqlist; il++) { int l = qlist[il]; // calculate spherical harmonics // Ylm, -l <= m <= l // sign convention: sign(Yll(0,0)) = (-1)^l qnm_r[il*mmax+l] += cpuPolarPrefactor(l, 0, MY_4PI, costheta); T expphim_r = expphi_r; T expphim_i = expphi_i; for(int m = 1; m <= +l; m++) { T prefactor = cpuPolarPrefactor(l, m, MY_4PI, costheta); T ylm_r = prefactor * expphim_r; T ylm_i = prefactor * expphim_i; qnm_r[il*mmax+m+l] += ylm_r; qnm_i[il*mmax+m+l] += ylm_i; if(m & 1) { qnm_r[il*mmax-m+l] -= ylm_r; qnm_i[il*mmax-m+l] += ylm_i; } else { qnm_r[il*mmax-m+l] += ylm_r; qnm_i[il*mmax-m+l] -= ylm_i; } T tmp_r = expphim_r*expphi_r - expphim_i*expphi_i; T tmp_i = expphim_r*expphi_i + expphim_i*expphi_r; expphim_r = tmp_r; expphim_i = tmp_i; } } } // convert sums to averages T facn = 1.0 / ncount; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; for(int m = 0; m < 2*l+1; m++) { qnm_r[il*mmax+m] *= facn; qnm_i[il*mmax+m] *= facn; } } // calculate Q_l // NOTE: optional W_l_hat and components of Q_qlcomp use these stored Q_l values int jj = 0; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; T qnormfac = sqrt(MY_4PI/(2*l+1)); T qm_sum = 0.0; for(int m = 0; m < 2*l+1; m++) qm_sum += qnm_r[il*mmax+m]*qnm_r[il*mmax+m] + qnm_i[il*mmax+m]*qnm_i[il*mmax+m]; qn[jj++] = qnormfac * sqrt(qm_sum); } // calculate W_l if (wlflag) { int idxcg_count = 0; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; T wlsum = 0.0; for(int m1 = 0; m1 < 2*l+1; m1++) { for(int m2 = max(0,l-m1); m2 < min(2*l+1,3*l-m1+1); m2++) { int m = m1 + m2 - l; T qm1qm2_r = qnm_r[il*mmax+m1]*qnm_r[il*mmax+m2] - qnm_i[il*mmax+m1]*qnm_i[il*mmax+m2]; T qm1qm2_i = qnm_r[il*mmax+m1]*qnm_i[il*mmax+m2] + qnm_i[il*mmax+m1]*qnm_r[il*mmax+m2]; wlsum += (qm1qm2_r*qnm_r[il*mmax+m] + qm1qm2_i*qnm_i[il*mmax+m])*cglist[idxcg_count]; idxcg_count++; } } qn[jj++] = wlsum/sqrt(2*l+1); } } // calculate W_l_hat if (wlhatflag) { int idxcg_count = 0; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; T wlsum = 0.0; for(int m1 = 0; m1 < 2*l+1; m1++) { for(int m2 = max(0,l-m1); m2 < min(2*l+1,3*l-m1+1); m2++) { int m = m1 + m2 - l; T qm1qm2_r = qnm_r[il*mmax+m1]*qnm_r[il*mmax+m2] - qnm_i[il*mmax+m1]*qnm_i[il*mmax+m2]; T qm1qm2_i = qnm_r[il*mmax+m1]*qnm_i[il*mmax+m2] + qnm_i[il*mmax+m1]*qnm_r[il*mmax+m2]; wlsum += (qm1qm2_r*qnm_r[il*mmax+m] + qm1qm2_i*qnm_i[il*mmax+m])*cglist[idxcg_count]; idxcg_count++; } } if (qn[il] < QEPSILON) qn[jj++] = 0.0; else { T qnormfac = sqrt(MY_4PI/(2*l+1)); T qnfac = qnormfac/qn[il]; qn[jj++] = wlsum/sqrt(2*l+1)*(qnfac*qnfac*qnfac); } } } // Calculate components of Q_l/|Q_l|, for l=qlcomp if (qlcompflag) { int il = iqlcomp; int l = qlcomp; if (qn[il] < QEPSILON) for(int m = 0; m < 2*l+1; m++) { qn[jj++] = 0.0; qn[jj++] = 0.0; } else { T qnormfac = sqrt(MY_4PI/(2*l+1)); T qnfac = qnormfac/qn[il]; for(int m = 0; m < 2*l+1; m++) { qn[jj++] = qnm_r[il*mmax+m] * qnfac; qn[jj++] = qnm_i[il*mmax+m] * qnfac; } } } } template <typename T> int cpuInitClebschGordan(T *cglist, T *factorial, int *qlist, int nqlist) { T sum,dcg,sfaccg, sfac1, sfac2; int m, aa2, bb2, cc2; int ifac, idxcg_count; idxcg_count = 0; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; for(int m1 = 0; m1 < 2*l+1; m1++) for(int m2 = max(0,l-m1); m2 < min(2*l+1,3*l-m1+1); m2++) idxcg_count++; } int idxcg_max = idxcg_count; idxcg_count = 0; for (int il = 0; il < nqlist; il++) { int l = qlist[il]; for(int m1 = 0; m1 < 2*l+1; m1++) { aa2 = m1 - l; for(int m2 = max(0,l-m1); m2 < min(2*l+1,3*l-m1+1); m2++) { bb2 = m2 - l; m = aa2 + bb2 + l; sum = 0.0; for (int z = max(0, max(-aa2, bb2)); z <= min(l, min(l - aa2, l + bb2)); z++) { ifac = z % 2 ? -1 : 1; sum += ifac / (factorial[z] * factorial[l - z] * factorial[l - aa2 - z] * factorial[l + bb2 - z] * factorial[aa2 + z] * factorial[-bb2 + z]); } cc2 = m - l; sfaccg = sqrt(factorial[l + aa2] * factorial[l - aa2] * factorial[l + bb2] * factorial[l - bb2] * factorial[l + cc2] * factorial[l - cc2] * (2*l + 1)); sfac1 = factorial[3*l + 1]; sfac2 = factorial[l]; dcg = sqrt(sfac2*sfac2*sfac2 / sfac1); cglist[idxcg_count] = sum * dcg * sfaccg; idxcg_count++; } } } return idxcg_max; } template <typename T> void cpuComputeOrientOrderAtom(T* qnarray, T *x, T *rlist, T *cglist, T *fac, T *qnm_r, T *qnm_i, T *distsq, T cutsq, T MY_EPSILON, T QEPSILON, T MY_4PI, int *neighlist, int *neighnum, int *ilist, int *qlist, int *nearest, int nqlist, int qmax, int wlflag, int wlhatflag, int qlcompflag, int iqlcomp, int qlcomp, int nnn, int jnum, int dim, int inum) { int ncol = nqlist; if (wlflag) ncol += nqlist; if (wlhatflag) ncol += nqlist; if (qlcompflag) ncol += 2*(2*qlcomp+1); cpuInitClebschGordan(cglist, fac, qlist, nqlist); for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T* qn = &qnarray[ncol*i]; T xtmp = x[i*dim+0]; T ytmp = x[i*dim+1]; T ztmp = x[i*dim+2]; int *jlist = &neighlist[jnum*i]; int m = neighnum[i]; // memory->create(distsq,maxneigh,"orientorder/atom:distsq"); // memory->create(rlist,maxneigh,3,"orientorder/atom:rlist"); // memory->create(nearest,maxneigh,"orientorder/atom:nearest"); int ncount = 0; for (int jj = 0; jj < m; jj++) { int j = jlist[jj]; //j &= NEIGHMASK; T delx = xtmp - x[j*dim+0]; T dely = ytmp - x[j*dim+1]; T delz = ztmp - x[j*dim+2]; T rsq = delx*delx + dely*dely + delz*delz; if (rsq < cutsq) { distsq[ncount] = rsq; rlist[ncount*dim+0] = delx; rlist[ncount*dim+1] = dely; rlist[ncount*dim+2] = delz; nearest[ncount++] = j; } } // if not nnn neighbors, order parameter = 0; if ((ncount == 0) || (ncount < nnn)) { for (int jj = 0; jj < ncol; jj++) qn[jj] = 0.0; continue; } // if nnn > 0, use only nearest nnn neighbors if (nnn > 0) { cpuSelect3(nnn,ncount,distsq,nearest,rlist); ncount = nnn; } cpuCalcBoop(qn, rlist, cglist, qnm_r, qnm_i, MY_EPSILON, QEPSILON, MY_4PI, qlist, nqlist, qmax, wlflag, wlhatflag, qlcompflag, iqlcomp, qlcomp, ncount); } } template void cpuComputeOrientOrderAtom(double *qnarray, double *x, double *rlist, double *cglist, double *fac, double *qnm_r, double *qnm_i, double *distsq, double cutsq, double MY_EPSILON, double QEPSILON, double MY_4PI, int *neighlist, int *neighnum, int *ilist, int *qlist, int *nearest, int nqlist, int qmax, int wlflag, int wlhatflag, int qlcompflag, int iqlcomp, int qlcomp, int nnn, int jnum, int dim, int inum); template void cpuComputeOrientOrderAtom(float *qnarray, float *x, float *rlist, float *cglist, float *fac, float *qnm_r, float *qnm_i, float *distsq, float cutsq, float MY_EPSILON, float QEPSILON, float MY_4PI, int *neighlist, int *neighnum, int *ilist, int *qlist, int *nearest, int nqlist, int qmax, int wlflag, int wlhatflag, int qlcompflag, int iqlcomp, int qlcomp, int nnn, int jnum, int dim, int inum); template <typename T> void cpuComputeCoordAtomCutoff(int *cvec, T *x, T *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int jnum, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T xtmp = x[i*dim]; T ytmp = x[i*dim+1]; T ztmp = x[i*dim+2]; int itype = type[i]; int kk = neighnum[i]; int n = 0; for (int jj = 0; jj < kk; jj++) { int j = neighlist[jj + jnum*i]; //j &= NEIGHMASK; if (jgroupbit[j]) { int jtype = type[j]; T delx = xtmp - x[j*dim+0]; T dely = ytmp - x[j*dim+1]; T delz = ztmp - x[j*dim+2]; T rsq = delx*delx + dely*dely + delz*delz; if (rsq < rcutsq[(jtype-1) + (itype-1)*ntypes] && jtype >= typelo[0] && jtype <= typehi[0]) n++; } } cvec[i] = n; } } template void cpuComputeCoordAtomCutoff(int *cvec, double *x, double *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int jnum, int inum); template void cpuComputeCoordAtomCutoff(int *cvec, float *x, float *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int jnum, int inum); template <typename T> void cpuComputeCoordAtomCutoff(int *carray, T *x, T *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int ncol, int dim, int ntypes, int jnum, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; for (int m = 0; m < ncol; m++) carray[m+ncol*i] = 0; T xtmp = x[i*dim]; T ytmp = x[i*dim+1]; T ztmp = x[i*dim+2]; int itype = type[i]; int kk = neighnum[i]; int n = 0; for (int jj = 0; jj < kk; jj++) { int j = neighlist[jj + jnum*i]; //j &= NEIGHMASK; if (jgroupbit[j]) { int jtype = type[j]; T delx = xtmp - x[j*dim+0]; T dely = ytmp - x[j*dim+1]; T delz = ztmp - x[j*dim+2]; T rsq = delx*delx + dely*dely + delz*delz; if (rsq < rcutsq[(jtype-1) + (itype-1)*ntypes]) { for (int m = 0; m < ncol; m++) if (jtype >= typelo[m] && jtype <= typehi[m]) carray[m+ncol*i] += 1; } } } } } template void cpuComputeCoordAtomCutoff(int *carray, double *x, double *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int ncol, int dim, int ntypes, int jnum, int inum); template void cpuComputeCoordAtomCutoff(int *carray, float *x, float *rcutsq, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int ncol, int dim, int ntypes, int jnum, int inum); template <typename T> void cpuComputeCoordAtomOrient(int *cvec, T *x, T *rcutsq, T *normv, T threshold, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int nqlist, int ncol, int l, int jnum, int inum) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; T xtmp = x[i*dim]; T ytmp = x[i*dim+1]; T ztmp = x[i*dim+2]; int itype = type[i]; int kk = neighnum[i]; int n = 0; for (int jj = 0; jj < kk; jj++) { int j = neighlist[jj + jnum*i]; //j &= NEIGHMASK; if (jgroupbit[j]) { int jtype = type[j]; T delx = xtmp - x[j*dim+0]; T dely = ytmp - x[j*dim+1]; T delz = ztmp - x[j*dim+2]; T rsq = delx*delx + dely*dely + delz*delz; if (rsq < rcutsq[(jtype-1) + (itype-1)*ntypes]) { T dot_product = 0.0; for (int m=0; m < 2*(2*l+1); m++) { dot_product += normv[(nqlist+m) + ncol*i]*normv[(nqlist+m) + ncol*j]; } if (dot_product > threshold) n++; } } } cvec[i] = n; } } template void cpuComputeCoordAtomOrient(int *cvec, double *x, double *rcutsq, double *normv, double threshold, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int nqlist, int ncol, int l, int jnum, int inum); template void cpuComputeCoordAtomOrient(int *cvec, float *x, float *rcutsq, float *normv, float threshold, int *type, int *ilist, int *neighlist, int *neighnum, int *typelo, int *typehi, int *jgroupbit, int dim, int ntypes, int nqlist, int ncol, int l, int jnum, int inum); template <typename T> void cpuComputeMSD(T *vector, T *x, T *xoriginal, T *h, T *xcm, int *ilist, int *image, int naverage, int avflag, int triclinic, int nmsd, int dim, int inum) { T dx,dy,dz; int xbox,ybox,zbox; T msd[4]; msd[0] = msd[1] = msd[2] = msd[3] = 0.0; T xtmp, ytmp, ztmp; // update number of averages if requested T navfac; if (avflag) { naverage += 1; navfac = 1.0/(naverage+1); } if (dim==3) { if (triclinic == 0) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; // xbox = (image[i] & IMGMASK) - IMGMAX; // ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; // zbox = (image[i] >> IMG2BITS) - IMGMAX; xtmp = x[i*dim+0] + image[i*dim+0]*h[0] - xcm[0]; ytmp = x[i*dim+1] + image[i*dim+1]*h[1] - xcm[1]; ztmp = x[i*dim+2] + image[i*dim+2]*h[2] - xcm[2]; if (avflag) { xoriginal[i*dim+0] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; xoriginal[i*dim+1] = (xoriginal[i*dim+1]*naverage + ytmp)*navfac; xoriginal[i*dim+2] = (xoriginal[i*dim+2]*naverage + ztmp)*navfac; } dx = xtmp - xoriginal[i*dim+0]; dy = ytmp - xoriginal[i*dim+1]; dz = ztmp - xoriginal[i*dim+2]; msd[0] += dx*dx; msd[1] += dy*dy; msd[2] += dz*dz; msd[3] += dx*dx + dy*dy + dz*dz; } } else { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; // xbox = (image[i] & IMGMASK) - IMGMAX; // ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; // zbox = (image[i] >> IMG2BITS) - IMGMAX; xtmp = x[i*dim+0] + h[0]*image[i*dim+0] + h[5]*image[i*dim+1] + h[4]*image[i*dim+2] - xcm[0]; ytmp = x[i*dim+1] + h[1]*image[i*dim+1] + h[3]*zbox - xcm[1]; ztmp = x[i*dim+2] + h[2]*image[i*dim+2] - xcm[2]; // use running average position for reference if requested if (avflag) { xoriginal[i*dim+0] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; xoriginal[i*dim+1] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; xoriginal[i*dim+2] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; } dx = xtmp - xoriginal[i*dim+0]; dy = ytmp - xoriginal[i*dim+1]; dz = ztmp - xoriginal[i*dim+2]; msd[0] += dx*dx; msd[1] += dy*dy; msd[2] += dz*dz; msd[3] += dx*dx + dy*dy + dz*dz; } } } else { if (triclinic == 0) { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; // xbox = (image[i] & IMGMASK) - IMGMAX; // ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; xtmp = x[i*dim+0] + image[i*dim+0]*h[0] - xcm[0]; ytmp = x[i*dim+1] + image[i*dim+1]*h[1] - xcm[1]; if (avflag) { xoriginal[i*dim+0] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; xoriginal[i*dim+1] = (xoriginal[i*dim+1]*naverage + ytmp)*navfac; } dx = xtmp - xoriginal[i*dim+0]; dy = ytmp - xoriginal[i*dim+1]; msd[0] += dx*dx; msd[1] += dy*dy; msd[3] += dx*dx + dy*dy; } } else { for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; // xbox = (image[i] & IMGMASK) - IMGMAX; // ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; xtmp = x[i*dim+0] + h[0]*image[i*dim+0] + h[5]*image[i*dim+1] - xcm[0]; ytmp = x[i*dim+1] + h[1]*image[i*dim+1] - xcm[1]; // use running average position for reference if requested if (avflag) { xoriginal[i*dim+0] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; xoriginal[i*dim+1] = (xoriginal[i*dim+0]*naverage + xtmp)*navfac; } dx = xtmp - xoriginal[i*dim+0]; dy = ytmp - xoriginal[i*dim+1]; msd[0] += dx*dx; msd[1] += dy*dy; msd[3] += dx*dx + dy*dy; } } } //MPI_Allreduce(msd,vector,4,MPI_DOUBLE,MPI_SUM,world); vector[0] /= nmsd; vector[1] /= nmsd; vector[2] /= nmsd; vector[3] /= nmsd; } template void cpuComputeMSD(double *vector, double *x, double *xoriginal, double *h, double *xcm, int *ilist, int *image, int naverage, int avflag, int triclinic, int nmsd, int dim, int inum); template void cpuComputeMSD(float *vector, float *x, float *xoriginal, float *h, float *xcm, int *ilist, int *image, int naverage, int avflag, int triclinic, int nmsd, int dim, int inum); template <typename T> void cpuComputeVACF(T *vacf, T *v, T *voriginal, int *ilist, int nvacf, int dim, int inum) { T vxsq,vysq,vzsq; vacf[0] = vacf[1] = vacf[2] = vacf[3] = 0.0; for (int ii = 0; ii < inum; ii++) { int i = ilist[ii]; vxsq = v[i*dim+0] * voriginal[i*dim+0]; vysq = v[i*dim+1] * voriginal[i*dim+1]; vzsq = (dim==3) ? (v[i*dim+2] * voriginal[i*dim+2]) : 0.0; vacf[0] += vxsq; vacf[1] += vysq; vacf[2] += vzsq; vacf[3] += vxsq + vysq + vzsq; } //MPI_Allreduce(vacf,vector,4,MPI_DOUBLE,MPI_SUM,world); vacf[0] /= nvacf; vacf[1] /= nvacf; vacf[2] /= nvacf; vacf[3] /= nvacf; } template void cpuComputeVACF(double *vacf, double *v, double *voriginal, int *ilist, int nvacf, int dim, int inum); template void cpuComputeVACF(float *vacf, float *v, float *voriginal, int *ilist, int nvacf, int dim, int inum); #endif
36.645113
135
0.523739
[ "vector" ]
dc63ffabd23fcfac57d40cd94b2afaf98594b36d
15,014
cpp
C++
src/mainwindow.cpp
swagking0/Sudoku-GUI
52944a10d9387a0eac70b80acc4646361f5fd543
[ "MIT" ]
null
null
null
src/mainwindow.cpp
swagking0/Sudoku-GUI
52944a10d9387a0eac70b80acc4646361f5fd543
[ "MIT" ]
null
null
null
src/mainwindow.cpp
swagking0/Sudoku-GUI
52944a10d9387a0eac70b80acc4646361f5fd543
[ "MIT" ]
null
null
null
/** * @file mainwindow.cpp * * * @authors Mohith Bhargav Sunkara */ #include "mainwindow.h" #include <qtconcurrentrun.h> #include <QDebug> #include <QFileDialog> #include <QFuture> #include <QGridLayout> #include <QGroupBox> #include <QHBoxLayout> #include <QKeyEvent> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QProcess> #include <QPushButton> #include <QString> #include <QVBoxLayout> #include <fstream> #include <iostream> #include <vector> QT_USE_NAMESPACE MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setMinimumSize(850, 850); const QSize btnSize = QSize(250, 30); butSolve = new QPushButton("Solve By Spiking"); butSolve->setEnabled(false); butSolve->setFixedSize(btnSize); butAbout = new QPushButton("About Us"); butAbout->setFixedSize(btnSize); UpdateSudoku = new QPushButton("Update Sudoku"); butFile = new QPushButton("Get Sudoku"); butVideo = new QPushButton("Make Video"); butVideo->setFixedSize(btnSize); butVideo->setEnabled(false); simulatorBox = new QComboBox; simulatorBox->addItem(tr("pyNN.nest")); simulatorBox->addItem(tr("pyNN.spiNNaker")); simulatorBox->addItem(tr("pyNN.spiNNaker0.1")); simulatorBox->addItem(tr("spikey")); simulatorBox->addItem(tr("BrainScaleS")); simulatorBox->setFixedSize(btnSize); cubeBox = new QCheckBox("LEDCube"); cubeBox->setFixedSize(QSize(120, 30)); solverBox = new QComboBox; solverBox->addItem(tr("Spiking")); solverBox->addItem(tr("Spiking, Single Pop")); solverBox->addItem(tr("Spiking, Single Neuron")); solverBox->addItem(tr("Spiking, Mirror Inhib")); solverBox->setFixedSize(btnSize); butParams = new QPushButton("Parameter File"); butParams->setFixedSize(btnSize); solved = new QLabel(); solved->setAlignment(Qt::AlignCenter); ScrubBar = new QScrollBar(Qt::Horizontal); connect(ScrubBar, SIGNAL(valueChanged(int)), this, SLOT(scrubThroughResult(int))); ScrubBar->setEnabled(false); rowgrey = new QLineEdit; columngrey = new QLineEdit; // Labes definied in the whole GUI rows = new QLabel("Rows:"); columns = new QLabel("Columns:"); const QSize LabSize = QSize(80, 30); Solvers = new QLabel("Solvers:"); Solvers->setFixedSize(LabSize); Simulators = new QLabel("Simulators:"); Simulators->setFixedSize(LabSize); AllContent1 = new QGridLayout; HBox = new QHBoxLayout; HBox->addWidget(butAbout); HBox->addWidget(butSolve); HBox->addWidget(butVideo); HBox->addWidget(cubeBox); HBox2 = new QHBoxLayout; HBox2->addWidget(rows); HBox2->addWidget(rowgrey); HBox2->addWidget(columns); HBox2->addWidget(columngrey); HBox2->addWidget(UpdateSudoku); HBox2->addWidget(butFile); HBox3 = new QHBoxLayout; HBox3->addWidget(Solvers); HBox3->addWidget(solverBox); HBox3->addWidget(butParams); HBox3->addWidget(Simulators); HBox3->addWidget(simulatorBox); SudokuSimulators = new QGroupBox("Sudoku Solver--Simulator Tools"); SudokuSimulators->setLayout(HBox3); GroupTools = new QGroupBox("Application Tools"); GroupTools->setLayout(HBox); SudokuUpdater = new QGroupBox("Sudoku Drawing Tools"); SudokuUpdater->setLayout(HBox2); GroupSudoku = new QGroupBox(); Grid2 = new QGridLayout; SudokuMain = new SudokuMatrixWidget(this); Grid2->addWidget(SudokuMain); GroupSudoku->setLayout(Grid2); GroupSudoku->setFlat(true); GroupSudoku->setStyleSheet("background-color: #FFFAF0"); AllContent1->addWidget(SudokuSimulators, 1, 2, 1, 1); AllContent1->addWidget(GroupSudoku, 2, 2, 1, 1); AllContent1->addWidget(ScrubBar, 4, 2, 1, 1); AllContent1->addWidget(solved, 5, 2, 1, 1); AllContent1->addWidget(SudokuUpdater, 6, 2, 1, 1); AllContent1->addWidget(GroupTools, 7, 2, 1, 1); setLayout(AllContent1); setWindowTitle("Sudoku Solver Using Spiking Neural Networks - Test bed"); painterActiver = false; SudokuMain->ChangePainterState(painterActiver); Folder_to_Save = "./Save_Sudoku_png/"; QDir dir(Folder_to_Save); if (!dir.exists()) { dir.mkpath("."); } // QObject connectors area // Connecting the aboutus button QObject::connect(butAbout, SIGNAL(clicked()), this, SLOT(showAboutBox())); // Connecting the sudoku update button QObject::connect(UpdateSudoku, SIGNAL(clicked()), this, SLOT(updateSudokuBox())); // Connecting the sudoku slover button QObject::connect(butSolve, SIGNAL(clicked()), this, SLOT(sudokuspikingsolver())); // Connecting the butFile button to read json sudokufiles QObject::connect(butFile, SIGNAL(clicked()), this, SLOT(fromFile())); // Connecting the butParams button to read json parameter files QObject::connect(butParams, SIGNAL(clicked()), this, SLOT(paramsFromFile())); // Connecting the butVideo button to make videos on created folder QObject::connect(butVideo, SIGNAL(clicked()), this, SLOT(makeVideo())); // Initialize Path values old_path = std::string(getenv("PATH")); home = std::string(getenv("HOME")); } MainWindow::~MainWindow() {} void MainWindow::showAboutBox() const { QString Text = "This application is developed for testing spiking neural networks on " "solving sudoku part as of ISY-Project @ Bielefeld University"; QMessageBox msg(QMessageBox::Information, "About", Text, QMessageBox::Ok); msg.exec(); } void MainWindow::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_A) { // qInfo() << "hi i am left"; int i = 20; GroupSudoku->scroll(i, 0); } if (event->key() == Qt::Key_D) { // qInfo() << "hi i am right"; int j = 20; GroupSudoku->scroll(-j, 0); } if (event->key() == Qt::Key_W) { // qInfo() << "hi i am Up"; int k = 20; GroupSudoku->scroll(0, k); } if (event->key() == Qt::Key_S) { // qInfo() << "hi i am down"; int l = 20; GroupSudoku->scroll(0, -l); } } namespace { int SudokuInWidgetSize(int row, int col) { if (row == 2 && col == 2) { return 310; } else if (row == 2 && col == 3) { return 400; } else if (row == 2 && col == 4) { return 525; } else if (row == 2 && col == 5) { return 560; } else if (row == 3 && col == 3) { return 505; } else if (row == 3 && col == 4) { return 610; } else if (row == 3 && col == 5) { return 700; } else if (row == 4 && col == 4) { return 800; } else { std::cerr << "Warning: Unknown size of Sudoku for creation of videos!" << std::endl; return 0; } } } // namespace void MainWindow::fromFile() { ScrubBar->setEnabled(false); QString filename = QFileDialog::getOpenFileName( this, tr("Open File"), QDir("../sudokus/").absolutePath(), "All files (*.*);;Text File(*.json)"); std::string fileload = filename.toUtf8().constData(); if (!fileload.empty()) { sudoku = Sudoku(fileload); row = sudoku.getHeight(); col = sudoku.getWidth(); if (row > col) { col = sudoku.getHeight(); row = sudoku.getWidth(); } sudoku_size_widget = SudokuInWidgetSize(row, col); activate = true; painterActiver = true; SudokuMain->ChangePainterState(painterActiver); SudokuMain->ChangeRowColumnValue(row, col); SudokuMain->ChangeInnerValues(sudoku); SudokuMain->ChangeInnerResults(sudoku, activate); folder = Folder_to_Save + QString("%1").arg(QDateTime::currentMSecsSinceEpoch()) + "--" + QString(QVariant(row).toString()) + "x" + QString(QVariant(col).toString()); QDir dir(folder); if (!dir.exists()) { dir.mkpath("."); } butSolve->setEnabled(true); SudokuMain->update(); } } void MainWindow::paramsFromFile() { QString filename = QFileDialog::getOpenFileName( this, tr("Open Parameter File"), QDir("../config/").absolutePath(), "JSON File(*.json);;All files (*.*)"); std::string fileload = filename.toUtf8().constData(); if (!fileload.empty()) { parameter_file = filename.toStdString(); } } void MainWindow::makeVideo() { QString input_file = folder + "/" + "'%d.png'"; QString output_file = folder + "/" + "sample_output.mp4"; QString process_1 = "ffmpeg -framerate 5 -i"; QString finial_process = QString("%1 %2 %3").arg(process_1).arg(input_file).arg(output_file); char *cstr; std::string fname = finial_process.toStdString(); cstr = new char[fname.size() + 1]; strcpy(cstr, fname.c_str()); int status = system(cstr); qDebug() << status; } void MainWindow::updateSudokuBox() { ScrubBar->setEnabled(false); row = rowgrey->text().toInt(); col = columngrey->text().toInt(); if (row > col) { col = rowgrey->text().toInt(); row = columngrey->text().toInt(); } sudoku = Sudoku(row, col); sudoku_size_widget = SudokuInWidgetSize(row, col); activate = true; painterActiver = true; SudokuMain->ChangePainterState(painterActiver); SudokuMain->ChangeRowColumnValue(row, col); SudokuMain->ChangeInnerValues(sudoku); SudokuMain->ChangeInnerResults(sudoku, activate); butSolve->setEnabled(true); SudokuMain->update(); folder = Folder_to_Save + QString("%1").arg(QDateTime::currentMSecsSinceEpoch()) + "--" + QString(QVariant(row).toString()) + "x" + QString(QVariant(col).toString()); QDir dir(folder); if (!dir.exists()) { dir.mkpath("."); } } void MainWindow::scrubThroughResult(int bin) { sudoku = solver->updateSudokuFromResult(sudoku, result, bin); activate = false; painterActiver = true; SudokuMain->ChangePainterState(painterActiver); SudokuMain->ChangeInnerResults(sudoku, activate); if (sudoku.complete()) { solved->setStyleSheet("background-color:green;"); } else { solved->setStyleSheet("background-color:red;"); } int bin_size = solver->config()["bin_size"]; QString bin_info = ""; bin_info.append(QString::number(bin_size * bin)); bin_info.append("-"); bin_info.append(QString::number(bin_size * (bin + 1))); bin_info.append(" ms"); solved->setText(bin_info); solved->show(); SudokuMain->update(); QPixmap pic; if (sudoku_size_widget > 0) { pic = QPixmap::grabWidget(SudokuMain, 0, 0, sudoku_size_widget, sudoku_size_widget); QRegion region(0, 0, sudoku_size_widget, sudoku_size_widget); QPoint offset(0, 0); SudokuMain->render(&pic, offset, region); } else { pic = QPixmap::grabWidget(SudokuMain); SudokuMain->render(&pic); } int imageID = bin; QString imageName = folder + "/" + QString(QVariant(imageID).toString()) + ".png"; std::string imageNametocstring = imageName.toUtf8().constData(); std::ifstream ifile(imageNametocstring); if (!ifile) { pic.save(imageName); } } void MainWindow::sudokuspikingsolver() { std::string simulator = simulatorBox->currentText().toStdString(); std::string solver_str = solverBox->currentText().toStdString(); if (first_time) { // Append path by VirtualEnvironment std::string new_path; if (simulator == "pyNN.nest") { new_path = home + "/venvs/nest/bin:" + old_path; // Disable Spikey and spinnaker simulatorBox->setItemData(1, false, Qt::UserRole - 1); simulatorBox->setItemData(2, false, Qt::UserRole - 1); simulatorBox->setItemData(3, false, Qt::UserRole - 1); } else if (simulator == "spikey") { new_path = old_path; // Disable spiNNaker and Nest simulatorBox->setItemData(0, false, Qt::UserRole - 1); simulatorBox->setItemData(1, false, Qt::UserRole - 1); simulatorBox->setItemData(2, false, Qt::UserRole - 1); } else { new_path = home + "/venvs/spinnaker4/bin:" + old_path; simulatorBox->setItemData(0, false, Qt::UserRole - 1); simulatorBox->setItemData(3, false, Qt::UserRole - 1); } setenv("PATH", new_path.c_str(), 1); first_time = false; } if (simulator == "pyNN.nest") { simulator = simulator + "={\"threads\": 4}"; } else if (simulator == "pyNN.spiNNaker") { simulator = "spinnaker={\"source_neurons_per_core\": 25, \"neurons_per_core\" " ": 25}"; } else if (simulator == "pyNN.spiNNaker0.1") { simulator = "spinnaker={\"timestep\": 0.1, \"source_neurons_per_core\": 25, " "\"neurons_per_core\" : 25}"; } else if (simulator == "BrainScaleS") { simulator = "slurm.nmpm1={\"wafer\": 33, \"hicann\": " "[268,269,270,296,297,298], \"calib_path\" : " "\"/wang/data/calibration/brainscales/default-2017-09-26-1\", " "\"neuron_size\" : 4,\"digital_weight\" : true,\"bandwidth\" : " "0.8}"; } // Reset Sudoku solver --> Read parameters file try { if (solver_str == "Spiking") { solver = std::make_shared<spikingSudokuSolver>( spikingSudokuSolver(parameter_file)); } else if (solver_str == "Spiking, Single Pop") { solver = std::make_shared<SpikingSolverSinglePop>( SpikingSolverSinglePop(parameter_file)); } else if (solver_str == "Spiking, Mirror Inhib") { solver = std::make_shared<SSolveMirrorInhib>( SSolveMirrorInhib(parameter_file)); } else if (solver_str == "Spiking, Single Neuron") { solver = std::make_shared<SpikingSolverSingleNeuron>( SpikingSolverSingleNeuron(parameter_file)); } else { throw; } } catch (std::exception &e) { QMessageBox::warning( this, QString("Internal error"), QString("Solver not known or parameter file is corrupt!")); std::cerr << e.what() << std::endl; return; } try { solver->initialize(sudoku); } catch (std::exception &e) { butVideo->setEnabled(false); ScrubBar->setEnabled(false); QMessageBox::warning( this, QString("Wrong Parameter File"), QString("You chose a parameter file that either is faulty or does " "not match to the solver! Please retry using a different " "paramter file!")); std::cerr << e.what() << std::endl; return; } const char *instance = QFileInfo(QCoreApplication::applicationFilePath()) .fileName() .toLatin1() .data(); try { solver->run(instance, simulator.c_str(), cubeBox->isChecked()); } catch (std::exception &e) { butVideo->setEnabled(false); ScrubBar->setEnabled(false); QMessageBox::warning( this, QString("Simulation broke down"), QString("The simulation broke down. Either you chose parameters " "that are not valid for this simulator or the solver " "cannot be executed on the given simulation backend")); std::cerr << e.what() << std::endl; exit(1); } activate = false; painterActiver = true; // result dims [row][col][bin] butVideo->setEnabled(true); result = solver->evaluate(); ScrubBar->setEnabled(true); ScrubBar->setMinimum(0); ScrubBar->setMaximum(int(result[0][0].size()) - 1); ScrubBar->setValue(0); sudoku = solver->updateSudokuFromResult(sudoku, result, 0); if (sudoku.complete()) { solved->setStyleSheet("background-color:green;"); } else { solved->setStyleSheet("background-color:red;"); } int bin_size = solver->config()["bin_size"]; QString bin_info = "0-"; bin_info.append(QString::number(bin_size)); bin_info.append(" ms"); solved->setText(bin_info); solved->show(); SudokuMain->ChangeInnerResults(sudoku, activate); SudokuMain->ChangePainterState(painterActiver); SudokuMain->update(); }
27.803704
76
0.671773
[ "render", "vector" ]
dc65314305d1c5e7180f75bb2b1c2797d55de017
22,063
cpp
C++
plugins/Chorus/SimpleChorus.cpp
JoergBitzer/DAFx2020
64e2f02047ad843760aaf4dcc0aa6986cc82d1d2
[ "BSD-3-Clause" ]
null
null
null
plugins/Chorus/SimpleChorus.cpp
JoergBitzer/DAFx2020
64e2f02047ad843760aaf4dcc0aa6986cc82d1d2
[ "BSD-3-Clause" ]
null
null
null
plugins/Chorus/SimpleChorus.cpp
JoergBitzer/DAFx2020
64e2f02047ad843760aaf4dcc0aa6986cc82d1d2
[ "BSD-3-Clause" ]
1
2020-06-15T19:04:58.000Z
2020-06-15T19:04:58.000Z
/* ============================================================================== SimpleChorus.cpp Created: 13 May 2020 10:24:49pm Author: Bitzer ============================================================================== */ #include "SimpleChorus.h" SimpleChorus::SimpleChorus() :m_lastDelayValueLeft(0.0), m_lastDelayValueRight(0.0) { m_fs = 44100.0; m_feedback = 0.0; m_forward = 0.707; m_blend = 1.0; m_lfoMinDelay = 3.0; m_lfoMaxDelay = 8.5; m_lfoLeft.setLFOFunction(LFO::LFOFunctions::sinus); m_lfoRight.setLFOFunction(LFO::LFOFunctions::sinus); m_lfoLeft.setFrequency(3.5); m_lfoRight.setFrequency(3.5); m_lfoRight.setStartphase(0.0);//Einziger Unterschied zwischen Links und Rechts m_width = 0.0; m_nominalDelay = m_absolutMaxDelay_ms / 2.0; initChorus(); } void SimpleChorus::setSamplerate(double samplerate) { m_fs = samplerate; m_lfoLeft.setSamplerate(m_fs); m_lfoRight.setSamplerate(m_fs); setMinDelay(); setMaxDelay(); initChorus(); m_lowLeftForward.setSamplerate(m_fs); m_lowLeftForward.setDesignroutine(FirstOrderFilter::FilterDesign::lowpassButter); m_lowLeftForward.setCutoff(4000.0); m_highLeftForward.setSamplerate(m_fs); m_highLeftForward.setDesignroutine(FirstOrderFilter::FilterDesign::lowShelv); m_highLeftForward.setGainIndB(-6.0); m_highLeftForward.setCutoff(1500.0); m_lowRightForward.setSamplerate(m_fs); m_lowRightForward.setDesignroutine(FirstOrderFilter::FilterDesign::lowpassButter); m_lowRightForward.setCutoff(4000.0); m_highRightForward.setSamplerate(m_fs); m_highRightForward.setDesignroutine(FirstOrderFilter::FilterDesign::lowShelv); m_highRightForward.setGainIndB(-6.0); m_highRightForward.setCutoff(1500.0); m_lowLeftFeedback.setSamplerate(m_fs); m_lowLeftFeedback.setDesignroutine(FirstOrderFilter::FilterDesign::lowpassButter); m_lowLeftFeedback.setCutoff(6000.0); m_highLeftFeedback.setSamplerate(m_fs); m_highLeftFeedback.setDesignroutine(FirstOrderFilter::FilterDesign::lowShelv); m_highLeftFeedback.setGainIndB(-6.0); m_highLeftFeedback.setCutoff(1500.0); m_lowRightFeedback.setSamplerate(m_fs); m_lowRightFeedback.setDesignroutine(FirstOrderFilter::FilterDesign::lowpassButter); m_lowRightFeedback.setCutoff(6000.0); m_highRightFeedback.setSamplerate(m_fs); m_highRightFeedback.setDesignroutine(FirstOrderFilter::FilterDesign::lowShelv); m_highRightFeedback.setGainIndB(-2.0); m_highRightFeedback.setCutoff(1500.0); } void SimpleChorus::setMaxBlockSize(int maxSize) { m_lfoDataLeft.resize(maxSize); m_lfoDataRight.resize(maxSize); } int SimpleChorus::processData(std::vector<double>& dataInLeft, std::vector<double>& dataInRight, std::vector<double>& dataOutLeft, std::vector<double>& dataOutRight) { int NroOfSamples = dataInLeft.size(); m_lfoDataLeft.resize(NroOfSamples); m_lfoDataRight.resize(NroOfSamples); m_lfoLeft.getData(m_lfoDataLeft); m_lfoRight.getData(m_lfoDataRight); for (auto kk = 0U; kk < NroOfSamples; ++kk) { double curDelayLeft = m_lfoDataLeft[kk]; int curDelayLeftInt = static_cast<int>(curDelayLeft); double fracDelayLeft = curDelayLeft - curDelayLeftInt; double curDelayRight = m_lfoDataRight[kk]; int curDelayRightInt = static_cast<int>(curDelayRight); double fracDelayRight = curDelayRight - curDelayRightInt; double curInRight; double curInLeft = dataInLeft[kk] - m_feedback*m_lastDelayValueLeft; m_delayMemoryLeft[m_writeCounter] = curInLeft; if (m_nrofchns == 2) { curInRight = dataInRight[kk] - m_feedback * m_lastDelayValueRight; m_delayMemoryRight[m_writeCounter] = curInRight; } double outLeft, outRight; int leftReadPos = m_writeCounter - curDelayLeftInt; if (leftReadPos < 0) leftReadPos += m_absolutDelay_samples; int leftReadFeedbackPos = m_writeCounter - m_nominalDelay_samples; if (leftReadFeedbackPos < 0) leftReadFeedbackPos += m_absolutDelay_samples; int nextleftReadPos = leftReadPos - 1; if (nextleftReadPos < 0) nextleftReadPos += m_absolutDelay_samples; // if (nextleftReadPos == m_absolutDelay_samples) // nextleftReadPos = 0; outLeft = (1.0-fracDelayLeft)*m_delayMemoryLeft[leftReadPos] + fracDelayLeft*m_delayMemoryLeft[nextleftReadPos]; double feed_l = m_delayMemoryLeft[leftReadFeedbackPos]; feed_l = m_lowLeftFeedback.processOneSample(feed_l); feed_l = m_highLeftFeedback.processOneSample(feed_l); m_lastDelayValueLeft = feed_l; double outdata = m_forward * outLeft + m_blend * curInLeft; outdata = m_lowLeftForward.processOneSample(outdata); outdata = m_highLeftForward.processOneSample(outdata); dataOutLeft[kk] = outdata; if (m_nrofchns == 2) { int rightReadPos = m_writeCounter - curDelayRightInt; if (rightReadPos < 0) rightReadPos += m_absolutDelay_samples; int rightReadFeedbackPos = m_writeCounter - m_nominalDelay_samples; if (rightReadFeedbackPos < 0) rightReadFeedbackPos += m_absolutDelay_samples; int nextrightReadPos = rightReadPos - 1; if (nextrightReadPos < 0) nextrightReadPos += m_absolutDelay_samples;; outRight = (1.0 - fracDelayRight)*m_delayMemoryRight[rightReadPos] + fracDelayRight*m_delayMemoryRight[nextrightReadPos]; double feed_r = m_delayMemoryRight[rightReadFeedbackPos]; feed_r = m_lowRightFeedback.processOneSample(feed_r); feed_r = m_highRightFeedback.processOneSample(feed_r); m_lastDelayValueRight = feed_r; double outdatar = m_forward * outRight + m_blend * curInRight; outdatar = m_lowRightForward.processOneSample(outdatar); outdatar = m_highRightForward.processOneSample(outdatar); dataOutRight[kk] = outdatar; } ++m_writeCounter; if (m_writeCounter == m_absolutDelay_samples) m_writeCounter = 0; } return 0; } void SimpleChorus::setRate(float rate_Hz) { m_lfoLeft.setFrequency(rate_Hz); m_lfoRight.setFrequency(rate_Hz); } void SimpleChorus::initChorus() { m_absolutDelay_samples = static_cast<int> (m_absolutMaxDelay_ms * 0.001 * m_fs + 0.5); m_delayMemoryLeft.resize(m_absolutDelay_samples); m_delayMemoryRight.resize(m_absolutDelay_samples); m_writeCounter = 0; } void SimpleChorus::setMinDelay() { m_nominalDelay = (m_lfoMaxDelay - m_lfoMinDelay)*0.5 + m_lfoMinDelay; m_nominalDelay_samples = int(m_nominalDelay * 0.001 * m_fs + 0.5); if (m_nominalDelay_samples <= 0) m_nominalDelay_samples = 1; if (m_nominalDelay_samples >= m_absolutDelay_samples) m_nominalDelay_samples = m_absolutDelay_samples - 1; m_width = (1.0 - m_lfoMinDelay / m_nominalDelay) * 100.0; int minDelay_Samples = m_lfoMinDelay * 0.001 * m_fs; if (minDelay_Samples < 0) minDelay_Samples = 0; if (minDelay_Samples >= m_absolutDelay_samples) minDelay_Samples = m_absolutDelay_samples; m_lfoLeft.setMin(minDelay_Samples); m_lfoRight.setMin(minDelay_Samples); } void SimpleChorus::setMaxDelay() { m_nominalDelay = (m_lfoMaxDelay - m_lfoMinDelay)*0.5 + m_lfoMinDelay; m_nominalDelay_samples = int(m_nominalDelay * 0.001 * m_fs + 0.5); if (m_nominalDelay_samples <= 0) m_nominalDelay_samples = 1; if (m_nominalDelay_samples >= m_absolutDelay_samples) m_nominalDelay_samples = m_absolutDelay_samples - 1; m_width = (1.0 - m_lfoMinDelay / m_nominalDelay) * 100.0; int maxDelay_Samples = m_lfoMaxDelay * 0.001 * m_fs; if (maxDelay_Samples < 0) maxDelay_Samples = 0; if (maxDelay_Samples >= m_absolutDelay_samples) maxDelay_Samples = m_absolutDelay_samples; m_lfoLeft.setMax(maxDelay_Samples); m_lfoRight.setMax(maxDelay_Samples); } void SimpleChorus::computeSampleDelay() { m_nominalDelay_samples = int(m_nominalDelay * 0.001 * m_fs + 0.5); if (m_nominalDelay_samples <= 0) m_nominalDelay_samples = 1; m_lfoMinDelay = m_nominalDelay * (1.0 - m_width * 0.01); if (m_lfoMinDelay <= 0.0) m_lfoMinDelay = 1.0 / m_fs * 1000.0; m_lfoMaxDelay = m_nominalDelay * (1.0 + m_width * 0.01); if (m_lfoMaxDelay >= m_absolutMaxDelay_ms) m_lfoMaxDelay = m_absolutMaxDelay_ms - 1.0 / m_fs * 1000.0; m_lfoLeft.setMin(m_lfoMinDelay * 0.001 * m_fs); m_lfoRight.setMin(m_lfoMinDelay * 0.001 * m_fs); m_lfoLeft.setMax(m_lfoMaxDelay * 0.001 * m_fs); m_lfoRight.setMax(m_lfoMaxDelay * 0.001 * m_fs); } int ChorusParameter::addParameter(std::vector<std::unique_ptr<RangedAudioParameter>>& paramVector) { paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusDelay.ID, paramChorusDelay.name, NormalisableRange<float>(paramChorusDelay.minValue, paramChorusDelay.maxValue), paramChorusDelay.defaultValue, paramChorusDelay.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 10 + 0.5)*0.1, MaxLen) + " ms"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusWidth.ID, paramChorusWidth.name, NormalisableRange<float>(paramChorusWidth.minValue, paramChorusWidth.maxValue), paramChorusWidth.defaultValue, paramChorusWidth.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 10 + 0.5)*0.1, MaxLen) + " %"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusDirectOut.ID, paramChorusDirectOut.name, NormalisableRange<float>(paramChorusDirectOut.minValue, paramChorusDirectOut.maxValue), paramChorusDirectOut.defaultValue, paramChorusDirectOut.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 100 + 0.5)*0.01, MaxLen) + ""); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusForward.ID, paramChorusForward.name, NormalisableRange<float>(paramChorusForward.minValue, paramChorusForward.maxValue), paramChorusForward.defaultValue, paramChorusForward.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 100 + 0.5)*0.01, MaxLen) + ""); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusFFLow.ID, paramChorusFFLow.name, NormalisableRange<float>(paramChorusFFLow.minValue, paramChorusFFLow.maxValue), paramChorusFFLow.defaultValue, paramChorusFFLow.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int(exp(value) * 10 + 0.5)*0.1, MaxLen) + " Hz"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusFFHigh.ID, paramChorusFFHigh.name, NormalisableRange<float>(paramChorusFFHigh.minValue, paramChorusFFHigh.maxValue), paramChorusFFHigh.defaultValue, paramChorusFFHigh.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int(exp(value) * 10 + 0.5)*0.1, MaxLen) + " Hz"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusFeedback.ID, paramChorusFeedback.name, NormalisableRange<float>(paramChorusFeedback.minValue, paramChorusFeedback.maxValue), paramChorusFeedback.defaultValue, paramChorusFeedback.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 100 + 0.5)*0.01, MaxLen) + ""); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusFBLow.ID, paramChorusFBLow.name, NormalisableRange<float>(paramChorusFBLow.minValue, paramChorusFBLow.maxValue), paramChorusFBLow.defaultValue, paramChorusFBLow.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int(exp(value) * 10 + 0.5)*0.1, MaxLen) + " Hz"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusFBHigh.ID, paramChorusFBHigh.name, NormalisableRange<float>(paramChorusFBHigh.minValue, paramChorusFBHigh.maxValue), paramChorusFBHigh.defaultValue, paramChorusFBHigh.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int(exp(value) * 10 + 0.5)*0.1, MaxLen) + " Hz"); }, [](const String& text) {return text.getFloatValue(); })); paramVector.push_back(std::make_unique<AudioParameterFloat>(paramChorusPhase.ID, paramChorusPhase.name, NormalisableRange<float>(paramChorusPhase.minValue, paramChorusPhase.maxValue), paramChorusPhase.defaultValue, paramChorusPhase.unitName, AudioProcessorParameter::genericParameter, [](float value, int MaxLen) { return (String(int((value) * 10 + 0.5)*0.1, MaxLen) + ""); }, [](const String& text) {return text.getFloatValue(); })); return 0; } ChorusParameterComponent::ChorusParameterComponent(AudioProcessorValueTreeState & vts) :m_vts(vts), somethingChanged(nullptr) { somethingChanged = nullptr; m_delayLabel.setText("Delay", NotificationType::dontSendNotification); addAndMakeVisible(m_delayLabel); m_delaySlider.setSliderStyle(Slider::SliderStyle::LinearHorizontal); m_delaySlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxAbove, true, 80, 20); m_delayAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusDelay.ID, m_delaySlider); addAndMakeVisible(m_delaySlider); m_delaySlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_widthLabel.setText("Width", NotificationType::dontSendNotification); addAndMakeVisible(m_widthLabel); m_widthSlider.setSliderStyle(Slider::SliderStyle::LinearHorizontal); m_widthSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_widthAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusWidth.ID, m_widthSlider); addAndMakeVisible(m_widthSlider); m_widthSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_forwardLabel.setText("Forward", NotificationType::dontSendNotification); addAndMakeVisible(m_forwardLabel); m_forwardSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_forwardSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_forwardAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusForward.ID, m_forwardSlider); addAndMakeVisible(m_forwardSlider); m_forwardSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_ffLowLabel.setText("FW Low", NotificationType::dontSendNotification); addAndMakeVisible(m_ffLowLabel); m_ffLowSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_ffLowSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_ffLowAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusFFLow.ID, m_ffLowSlider); addAndMakeVisible(m_ffLowSlider); m_ffLowSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_ffHighLabel.setText("FW High", NotificationType::dontSendNotification); addAndMakeVisible(m_ffHighLabel); m_ffHighSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_ffHighSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_ffHighAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusFFHigh.ID, m_ffHighSlider); addAndMakeVisible(m_ffHighSlider); m_ffHighSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_feedbackLabel.setText("Feedback", NotificationType::dontSendNotification); addAndMakeVisible(m_feedbackLabel); m_feedbackSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_feedbackSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_feedbackAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusFeedback.ID, m_feedbackSlider); addAndMakeVisible(m_feedbackSlider); m_feedbackSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_fbLowLabel.setText("FB Low", NotificationType::dontSendNotification); addAndMakeVisible(m_fbLowLabel); m_fbLowSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_fbLowSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_fbLowAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusFBLow.ID, m_fbLowSlider); addAndMakeVisible(m_fbLowSlider); m_fbLowSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_fbHighLabel.setText("FB High", NotificationType::dontSendNotification); addAndMakeVisible(m_fbHighLabel); m_fbHighSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_fbHighSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_fbHighAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusFBHigh.ID, m_fbHighSlider); addAndMakeVisible(m_fbHighSlider); m_fbHighSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_directLabel.setText("Direct Out", NotificationType::dontSendNotification); addAndMakeVisible(m_directLabel); m_directSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_directSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_directAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusDirectOut.ID, m_directSlider); addAndMakeVisible(m_directSlider); m_directSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; m_phaseLRLabel.setText("Phase L/R", NotificationType::dontSendNotification); addAndMakeVisible(m_phaseLRLabel); m_phaseLRSlider.setSliderStyle(Slider::SliderStyle::Rotary); m_phaseLRSlider.setTextBoxStyle(Slider::TextEntryBoxPosition::TextBoxBelow, true, 80, 20); m_phaseLRAttachment = std::make_unique<SliderAttachment>(m_vts, paramChorusPhase.ID, m_phaseLRSlider); addAndMakeVisible(m_phaseLRSlider); m_phaseLRSlider.onValueChange = [this]() {if (somethingChanged != nullptr) somethingChanged(); }; } void ChorusParameterComponent::paint(Graphics & g) { g.fillAll((getLookAndFeel().findColour(ResizableWindow::backgroundColourId)).brighter(0.2)); } #define GUI_MIN_DISTANCE 5 #define ELEMNT_HEIGHT 20 #define FROM_MID_DISTANCE 40 #define ROTARYSIZE 60 #define LABEL_WIDTH 60 void ChorusParameterComponent::resized() { int w = getWidth(); int h = getHeight(); m_delayLabel.setBounds(GUI_MIN_DISTANCE + ROTARYSIZE, GUI_MIN_DISTANCE, LABEL_WIDTH, ELEMNT_HEIGHT); m_delaySlider.setBounds(GUI_MIN_DISTANCE + ROTARYSIZE, GUI_MIN_DISTANCE, w - 2 * GUI_MIN_DISTANCE-2*ROTARYSIZE,2*ELEMNT_HEIGHT); m_widthLabel.setBounds(GUI_MIN_DISTANCE + w/2 - LABEL_WIDTH/2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_widthSlider.setBounds(GUI_MIN_DISTANCE + ROTARYSIZE, GUI_MIN_DISTANCE + 3 * ELEMNT_HEIGHT, w - 2 * GUI_MIN_DISTANCE - 2*ROTARYSIZE, 2 * ELEMNT_HEIGHT); m_forwardLabel.setBounds(w/2 + FROM_MID_DISTANCE + GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_forwardSlider.setBounds(w / 2 + FROM_MID_DISTANCE + GUI_MIN_DISTANCE + LABEL_WIDTH/2-ROTARYSIZE/2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_ffLowLabel.setBounds(w / 2 + ROTARYSIZE + FROM_MID_DISTANCE + 2*GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_ffLowSlider.setBounds(w / 2 + ROTARYSIZE + FROM_MID_DISTANCE + 2*GUI_MIN_DISTANCE + LABEL_WIDTH / 2 - ROTARYSIZE / 2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_ffHighLabel.setBounds(w / 2 + 2*ROTARYSIZE + FROM_MID_DISTANCE + 3 * GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_ffHighSlider.setBounds(w / 2 + 2*ROTARYSIZE + FROM_MID_DISTANCE + 3 * GUI_MIN_DISTANCE + LABEL_WIDTH / 2 - ROTARYSIZE / 2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_fbHighLabel.setBounds(w / 2 - ROTARYSIZE - FROM_MID_DISTANCE - GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_fbHighSlider.setBounds(w / 2 - ROTARYSIZE - FROM_MID_DISTANCE - GUI_MIN_DISTANCE - LABEL_WIDTH / 2 + ROTARYSIZE / 2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_fbLowLabel.setBounds(w / 2 - 2*ROTARYSIZE - FROM_MID_DISTANCE - 2 * GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_fbLowSlider.setBounds(w / 2 - 2*ROTARYSIZE - FROM_MID_DISTANCE - 2 * GUI_MIN_DISTANCE - LABEL_WIDTH / 2 + ROTARYSIZE / 2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_feedbackLabel.setBounds(w / 2 - 3 * ROTARYSIZE - FROM_MID_DISTANCE - 3 * GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 4 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_feedbackSlider.setBounds(w / 2 - 3 * ROTARYSIZE - FROM_MID_DISTANCE - 3 * GUI_MIN_DISTANCE - LABEL_WIDTH / 2 + ROTARYSIZE / 2, GUI_MIN_DISTANCE + 5 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_directLabel.setBounds(GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 2 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_directSlider.setBounds(GUI_MIN_DISTANCE, GUI_MIN_DISTANCE + 3 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); m_phaseLRLabel.setBounds(w-GUI_MIN_DISTANCE-LABEL_WIDTH, GUI_MIN_DISTANCE + 2 * ELEMNT_HEIGHT, LABEL_WIDTH, ELEMNT_HEIGHT); m_phaseLRSlider.setBounds(w-GUI_MIN_DISTANCE-ROTARYSIZE, GUI_MIN_DISTANCE + 3 * ELEMNT_HEIGHT, ROTARYSIZE, 3 * ELEMNT_HEIGHT); }
43.862823
199
0.755745
[ "vector" ]
dc65bc03b7ce74ddee305469c663cef690fda466
2,402
hpp
C++
ios/Pods/boost-for-react-native/boost/polygon/polygon_45_data.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/polygon/polygon_45_data.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/polygon/polygon_45_data.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
/* Copyright 2008 Intel Corporation Use, modification and distribution are subject to 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). */ #ifndef BOOST_POLYGON_POLYGON_45_DATA_HPP #define BOOST_POLYGON_POLYGON_45_DATA_HPP #include "isotropy.hpp" namespace boost { namespace polygon{ struct polygon_45_concept; template <typename T> class polygon_data; template <typename T> class polygon_45_data { public: typedef polygon_45_concept geometry_type; typedef T coordinate_type; typedef typename std::vector<point_data<coordinate_type> >::const_iterator iterator_type; typedef typename coordinate_traits<T>::coordinate_distance area_type; typedef point_data<T> point_type; inline polygon_45_data() : coords_() {} //do nothing default constructor template<class iT> inline polygon_45_data(iT input_begin, iT input_end) : coords_(input_begin, input_end) {} template<class iT> inline polygon_45_data& set(iT input_begin, iT input_end) { coords_.clear(); //just in case there was some old data there coords_.insert(coords_.end(), input_begin, input_end); return *this; } // copy constructor (since we have dynamic memory) inline polygon_45_data(const polygon_45_data& that) : coords_(that.coords_) {} // assignment operator (since we have dynamic memory do a deep copy) inline polygon_45_data& operator=(const polygon_45_data& that) { coords_ = that.coords_; return *this; } template <typename T2> inline polygon_45_data& operator=(const T2& rvalue); inline bool operator==(const polygon_45_data& that) const { if(coords_.size() != that.coords_.size()) return false; for(std::size_t i = 0; i < coords_.size(); ++i) { if(coords_[i] != that.coords_[i]) return false; } return true; } inline bool operator!=(const polygon_45_data& that) const { return !((*this) == that); } // get begin iterator, returns a pointer to a const Unit inline iterator_type begin() const { return coords_.begin(); } // get end iterator, returns a pointer to a const Unit inline iterator_type end() const { return coords_.end(); } inline std::size_t size() const { return coords_.size(); } public: std::vector<point_data<coordinate_type> > coords_; }; } } #endif
32.90411
92
0.711907
[ "vector" ]
dc6862d180e17ab3603c1f60d9a7892385d3c0fb
11,854
cpp
C++
rmf_fleet_adapter/test/services/test_FindPath.cpp
Capstone-S13/rmf_ros2
66721dd2ab5a458c050bad154c6a17d8e4b5c8f4
[ "Apache-2.0" ]
18
2021-03-30T03:03:16.000Z
2022-03-21T13:48:41.000Z
rmf_fleet_adapter/test/services/test_FindPath.cpp
Capstone-S13/rmf_ros2
66721dd2ab5a458c050bad154c6a17d8e4b5c8f4
[ "Apache-2.0" ]
147
2021-03-09T09:16:27.000Z
2022-03-25T11:26:58.000Z
rmf_fleet_adapter/test/services/test_FindPath.cpp
Capstone-S13/rmf_ros2
66721dd2ab5a458c050bad154c6a17d8e4b5c8f4
[ "Apache-2.0" ]
20
2021-05-21T06:54:58.000Z
2022-03-18T10:43:01.000Z
/* * Copyright (C) 2020 Open Source Robotics Foundation * * 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 <services/FindPath.hpp> #include <rmf_traffic/geometry/Circle.hpp> #include <rmf_traffic/schedule/Database.hpp> #include <rmf_traffic/DetectConflict.hpp> #include <rmf_fleet_adapter/agv/parse_graph.hpp> #include <rmf_utils/catch.hpp> #include "../thread_cooldown.hpp" //============================================================================== SCENARIO("Find a path") { rmf_fleet_adapter_test::thread_cooldown = true; auto database = std::make_shared<rmf_traffic::schedule::Database>(); rmf_traffic::Profile profile{ rmf_traffic::geometry::make_final_convex< rmf_traffic::geometry::Circle>(1.0) }; auto p0 = rmf_traffic::schedule::make_participant( rmf_traffic::schedule::ParticipantDescription{ "participant 1", "test_Negotiator", rmf_traffic::schedule::ParticipantDescription::Rx::Responsive, profile }, database); auto p1 = rmf_traffic::schedule::make_participant( rmf_traffic::schedule::ParticipantDescription{ "participant 2", "test_Negotiator", rmf_traffic::schedule::ParticipantDescription::Rx::Responsive, profile }, database); const std::string test_map_name = "test_map"; rmf_traffic::agv::Graph graph; graph.add_waypoint(test_map_name, {0.0, -10.0}); // 0 graph.add_waypoint(test_map_name, {0.0, -5.0}); // 1 graph.add_waypoint(test_map_name, {5.0, -5.0}).set_holding_point(true); // 2 graph.add_waypoint(test_map_name, {-10.0, 0.0}); // 3 graph.add_waypoint(test_map_name, {-5.0, 0.0}); // 4 graph.add_waypoint(test_map_name, {0.0, 0.0}); // 5 graph.add_waypoint(test_map_name, {5.0, 0.0}); // 6 graph.add_waypoint(test_map_name, {10.0, 0.0}); // 7 graph.add_waypoint(test_map_name, {0.0, 5.0}); // 8 graph.add_waypoint(test_map_name, {5.0, 5.0}).set_holding_point(true); // 9 graph.add_waypoint(test_map_name, {0.0, 10.0}); // 10 /* * 10 * | * | * 8------9 * | | * | | * 3------4------5------6------7 * | | * | | * 1------2 * | * | * 0 **/ auto add_bidir_lane = [&](const std::size_t w0, const std::size_t w1) { graph.add_lane(w0, w1); graph.add_lane(w1, w0); }; add_bidir_lane(0, 1); add_bidir_lane(1, 2); add_bidir_lane(1, 5); add_bidir_lane(2, 6); add_bidir_lane(3, 4); add_bidir_lane(4, 5); add_bidir_lane(5, 6); add_bidir_lane(6, 7); add_bidir_lane(5, 8); add_bidir_lane(6, 9); add_bidir_lane(8, 9); add_bidir_lane(8, 10); const rmf_traffic::agv::VehicleTraits traits{ {0.7, 0.3}, {1.0, 0.45}, profile }; rmf_traffic::agv::Planner::Configuration configuration{graph, traits}; const auto planner = std::make_shared<rmf_traffic::agv::Planner>( configuration, rmf_traffic::agv::Planner::Options{nullptr} ); const auto now = std::chrono::steady_clock::now(); using namespace std::chrono_literals; WHEN("Robots need to cross paths") { const auto start_0 = rmf_traffic::agv::Plan::Start(now, 0, M_PI/2.0); const auto goal_0 = rmf_traffic::agv::Plan::Goal(10); const auto start_1 = rmf_traffic::agv::Plan::Start(now, 3, 0.0); const auto goal_1 = rmf_traffic::agv::Plan::Goal(7); auto path_service = std::make_shared<rmf_fleet_adapter::services::FindPath>( planner, rmf_traffic::agv::Plan::StartSet({start_0}), goal_0, database->snapshot(), p0.id(), std::make_shared<rmf_traffic::Profile>(p0.description().profile())); std::promise<rmf_traffic::agv::Plan::Result> result_0_promise; auto result_0_future = result_0_promise.get_future(); auto path_sub = rmf_rxcpp::make_job<rmf_fleet_adapter::services::FindPath::Result>( path_service) .observe_on(rxcpp::observe_on_event_loop()) .subscribe( [&result_0_promise](const auto& result) { result_0_promise.set_value(result); }); const auto status_0 = result_0_future.wait_for(1s); REQUIRE(std::future_status::ready == status_0); const auto result_0 = result_0_future.get(); REQUIRE(result_0.success()); // First we will test that a conflict happens when p0 does not put its // itinerary in the database. path_service = std::make_shared<rmf_fleet_adapter::services::FindPath>( planner, rmf_traffic::agv::Plan::StartSet({start_1}), goal_1, database->snapshot(), p1.id(), std::make_shared<rmf_traffic::Profile>(p1.description().profile())); std::promise<rmf_traffic::agv::Plan::Result> pre_result_1_promise; auto pre_result_1_future = pre_result_1_promise.get_future(); path_sub = rmf_rxcpp::make_job<rmf_fleet_adapter::services::FindPath::Result>( path_service) .observe_on(rxcpp::observe_on_event_loop()) .subscribe( [&pre_result_1_promise](const auto& result) { pre_result_1_promise.set_value(result); }); const auto pre_status_1 = pre_result_1_future.wait_for(1s); REQUIRE(std::future_status::ready == pre_status_1); const auto pre_result_1 = pre_result_1_future.get(); REQUIRE(pre_result_1.success()); bool at_least_one_conflict = false; for (const auto& t0 : result_0->get_itinerary()) { for (const auto& t1 : pre_result_1->get_itinerary()) { at_least_one_conflict |= rmf_traffic::DetectConflict::between( p0.description().profile(), t0.trajectory(), p1.description().profile(), t1.trajectory()).has_value(); } } CHECK(at_least_one_conflict); // Now we perform FindPath again for p1, but with p0's itinerary // in the schedule p0.set(result_0->get_itinerary()); path_service = std::make_shared<rmf_fleet_adapter::services::FindPath>( planner, rmf_traffic::agv::Plan::StartSet({start_1}), goal_1, database->snapshot(), p1.id(), std::make_shared<rmf_traffic::Profile>(p1.description().profile())); std::promise<rmf_traffic::agv::Plan::Result> result_1_promise; auto result_1_future = result_1_promise.get_future(); path_sub = rmf_rxcpp::make_job<rmf_fleet_adapter::services::FindPath::Result>( path_service) .observe_on(rxcpp::observe_on_event_loop()) .subscribe( [&result_1_promise](const auto& result) { result_1_promise.set_value(result); }); const auto status_1 = result_1_future.wait_for(1s); REQUIRE(std::future_status::ready == status_1); const auto result_1 = result_1_future.get(); REQUIRE(result_1.success()); for (const auto& t0 : result_0->get_itinerary()) { for (const auto& t1 : result_1->get_itinerary()) { CHECK_FALSE(rmf_traffic::DetectConflict::between( p0.description().profile(), t0.trajectory(), p1.description().profile(), t1.trajectory())); } } } WHEN("A robot is perpetually blocking the path of another") { const auto l0 = graph.get_waypoint(5).get_location(); const auto start_1 = rmf_traffic::agv::Plan::Start(now, 3, 0.0); const auto goal_1 = rmf_traffic::agv::Plan::Goal(7); rmf_traffic::Trajectory blocking_traj; blocking_traj.insert( now, {l0[0], l0[1], 0.0}, Eigen::Vector3d::Zero()); blocking_traj.insert( now + 1h, {l0[0], l0[1], 0.0}, Eigen::Vector3d::Zero()); rmf_traffic::Route blocking_route( graph.get_waypoint(5).get_map_name(), blocking_traj); p0.set({blocking_route}); auto path_service = std::make_shared<rmf_fleet_adapter::services::FindPath>( planner, rmf_traffic::agv::Plan::StartSet({start_1}), goal_1, database->snapshot(), p1.id(), std::make_shared<rmf_traffic::Profile>(p1.description().profile())); std::promise<rmf_traffic::agv::Plan::Result> result_1_promise; auto result_1_future = result_1_promise.get_future(); auto path_sub = rmf_rxcpp::make_job<rmf_fleet_adapter::services::FindPath::Result>( path_service) .observe_on(rxcpp::observe_on_event_loop()) .subscribe( [&result_1_promise](const auto& result) { result_1_promise.set_value(result); }); auto status_1 = result_1_future.wait_for(60s); REQUIRE(std::future_status::ready == status_1); const auto result_1 = result_1_future.get(); REQUIRE(result_1.success()); // The FindPath service should return us a "successful" result, but that // result intentionally conflicts with p0. When we submit this to the // schedule in a real deployment, the ScheduleNode will detect the conflict // and begin a negotiation. bool at_least_one_conflict = false; for (const auto& t1 : result_1->get_itinerary()) { at_least_one_conflict = at_least_one_conflict || rmf_traffic::DetectConflict::between( p0.description().profile(), blocking_traj, p1.description().profile(), t1.trajectory()); } CHECK(at_least_one_conflict); } } //============================================================================== SCENARIO("Office map") { rmf_fleet_adapter_test::thread_cooldown = true; rmf_traffic::Profile profile{ rmf_traffic::geometry::make_final_convex< rmf_traffic::geometry::Circle>(1.0) }; const rmf_traffic::agv::VehicleTraits traits{ {0.5, 0.75}, {0.6, 2.0}, profile }; const auto graph = rmf_fleet_adapter::agv::parse_graph( TEST_RESOURCES_DIR "/office_nav.yaml", traits); auto database = std::make_shared<rmf_traffic::schedule::Database>(); auto p0 = rmf_traffic::schedule::make_participant( rmf_traffic::schedule::ParticipantDescription{ "participant 1", "test_Negotiator", rmf_traffic::schedule::ParticipantDescription::Rx::Responsive, profile }, database); rmf_traffic::agv::Planner::Configuration configuration{graph, traits}; const auto planner = std::make_shared<rmf_traffic::agv::Planner>( configuration, rmf_traffic::agv::Planner::Options{nullptr} ); const auto now = std::chrono::steady_clock::now(); const auto starts = rmf_traffic::agv::Plan::StartSet( { {now, 17, 2.7496, Eigen::Vector2d(7.75515, -5.7033)} }); const auto goal = rmf_traffic::agv::Plan::Goal(10); auto path_service = std::make_shared<rmf_fleet_adapter::services::FindPath>( planner, starts, goal, database->snapshot(), 0, std::make_shared<rmf_traffic::Profile>(p0.description().profile())); std::promise<rmf_traffic::agv::Plan::Result> result_0_promise; auto result_0_future = result_0_promise.get_future(); auto path_sub = rmf_rxcpp::make_job<rmf_fleet_adapter::services::FindPath::Result>( path_service) .observe_on(rxcpp::observe_on_event_loop()) .subscribe( [&result_0_promise](const auto& result) { result_0_promise.set_value(result); }); using namespace std::chrono_literals; const auto status_0 = result_0_future.wait_for(2min); REQUIRE(std::future_status::ready == status_0); const auto result_0 = result_0_future.get(); REQUIRE(result_0.success()); }
33.391549
80
0.652607
[ "geometry" ]
dc6a57739400d07dff519df45da193bca0ee3c38
8,348
cpp
C++
aws-cpp-sdk-license-manager/source/model/LicenseConfiguration.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-license-manager/source/model/LicenseConfiguration.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-license-manager/source/model/LicenseConfiguration.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/license-manager/model/LicenseConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LicenseManager { namespace Model { LicenseConfiguration::LicenseConfiguration() : m_licenseConfigurationIdHasBeenSet(false), m_licenseConfigurationArnHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_licenseCountingType(LicenseCountingType::NOT_SET), m_licenseCountingTypeHasBeenSet(false), m_licenseRulesHasBeenSet(false), m_licenseCount(0), m_licenseCountHasBeenSet(false), m_licenseCountHardLimit(false), m_licenseCountHardLimitHasBeenSet(false), m_consumedLicenses(0), m_consumedLicensesHasBeenSet(false), m_statusHasBeenSet(false), m_ownerAccountIdHasBeenSet(false), m_consumedLicenseSummaryListHasBeenSet(false), m_managedResourceSummaryListHasBeenSet(false) { } LicenseConfiguration::LicenseConfiguration(JsonView jsonValue) : m_licenseConfigurationIdHasBeenSet(false), m_licenseConfigurationArnHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_licenseCountingType(LicenseCountingType::NOT_SET), m_licenseCountingTypeHasBeenSet(false), m_licenseRulesHasBeenSet(false), m_licenseCount(0), m_licenseCountHasBeenSet(false), m_licenseCountHardLimit(false), m_licenseCountHardLimitHasBeenSet(false), m_consumedLicenses(0), m_consumedLicensesHasBeenSet(false), m_statusHasBeenSet(false), m_ownerAccountIdHasBeenSet(false), m_consumedLicenseSummaryListHasBeenSet(false), m_managedResourceSummaryListHasBeenSet(false) { *this = jsonValue; } LicenseConfiguration& LicenseConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("LicenseConfigurationId")) { m_licenseConfigurationId = jsonValue.GetString("LicenseConfigurationId"); m_licenseConfigurationIdHasBeenSet = true; } if(jsonValue.ValueExists("LicenseConfigurationArn")) { m_licenseConfigurationArn = jsonValue.GetString("LicenseConfigurationArn"); m_licenseConfigurationArnHasBeenSet = true; } if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("Description")) { m_description = jsonValue.GetString("Description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("LicenseCountingType")) { m_licenseCountingType = LicenseCountingTypeMapper::GetLicenseCountingTypeForName(jsonValue.GetString("LicenseCountingType")); m_licenseCountingTypeHasBeenSet = true; } if(jsonValue.ValueExists("LicenseRules")) { Array<JsonView> licenseRulesJsonList = jsonValue.GetArray("LicenseRules"); for(unsigned licenseRulesIndex = 0; licenseRulesIndex < licenseRulesJsonList.GetLength(); ++licenseRulesIndex) { m_licenseRules.push_back(licenseRulesJsonList[licenseRulesIndex].AsString()); } m_licenseRulesHasBeenSet = true; } if(jsonValue.ValueExists("LicenseCount")) { m_licenseCount = jsonValue.GetInt64("LicenseCount"); m_licenseCountHasBeenSet = true; } if(jsonValue.ValueExists("LicenseCountHardLimit")) { m_licenseCountHardLimit = jsonValue.GetBool("LicenseCountHardLimit"); m_licenseCountHardLimitHasBeenSet = true; } if(jsonValue.ValueExists("ConsumedLicenses")) { m_consumedLicenses = jsonValue.GetInt64("ConsumedLicenses"); m_consumedLicensesHasBeenSet = true; } if(jsonValue.ValueExists("Status")) { m_status = jsonValue.GetString("Status"); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("OwnerAccountId")) { m_ownerAccountId = jsonValue.GetString("OwnerAccountId"); m_ownerAccountIdHasBeenSet = true; } if(jsonValue.ValueExists("ConsumedLicenseSummaryList")) { Array<JsonView> consumedLicenseSummaryListJsonList = jsonValue.GetArray("ConsumedLicenseSummaryList"); for(unsigned consumedLicenseSummaryListIndex = 0; consumedLicenseSummaryListIndex < consumedLicenseSummaryListJsonList.GetLength(); ++consumedLicenseSummaryListIndex) { m_consumedLicenseSummaryList.push_back(consumedLicenseSummaryListJsonList[consumedLicenseSummaryListIndex].AsObject()); } m_consumedLicenseSummaryListHasBeenSet = true; } if(jsonValue.ValueExists("ManagedResourceSummaryList")) { Array<JsonView> managedResourceSummaryListJsonList = jsonValue.GetArray("ManagedResourceSummaryList"); for(unsigned managedResourceSummaryListIndex = 0; managedResourceSummaryListIndex < managedResourceSummaryListJsonList.GetLength(); ++managedResourceSummaryListIndex) { m_managedResourceSummaryList.push_back(managedResourceSummaryListJsonList[managedResourceSummaryListIndex].AsObject()); } m_managedResourceSummaryListHasBeenSet = true; } return *this; } JsonValue LicenseConfiguration::Jsonize() const { JsonValue payload; if(m_licenseConfigurationIdHasBeenSet) { payload.WithString("LicenseConfigurationId", m_licenseConfigurationId); } if(m_licenseConfigurationArnHasBeenSet) { payload.WithString("LicenseConfigurationArn", m_licenseConfigurationArn); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_licenseCountingTypeHasBeenSet) { payload.WithString("LicenseCountingType", LicenseCountingTypeMapper::GetNameForLicenseCountingType(m_licenseCountingType)); } if(m_licenseRulesHasBeenSet) { Array<JsonValue> licenseRulesJsonList(m_licenseRules.size()); for(unsigned licenseRulesIndex = 0; licenseRulesIndex < licenseRulesJsonList.GetLength(); ++licenseRulesIndex) { licenseRulesJsonList[licenseRulesIndex].AsString(m_licenseRules[licenseRulesIndex]); } payload.WithArray("LicenseRules", std::move(licenseRulesJsonList)); } if(m_licenseCountHasBeenSet) { payload.WithInt64("LicenseCount", m_licenseCount); } if(m_licenseCountHardLimitHasBeenSet) { payload.WithBool("LicenseCountHardLimit", m_licenseCountHardLimit); } if(m_consumedLicensesHasBeenSet) { payload.WithInt64("ConsumedLicenses", m_consumedLicenses); } if(m_statusHasBeenSet) { payload.WithString("Status", m_status); } if(m_ownerAccountIdHasBeenSet) { payload.WithString("OwnerAccountId", m_ownerAccountId); } if(m_consumedLicenseSummaryListHasBeenSet) { Array<JsonValue> consumedLicenseSummaryListJsonList(m_consumedLicenseSummaryList.size()); for(unsigned consumedLicenseSummaryListIndex = 0; consumedLicenseSummaryListIndex < consumedLicenseSummaryListJsonList.GetLength(); ++consumedLicenseSummaryListIndex) { consumedLicenseSummaryListJsonList[consumedLicenseSummaryListIndex].AsObject(m_consumedLicenseSummaryList[consumedLicenseSummaryListIndex].Jsonize()); } payload.WithArray("ConsumedLicenseSummaryList", std::move(consumedLicenseSummaryListJsonList)); } if(m_managedResourceSummaryListHasBeenSet) { Array<JsonValue> managedResourceSummaryListJsonList(m_managedResourceSummaryList.size()); for(unsigned managedResourceSummaryListIndex = 0; managedResourceSummaryListIndex < managedResourceSummaryListJsonList.GetLength(); ++managedResourceSummaryListIndex) { managedResourceSummaryListJsonList[managedResourceSummaryListIndex].AsObject(m_managedResourceSummaryList[managedResourceSummaryListIndex].Jsonize()); } payload.WithArray("ManagedResourceSummaryList", std::move(managedResourceSummaryListJsonList)); } return payload; } } // namespace Model } // namespace LicenseManager } // namespace Aws
29.708185
170
0.778989
[ "model" ]
dc6b5ddd90a4fe98ed01c442d9a3a9a52a5a1cd8
2,351
cpp
C++
platform_bionic-android-vts-12.0_r2/tools/versioner/src/Utils.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
1
2019-05-04T02:30:08.000Z
2019-05-04T02:30:08.000Z
platform_bionic-android-vts-12.0_r2/tools/versioner/src/Utils.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
platform_bionic-android-vts-12.0_r2/tools/versioner/src/Utils.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2016 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. */ #include "Utils.h" #include <err.h> #include <fts.h> #include <string.h> #include <unistd.h> #include <sstream> #include <string> #include <vector> #include <android-base/strings.h> #include "DeclarationDatabase.h" std::string getWorkingDir() { char buf[PATH_MAX]; if (!getcwd(buf, sizeof(buf))) { err(1, "getcwd failed"); } return buf; } std::vector<std::string> collectHeaders(const std::string& directory, const std::unordered_set<std::string>& ignored_directories) { std::vector<std::string> headers; char* dir_argv[2] = { const_cast<char*>(directory.c_str()), nullptr }; std::unique_ptr<FTS, decltype(&fts_close)> fts( fts_open(dir_argv, FTS_LOGICAL | FTS_NOCHDIR, nullptr), fts_close); if (!fts) { err(1, "failed to open directory '%s'", directory.c_str()); } FTSENT* skipping = nullptr; while (FTSENT* ent = fts_read(fts.get())) { if (ent->fts_info & FTS_DP) { if (ent == skipping) { skipping = nullptr; } continue; } if (skipping != nullptr) { continue; } if (ent->fts_info & FTS_D) { if (ignored_directories.count(ent->fts_path) != 0) { // fts_read guarantees that `ent` is valid and okay to hold on to until // after it's returned with FTS_DP set. skipping = ent; } continue; } std::string path = ent->fts_path; if (!android::base::EndsWith(path, ".h")) { continue; } headers.push_back(std::move(path)); } return headers; } llvm::StringRef StripPrefix(llvm::StringRef string, llvm::StringRef prefix) { if (string.startswith(prefix)) { return string.drop_front(prefix.size()); } return string; }
25.835165
101
0.647384
[ "vector" ]
dc796d932585a1f5a8ac12f9b7f41697114e8b5c
60,307
cxx
C++
osprey/be/cg/MIPS/cgtarget.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/MIPS/cgtarget.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/MIPS/cgtarget.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2002, 2003, 2004 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ /* ==================================================================== * ==================================================================== * * Module: cgtarget.cxx * $Revision: 1.4 $ * $Date: 2006/06/13 02:11:08 $ * $Author: weitang $ * $Source: /depot/CVSROOT/javi/src/sw/cmplr/be/cg/MIPS/cgtarget.cxx,v $ * * Description: * * Support routines for target-specific code generator functionality. * * ==================================================================== * ==================================================================== */ #include <ctype.h> #include "defs.h" #include "util.h" #include "config.h" #include "config_targ_opt.h" #include "erglob.h" #include "tracing.h" #include "data_layout.h" #include "const.h" #include "wn.h" #include "opt_alias_interface.h" #include "opt_alias_mgr.h" #include "cgir.h" #include "cg.h" #include "void_list.h" #include "cg_dep_graph.h" #include "cg_spill.h" #include "cg_vector.h" #include "whirl2ops.h" #include "ti_errors.h" #include "ti_latency.h" #include "w2op.h" #include "cgexp.h" #include "cg_loop_recur.h" #include "targ_proc_properties.h" #include "ti_bundle.h" #include "hb_sched.h" #include "hb_hazards.h" #include "bb.h" #include "op.h" #include "op_list.h" #include "cg_grouping.h" #include "calls.h" #include "cgtarget.h" #include "calls.h" UINT32 CGTARG_branch_taken_penalty; BOOL CGTARG_branch_taken_penalty_overridden = FALSE; TOP CGTARG_Invert_Table[TOP_count+1]; TOP CGTARG_Immed_To_Reg_Table[TOP_count+1]; OPCODE CGTARG_Assoc_Base_Opr_Table[TOP_count]; mTOP CGTARG_Assoc_Base_Top_Table[TOP_count]; mTOP CGTARG_Assoc_Base_Fnc_Table[TOP_count]; mTOP CGTARG_Inter_RegClass_Copy_Table[ISA_REGISTER_CLASS_MAX+1][ISA_REGISTER_CLASS_MAX+1][2]; /* Trace flags: */ BOOL Trace_TD = FALSE; /* Target-dependent prep trace */ BOOL Trace_Eager = FALSE; /* gcm used to set this... */ extern BOOL Trace_Call_Exp; /* Trace call expansion, from cgexp */ UINT32 CGTARG_Mem_Ref_Bytes(const OP *memop) /* ----------------------------------------------------------------------- * Requires: OP_load(memop) || OP_store(memop) * See interface description. * ----------------------------------------------------------------------- */ { FmtAssert(OP_load(memop) || OP_store(memop), ("not a load or store")); TOP topcode = OP_code(memop); Is_True(topcode < TOP_count, ("unexpected topcode %d\n", topcode)); if (topcode < TOP_count) { switch (topcode) { case TOP_lb: case TOP_lbu: case TOP_sb: return 1; case TOP_lh: case TOP_lhu: case TOP_sh: return 2; #ifdef TARG_SL case TOP_ldw16: case TOP_stw16: case TOP_push16: case TOP_pop16: return 4; case TOP_ldub16_rs: return 1; case TOP_lduh16_rs: return 2; case TOP_c3_ld: case TOP_c3_st: case TOP_c3_dmac_a: case TOP_c3_dmacn_a: case TOP_c3_dmula_a: case TOP_c3_dmulan_a: case TOP_c3_mac_a: case TOP_c3_mac_ar: case TOP_c3_macn_a: case TOP_c3_macn_ar: case TOP_c3_mula_a: case TOP_c3_mula_ar: case TOP_c3_saadd_a: case TOP_c3_saaddh_a: case TOP_c3_saddha_a: case TOP_c3_samulh_a: case TOP_c3_sasub_a: case TOP_c3_sasubh_a: case TOP_c3_viterbi: case TOP_c3_trback: case TOP_c3_fft: case TOP_c3_fftld: case TOP_c3_fftst: // new C3 case TOP_C3_dmac_a: case TOP_C3_dmacn_a: case TOP_C3_dmula_a: case TOP_C3_dmulan_a: case TOP_C3_ffe: case TOP_C3_fftld: case TOP_C3_ld: case TOP_C3_fftst: case TOP_C3_st: case TOP_C3_mac_a: case TOP_C3_macn_a: case TOP_C3_mac_ar: case TOP_C3_macn_ar: case TOP_C3_mula_a: case TOP_C3_mula_ar: case TOP_C3_saadd_a: case TOP_C3_sasub_a: case TOP_C3_saaddh_a: case TOP_C3_sasubh_a: case TOP_C3_sadda_a: case TOP_C3_samulh_a: // end return 4; #endif #ifdef TARG_SL2 //ld_v: vbuf->rf case TOP_c2_ld_v_b_u: case TOP_c2_ld_v_b: case TOP_c2_ldi_v_b_u: case TOP_c2_ldi_v_b: return 16; case TOP_c2_ld_v_h: case TOP_c2_ldi_v_h: return 32; case TOP_c2_ld_v_w: case TOP_c2_ldi_v_w: return 64; case TOP_c2_ld_v_sw: case TOP_c2_ld_v_m_b_u: case TOP_c2_ld_v_m_b: case TOP_c2_ld_v_m_h: case TOP_c2_ld_v_m_w: case TOP_c2_ldi_v_m_b_u: case TOP_c2_ldi_v_m_b: case TOP_c2_ldi_v_m_h: case TOP_c2_ldi_v_m_w: return 32768; //ld_g: sbuf->gpr case TOP_c2_ld_s_h_u_p: case TOP_c2_ld_s_h_u: case TOP_c2_ld_s_h_p: case TOP_c2_ld_s_h: case TOP_c2_ldi_s_h_u: case TOP_c2_ldi_s_h: return 2; case TOP_c2_ld_s_w_p: case TOP_c2_ld_s_w: case TOP_c2_ldi_s_w: return 4; //ld_v2g: vbuf->gpr case TOP_c2_ld_v2g_b_u: case TOP_c2_ld_v2g_b: case TOP_c2_ldi_v2g_b_u: case TOP_c2_ldi_v2g_b: return 1; case TOP_c2_ld_v2g_h_u: case TOP_c2_ld_v2g_h: case TOP_c2_ldi_v2g_h_u: case TOP_c2_ldi_v2g_h: return 17; case TOP_c2_ld_v2g_w: case TOP_c2_ldi_v2g_w: return 49; //ld_c_imm: sbuf->cr case TOP_c2_ldi_c: return 4; //st_v: rf->vbuf case TOP_c2_st_v_b: case TOP_c2_sti_v_b: return 16; case TOP_c2_st_v_h: case TOP_c2_sti_v_h: return 32; case TOP_c2_st_v_w: case TOP_c2_sti_v_w: return 64; case TOP_c2_st_v_m_b: case TOP_c2_st_v_m_h: case TOP_c2_st_v_m_w: case TOP_c2_sti_v_m_b: case TOP_c2_sti_v_m_h: case TOP_c2_sti_v_m_w: return 32768; //st_g: gpr->sbuf case TOP_c2_st_s_h: case TOP_c2_st_s_h_p: case TOP_c2_sti_s_h: return 2; case TOP_c2_st_s_w: case TOP_c2_st_s_w_p: case TOP_c2_sti_s_w: return 4; case TOP_c2_sti_c: return 4; //st_g2v: gpr->vbuf case TOP_c2_st_g2v_b: case TOP_c2_sti_g2v_b: return 1; case TOP_c2_st_g2v_h: case TOP_c2_sti_g2v_h: return 17; case TOP_c2_st_g2v_w: case TOP_c2_sti_g2v_w: return 49; #endif case TOP_lw: case TOP_ll: case TOP_lwu: case TOP_lwc1: case TOP_lwxc1: case TOP_sw: case TOP_sc: case TOP_swc1: case TOP_swxc1: return 4; case TOP_ld: case TOP_lld: case TOP_ldc1: case TOP_ldxc1: case TOP_sd: case TOP_scd: case TOP_sdc1: case TOP_sdxc1: return 8; } } return 0; } /* ==================================================================== * * CGTARG_Is_OP_Speculative * * See interface description * * ==================================================================== */ BOOL CGTARG_Is_OP_Speculative(OP *op) { if (!OP_load(op)) return FALSE; // speculative and advanced loads are safe to speculate. if (CGTARG_Is_OP_Advanced_Load(op) || CGTARG_Is_OP_Speculative_Load(op)) return TRUE; return FALSE; } /* ==================================================================== * * CGTARG_Perform_THR_Code_Generation * * See interface description * * ==================================================================== */ void CGTARG_Perform_THR_Code_Generation (OP *load_op, OP *chk_load, THR_TYPE type) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_ARC_Sched_Latency * * See interface description * * ==================================================================== */ INT CGTARG_ARC_Sched_Latency( ARC *arc ) { if ( ARC_kind(arc) == CG_DEP_PREBR && PROC_has_same_cycle_branch_shadow() ) return 0; else return ARC_latency(arc); } /* ==================================================================== * * CGTARG_Bundle_Slot_Available * * See interface description * * ==================================================================== */ BOOL CGTARG_Bundle_Slot_Available(TI_BUNDLE *bundle, OP *op, INT slot, ISA_EXEC_UNIT_PROPERTY *prop, BOOL stop_bit_reqd, const CG_GROUPING *grouping) { return FALSE; } /* ==================================================================== * * CGTARG_Bundle_Stop_Bit_Available * * See interface description * * ==================================================================== */ BOOL CGTARG_Bundle_Stop_Bit_Available(TI_BUNDLE *bundle, INT slot) { // Return TRUE the stop-bit is already set. if (TI_BUNDLE_stop_bit(bundle, slot)) return TRUE; return TI_BUNDLE_Stop_Bit_Available(bundle, slot); } /* ==================================================================== * * CGTARG_Handle_Bundle_Hazard * * See interface description * * ==================================================================== */ void CGTARG_Handle_Bundle_Hazard (OP *op, TI_BUNDLE *bundle, VECTOR *bundle_vector, BOOL can_fill, INT slot_pos, INT max_pos, BOOL stop_bit_reqd, ISA_EXEC_UNIT_PROPERTY prop) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Handle_Errata_Hazard * * See interface description * * ==================================================================== */ void CGTARG_Handle_Errata_Hazard (OP *op, INT erratnum, INT ops_to_check) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * Reduce_Fraction * * Half hearted attempt to reduce a fraction. If we don't succeed * the only problem will be that we might round incorrectly on a * instruction rate. * * The algorithm is to first try the denominator as a factor and * then a few small primes. * * ==================================================================== */ static void Reduce_Fraction(INT frac[2]) { INT i; static const INT primes[] = {2, 3, 5, 7, 11, 13}; INT n = frac[0]; INT d = frac[1]; INT p = d; if (d < -1 || d > 1) { for (i = sizeof(primes) / sizeof(primes[0]); ; p = primes[--i]) { while (n % p == 0 && d % p == 0) { n = n / p; d = d / p; } if (i == 0) break; } } frac[0] = n; frac[1] = d; } /* ==================================================================== * * Harmonic_Mean * * Compute the harmonic weighted mean of two rates as follows: * * 1 a b * ---- = ( ----- * a_rate ) + ( ----- * b_rate ) * mean a + b a + b * * Where: * * "a" is the number of operations of class "a" * "b" is the number of operations of class "b" * * ==================================================================== */ static void Harmonic_Mean( INT mean[2], INT a, const INT a_rate[2], INT b, const INT b_rate[2] ) { if (a == 0) { mean[0] = b_rate[0]; mean[1] = b_rate[1]; } else if (b == 0) { mean[0] = a_rate[0]; mean[1] = a_rate[1]; } else { mean[1] = (a * a_rate[1] * b_rate[0]) + (b * b_rate[1] * a_rate[0]); mean[0] = (a + b) * a_rate[0] * b_rate[0]; Reduce_Fraction(mean); } } /* ==================================================================== * * CGTARG_Peak_Rate * * See interface description * * ==================================================================== */ void CGTARG_Peak_Rate( PEAK_RATE_CLASS prc, PRC_INFO *info, INT ratio[2] ) { ratio[0] = 1; ratio[1] = 1; switch (prc) { case PRC_INST: ratio[0] = 4; break; case PRC_MADD: case PRC_MEMREF: ratio[0] = 2; break; case PRC_FLOP: case PRC_FADD: case PRC_FMUL: ratio[0] = 2; break; case PRC_IOP: ratio[0] = 2; break; default: ratio[0] = 2; break; } } /* ======================================================================= * * Plural * * Return "s" if i != 1, "" otherwise. Used to get the number of nouns * right when printing. * * ======================================================================= */ #define Plural(i) ((i) != 1 ? "s" : "") /* ======================================================================= * * Percent_Of_Peak * * Compute the percentage of peak instructions executed. Both the * actual number of instructions executed and the peak attainable * are expressed as a fraction of insts/cycle. * * ======================================================================= */ static INT Percent_Of_Peak(INT numer, INT denom, INT peak[2]) { if (numer == 0) return 0; return (numer * peak[1] * 100) / ((denom * peak[0]) + peak[1] - 1); } /* ======================================================================= * * CGTARG_Print_PRC_INFO * * Print statistics for the PRC_INFO to a 'file'. * * ======================================================================= */ void CGTARG_Print_PRC_INFO( FILE *file, PRC_INFO *info, INT32 ii, const char *prefix, const char *suffix ) { char *s; INT madds_per_cycle[2]; INT memrefs_per_cycle[2]; INT flops_per_cycle[2]; INT fadds_per_cycle[2]; INT fmuls_per_cycle[2]; INT iops_per_cycle[2]; INT insts_per_cycle[2]; INT insts = info->refs[PRC_INST]; INT memrefs = info->refs[PRC_MEMREF]; INT flops = info->refs[PRC_FLOP]; INT madds = info->refs[PRC_MADD]; INT fadds = info->refs[PRC_FADD]; INT fmuls = info->refs[PRC_FMUL]; INT iops = info->refs[PRC_IOP]; CGTARG_Peak_Rate(PRC_INST, info, insts_per_cycle); CGTARG_Peak_Rate(PRC_MEMREF, info, memrefs_per_cycle); CGTARG_Peak_Rate(PRC_FLOP, info, flops_per_cycle); CGTARG_Peak_Rate(PRC_MADD, info, madds_per_cycle); CGTARG_Peak_Rate(PRC_FADD, info, fadds_per_cycle); CGTARG_Peak_Rate(PRC_FMUL, info, fmuls_per_cycle); CGTARG_Peak_Rate(PRC_IOP, info, iops_per_cycle); if (flops != 0) { BOOL unbalanced_fpu = FALSE; if ( madds_per_cycle[0] != 0 ) { fprintf(file,"%s%5d flop%1s (%3d%% of peak) (madds count as 2)%s" "%s%5d flop%1s (%3d%% of peak) (madds count as 1)%s" "%s%5d madd%1s (%3d%% of peak)%s", prefix, flops + madds, Plural(flops + madds), Percent_Of_Peak(flops + madds, ii * 2, madds_per_cycle), suffix, prefix, flops, Plural(flops), Percent_Of_Peak(flops, ii, flops_per_cycle), suffix, prefix, madds, Plural(madds), Percent_Of_Peak(madds, ii, madds_per_cycle), suffix); } else { fprintf(file,"%s%5d flop%1s (%3d%% of peak)%s", prefix, flops, Plural(flops), Percent_Of_Peak(flops, ii, flops_per_cycle), suffix); } if ( unbalanced_fpu ) { INT fmuls2_per_cycle[2]; /* combined fmul/madd peak rate */ INT fadds2_per_cycle[2]; /* combined fadd/madd peak rate */ INT fadds2 = fadds + madds; INT fmuls2 = fmuls + madds; Harmonic_Mean(fmuls2_per_cycle, fmuls, fmuls_per_cycle, madds, madds_per_cycle); Harmonic_Mean(fadds2_per_cycle, fadds, fadds_per_cycle, madds, madds_per_cycle); fprintf(file,"%s%5d fmul%1s (%3d%% of peak)%s%s", prefix, fmuls2, Plural(fmuls2), Percent_Of_Peak(fmuls2, ii, fmuls2_per_cycle), madds_per_cycle[0] ? " (madds count as 1)" : "", suffix); fprintf(file,"%s%5d fadd%1s (%3d%% of peak)%s%s", prefix, fadds2, Plural(fadds2), Percent_Of_Peak(fadds2, ii, fadds2_per_cycle), madds_per_cycle[0] ? " (madds count as 1)" : "", suffix); } } s = ""; if (FALSE) { iops += memrefs; s = " (mem refs included)"; } fprintf(file,"%s%5d mem ref%1s (%3d%% of peak)%s" "%s%5d integer op%1s (%3d%% of peak)%s%s" "%s%5d instruction%1s (%3d%% of peak)%s", prefix, memrefs, Plural(memrefs), Percent_Of_Peak(memrefs, ii, memrefs_per_cycle), suffix, prefix, iops, Plural(iops), Percent_Of_Peak(iops, ii, iops_per_cycle), s, suffix, prefix, insts, Plural(insts), Percent_Of_Peak(insts, ii, insts_per_cycle), suffix); } /* ======================================================================= * * CGTARG_Compute_PRC_INFO * * Compute some basic information about the given 'bb'. * * ======================================================================= */ void CGTARG_Compute_PRC_INFO( BB *bb, PRC_INFO *info ) { OP *op; bzero (info, sizeof (PRC_INFO)); for ( op = BB_first_op(bb); op != NULL; op = OP_next(op) ) { INT num_insts = OP_Real_Ops (op); if (num_insts == 0) continue; info->refs[PRC_INST] += num_insts; if ( OP_flop(op) ) { BOOL is_single = (OP_result_size(op,0) == 32); ++info->refs[PRC_FLOP]; info->refs[PRC_FLOP_S] += is_single; if (OP_madd(op)) { ++info->refs[PRC_MADD]; info->refs[PRC_MADD_S] += is_single; } else if (OP_fadd(op) || OP_fsub(op)) { ++info->refs[PRC_FADD]; info->refs[PRC_FADD_S] += is_single; } else if (OP_fmul(op)) { ++info->refs[PRC_FMUL]; info->refs[PRC_FMUL_S] += is_single; } } else if (OP_memory(op)) ++info->refs[PRC_MEMREF]; else { INT k; /* Conditional moves and m[tf]c1 are not tagged as flops. * We certainly don't want to call them integer ops, so assume * anything that uses FP regs isn't an integer instruction. */ if (OP_has_result(op) && TN_is_float(OP_result(op,0))) goto not_iop; for (k = 0; k < OP_opnds(op); k++) { if (TN_is_float(OP_opnd(op,k))) goto not_iop; } info->refs[PRC_IOP] += num_insts; not_iop: ; } } } /* ==================================================================== * * CG_TARG_Branch_Info * * See interface description * * ==================================================================== */ void CGTARG_Branch_Info ( const OP *op, INT *tfirst, /* Which operand is the first target? */ INT *tcount ) /* How many target operands are there? */ { INT i; TN *tn; /* Initialize results: */ *tfirst = -1; *tcount = 0; /* Find the first target: */ for ( i = 0; ; i++ ) { if ( i >= OP_opnds(op) ) return; tn = OP_opnd(op,i); if ( tn != NULL && TN_is_label(tn) ) break; } *tfirst = i; /* Count the targets: */ *tcount = 1; for ( i++; i < OP_opnds(op); i++ ) { tn = OP_opnd(op,i); if ( tn == NULL || ! TN_is_label(tn) ) return; (*tcount)++; } return; } /* ==================================================================== * * CGTARG_Can_Be_Speculative * * See interface description * * ==================================================================== */ BOOL CGTARG_Can_Be_Speculative( OP *op ) { WN *wn; /* not allowed to speculate anything. */ if (Eager_Level == EAGER_NONE) return FALSE; /* don't speculate volatile memory references. */ if (OP_volatile(op)) return FALSE; if (TOP_Can_Be_Speculative(OP_code(op))) return TRUE; if (!OP_load(op)) return FALSE; /* Try to identify simple scalar loads than can be safely speculated: * a) read only loads (literals, GOT-loads, etc.) * b) load of a fixed variable (directly referenced) * c) load of a fixed variable (base address is constant or * known to be in bounds) * d) speculative, advanced and advanced-speculative loads are safe. */ /* a) read only loads (literals, GOT-loads, etc.) */ if (OP_no_alias(op)) goto scalar_load; /* b) load of a fixed variable (directly referenced); this * includes spill-restores. * b') exclude cases of direct loads of weak symbols (#622949). */ if (TN_is_symbol(OP_opnd(op, 1)) && !ST_is_weak_symbol(TN_var(OP_opnd(op, 1)))) goto scalar_load; /* c) load of a fixed variable (base address is constant or * known to be in bounds), comment out the rematerizable bit check * since it doesn;t guarantee safeness all the time. */ if (/* TN_is_rematerializable(OP_opnd(op, 0)) || */ ( (wn = Get_WN_From_Memory_OP(op)) && Alias_Manager->Safe_to_speculate(wn))) goto scalar_load; /* d) speculative, advanced, speculative-advanced loads are safe to * speculate. */ if (CGTARG_Is_OP_Speculative(op)) goto scalar_load; /* If we got to here, we couldn't convince ourself that we have * a scalar load -- no speculation this time... */ return FALSE; /* We now know we have a scalar load of some form. Determine if they * are allowed to be speculated. */ scalar_load: return TRUE; } /* ==================================================================== * * CGTARG_Is_OP_Speculative_Load * * See interface description * * ==================================================================== */ BOOL CGTARG_Is_OP_Speculative_Load( OP *memop ) { return FALSE; } /* ==================================================================== * * CGTARG_Is_OP_Advanced_Load * * See interface description * * ==================================================================== */ BOOL CGTARG_Is_OP_Advanced_Load( OP *memop ) { return FALSE; } /* ==================================================================== * * CGTARG_Is_OP_Check_Load * * See interface description * * ==================================================================== */ BOOL CGTARG_Is_OP_Check_Load( OP *memop ) { return FALSE; } /* ==================================================================== * * CGTARG_OP_Defs_TN * CGTARG_OP_Refs_TN * * See interface description * * ==================================================================== */ BOOL CGTARG_OP_Defs_TN( OP *op, TN *tn ) { return FALSE; } BOOL CGTARG_OP_Refs_TN( OP *op, TN *tn ) { return FALSE; } /* ==================================================================== * * CGTARG_Interference implementation starts here * * ==================================================================== */ static MEM_POOL interference_pool; static VOID_LIST** writing; /* writing[i] is a list of live ranges being written into registers in cycle i */ static BOOL is_loop; /* Are we working on a loop? */ static INT32 assumed_longest_latency = 40; /* We need to allocate <writing> to be somewhat longer than the number of cycles in the schedule in order to accommodate writes initiated near the end of the schedule. We'll check and grow this number as necessary. */ static INT32 cycle_count; /* Number of cycles in the schedule under consideration. */ static void (*make_interference)(void*,void*); /* Client's interference call back. */ /* ==================================================================== * * Increase_Assumed_Longest_Latency * * We need to increase our assumptions about the longest latency operation * in our target. Also reallocate <writing>. * * ==================================================================== */ static void Increase_Assumed_Longest_Latency(INT32 new_longest_latency ) { DevWarn("Assumed longest latency should be at least %d", new_longest_latency); writing = TYPE_MEM_POOL_REALLOC_N(VOID_LIST*,&interference_pool,writing, cycle_count + assumed_longest_latency, cycle_count + new_longest_latency); assumed_longest_latency = new_longest_latency; } /* ==================================================================== * * CGTARG_Interference_Required * * See interface description * * ==================================================================== */ BOOL CGTARG_Interference_Required(void) { return FALSE; } /* ==================================================================== * * CGTARG_Interference_Initialize * * See interface description * * ==================================================================== */ void CGTARG_Interference_Initialize( INT32 cycle_count_local, BOOL is_loop_local, void (*make_interference_local)(void*,void*) ) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Result_Live_Range * * See interface description * * ==================================================================== */ void CGTARG_Result_Live_Range( void* lrange, OP* op, INT32 offset ) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Operand_Live_Range * * See interface description * * ==================================================================== */ void CGTARG_Operand_Live_Range( void* lrange, INT opnd, OP* op, INT32 offset ) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Interference_Finalize * * See interface description * * ==================================================================== */ void CGTARG_Interference_Finalize(void) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Preg_Register_And_Class * * See interface description * * ==================================================================== */ BOOL CGTARG_Preg_Register_And_Class( WN_OFFSET preg, ISA_REGISTER_CLASS *p_rclass, REGISTER *p_reg ) { ISA_REGISTER_CLASS rclass; INT regnum; /* Get the target register number and class associated with the * preg, if there is one that is. */ if (!Preg_Is_Dedicated(preg)) return FALSE; if (!Preg_Offset_Is_Int(preg) && !Preg_Offset_Is_Float(preg) && !Preg_Offset_Is_Fcc(preg)) return FALSE; /* Get the target register number and class associated with the * * preg, if there is one that is. */ if (Preg_Offset_Is_Int(preg)) { regnum = preg - (Int_Preg_Min_Offset - 1); rclass = ISA_REGISTER_CLASS_integer; } else if (Preg_Offset_Is_Float(preg)) { regnum = preg - Float_Preg_Min_Offset; rclass = ISA_REGISTER_CLASS_float; } else if (Preg_Offset_Is_Fcc(preg)) { regnum = preg - Fcc_Preg_Min_Offset; rclass = ISA_REGISTER_CLASS_fcc; } else if (preg == 0) { regnum = 0; rclass = ISA_REGISTER_CLASS_integer; } else { return FALSE; } /* Find the CG register for the target register and class. */ for ( REGISTER reg = REGISTER_MIN; reg <= REGISTER_CLASS_last_register(rclass); reg++ ) { if ( REGISTER_machine_id(rclass,reg) == regnum ) { *p_reg = reg; *p_rclass = rclass; return TRUE; } } FmtAssert(FALSE, ("failed to map preg %d", preg)); /*NOTREACHED*/ } /* ==================================================================== * * CGTARG_Compute_Branch_Parameters * * See interface description * * ==================================================================== */ void CGTARG_Compute_Branch_Parameters(INT32 *mispredict, INT32 *fixed, INT32 *brtaken, double *factor) { *mispredict = 0; *fixed = 0; *brtaken = 0; *factor = 0.0; #ifdef TARG_SL if (Is_Target_Sl1_pcore() || Is_Target_Sl1_dsp()) { *mispredict= 7; *fixed= 1; *brtaken= 1; *factor = 1.0; } else if ( Is_Target_Sl2_pcore() || Is_Target_Sl2_mcore()) { *mispredict= 3; *fixed= 1; *brtaken= 1; *factor = 1.0; } #endif /* * override for command line options * -CG:mispredicted_branch=N * -CG:mispredicted_factor=N */ if (CG_branch_mispredict_penalty >= 0) *mispredict= CG_branch_mispredict_penalty ; if (CG_branch_mispredict_factor >= 0) *factor= CG_branch_mispredict_factor * (.01); } /* ==================================================================== * * CGTARG_Can_Change_To_Brlikely * * See interface description * * ==================================================================== */ BOOL CGTARG_Can_Change_To_Brlikely(OP *xfer_op, TOP *new_opcode) { return FALSE; } /* ==================================================================== * * CGTARG_Is_Long_Latency * * See interface description * * ==================================================================== */ BOOL CGTARG_Is_Long_Latency(TOP op) { return (TI_LATENCY_Result_Available_Cycle(op, 0) - TI_LATENCY_Operand_Access_Cycle(op, 0)) > 2; } /* ==================================================================== * * CGTARG_Analyze_Branch * * See interface description * * ==================================================================== */ VARIANT CGTARG_Analyze_Branch( OP *br, TN **tn1, TN **tn2) { INT variant; /* Branch operands are usually number 0 and 1. Where something different is used, we override below. */ *tn1 = OP_opnd(br, 0); *tn2 = OP_opnd(br, 1); switch (OP_code(br)) { case TOP_beq: variant = V_BR_I4EQ; break; case TOP_bne: variant = V_BR_I4NE; break; case TOP_bgez: variant = V_BR_I4GE; *tn2 = Gen_Literal_TN(0,4); break; case TOP_bltz: variant = V_BR_I4LT; *tn2 = Gen_Literal_TN(0,4); break; case TOP_bgtz: variant = V_BR_I4GT; *tn2 = Gen_Literal_TN(0,4); break; case TOP_blez: variant = V_BR_I4LE; *tn2 = Gen_Literal_TN(0,4); break; case TOP_bc1t: variant = V_BR_F_TRUE; *tn2 = NULL; break; case TOP_bc1f: variant = V_BR_F_FALSE; *tn2 = NULL; break; default: variant = V_BR_NONE; *tn1 = NULL; *tn2 = NULL; Is_True( !OP_cond( br ), ("unexpected conditional branch %d\n", OP_code(br) ) ); break; } return variant; } /* ==================================================================== * * CGTARG_Analyze_Compare * * See interface description * * ==================================================================== */ VARIANT CGTARG_Analyze_Compare( OP *br, TN **tn1, TN **tn2, OP **compare_op) { TN *cond_tn1; TN *cond_tn2; /* Classify the condition based on the branch instruction. */ INT variant = CGTARG_Analyze_Branch(br, &cond_tn1, &cond_tn2); /* Once we have varients for 'bf' and 'bt' (and possibly some others), we can attempt to find the comparison. For now, none of the branches have associated comparisons. */ *compare_op = NULL; *tn1 = cond_tn1; *tn2 = cond_tn2; return variant; } /* ==================================================================== * * CGTARG_Equivalent_Nonindex_Memory_Op * * See interface description * * ==================================================================== */ TOP CGTARG_Equiv_Nonindex_Memory_Op ( OP *op ) { return TOP_UNDEFINED; } /* ==================================================================== * * CGTARG_Which_OP_Select * * See interface description * * ==================================================================== */ TOP CGTARG_Which_OP_Select ( UINT16 bit_size, BOOL is_float, BOOL is_fcc ) { FmtAssert( FALSE, ( "CGTARG_Which_OP_Select: Unsupported Target") ); return TOP_UNDEFINED; } /* ==================================================================== * * Is_OP_fp_op1 * * FP_OP1 = {sfmac, sfmisc, xma, xmpy, fmac, cvt.fx, fmisc} * * ==================================================================== */ static BOOL Is_OP_fp_op1(OP *op) { return FALSE; } /* ==================================================================== * * Insert_Stop_Bits * * ==================================================================== */ void Insert_Stop_Bits(BB *bb) { } /* ==================================================================== * * CGTARG_Special_Min_II * * See interface description * * ==================================================================== */ INT32 CGTARG_Special_Min_II(BB* loop_body, BOOL trace) { return 0; } /* ==================================================================== * * Hardware_Workarounds * * Placeholder for all Hardware workarounds. * * ==================================================================== */ void Hardware_Workarounds(void) { } /* ==================================================================== * * CGTARG_Initialize * * See interface description * * ==================================================================== */ void CGTARG_Initialize(void) { INT32 i; /* Init all table entries to TOP_UNDEFINED. */ for(i = 0; i <= TOP_count; ++i) { CGTARG_Invert_Table[i] = TOP_UNDEFINED; CGTARG_Immed_To_Reg_Table[i] = TOP_UNDEFINED; } for (i = 0; i <= ISA_REGISTER_CLASS_MAX; ++i) { INT j; for (j = 0; j <= ISA_REGISTER_CLASS_MAX; ++j) { CGTARG_Inter_RegClass_Copy_Table[i][j][FALSE] = TOP_UNDEFINED; CGTARG_Inter_RegClass_Copy_Table[i][j][TRUE] = TOP_UNDEFINED; } } /* Init table for CGTARG_Invert: */ CGTARG_Invert_Table[TOP_add_s] = TOP_sub_s; CGTARG_Invert_Table[TOP_add_d] = TOP_sub_d; CGTARG_Invert_Table[TOP_madd_s] = TOP_nmadd_s; CGTARG_Invert_Table[TOP_madd_d] = TOP_nmadd_d; CGTARG_Invert_Table[TOP_add] = TOP_sub; CGTARG_Invert_Table[TOP_addu] = TOP_subu; CGTARG_Invert_Table[TOP_dadd] = TOP_dsub; CGTARG_Invert_Table[TOP_daddu] = TOP_dsubu; CGTARG_Invert_Table[TOP_sub_s] = TOP_add_s; CGTARG_Invert_Table[TOP_sub_d] = TOP_add_d; CGTARG_Invert_Table[TOP_nmadd_s] = TOP_madd_s; CGTARG_Invert_Table[TOP_nmadd_d] = TOP_madd_d; CGTARG_Invert_Table[TOP_sub] = TOP_add; CGTARG_Invert_Table[TOP_subu] = TOP_addu; CGTARG_Invert_Table[TOP_dsub] = TOP_dadd; CGTARG_Invert_Table[TOP_dsubu] = TOP_daddu; CGTARG_Invert_Table[TOP_or] = TOP_nor; CGTARG_Invert_Table[TOP_nor] = TOP_or; CGTARG_Invert_Table[TOP_movf] = TOP_movt; CGTARG_Invert_Table[TOP_movt] = TOP_movf; CGTARG_Invert_Table[TOP_movz] = TOP_movn; CGTARG_Invert_Table[TOP_movn] = TOP_movz; CGTARG_Invert_Table[TOP_movf_s] = TOP_movt_s; CGTARG_Invert_Table[TOP_movt_s] = TOP_movf_s; CGTARG_Invert_Table[TOP_movz_s] = TOP_movn_s; CGTARG_Invert_Table[TOP_movn_s] = TOP_movz_s; CGTARG_Invert_Table[TOP_movf_d] = TOP_movt_d; CGTARG_Invert_Table[TOP_movt_d] = TOP_movf_d; CGTARG_Invert_Table[TOP_movz_d] = TOP_movn_d; CGTARG_Invert_Table[TOP_movn_d] = TOP_movz_d; CGTARG_Invert_Table[TOP_beq] = TOP_bne; CGTARG_Invert_Table[TOP_bne] = TOP_beq; CGTARG_Invert_Table[TOP_bgez] = TOP_bltz; CGTARG_Invert_Table[TOP_bgtz] = TOP_blez; CGTARG_Invert_Table[TOP_bltz] = TOP_bgez; CGTARG_Invert_Table[TOP_blez] = TOP_bgtz; CGTARG_Invert_Table[TOP_bgezal] = TOP_bltzal; CGTARG_Invert_Table[TOP_bltzal] = TOP_bgezal; CGTARG_Invert_Table[TOP_bc1f] = TOP_bc1t; CGTARG_Invert_Table[TOP_bc1t] = TOP_bc1f; CGTARG_Invert_Table[TOP_c_f_s] = TOP_c_t_s; CGTARG_Invert_Table[TOP_c_f_d] = TOP_c_t_d; CGTARG_Invert_Table[TOP_c_t_s] = TOP_c_f_s; CGTARG_Invert_Table[TOP_c_t_d] = TOP_c_f_d; CGTARG_Invert_Table[TOP_c_un_s] = TOP_c_or_s; CGTARG_Invert_Table[TOP_c_un_d] = TOP_c_or_d; CGTARG_Invert_Table[TOP_c_or_s] = TOP_c_un_s; CGTARG_Invert_Table[TOP_c_or_d] = TOP_c_un_d; CGTARG_Invert_Table[TOP_c_eq_s] = TOP_c_neq_s; CGTARG_Invert_Table[TOP_c_eq_d] = TOP_c_neq_d; CGTARG_Invert_Table[TOP_c_neq_s] = TOP_c_eq_s; CGTARG_Invert_Table[TOP_c_neq_d] = TOP_c_eq_d; CGTARG_Invert_Table[TOP_c_ueq_s] = TOP_c_olg_s; CGTARG_Invert_Table[TOP_c_ueq_d] = TOP_c_olg_d; CGTARG_Invert_Table[TOP_c_olg_s] = TOP_c_ueq_s; CGTARG_Invert_Table[TOP_c_olg_d] = TOP_c_ueq_d; CGTARG_Invert_Table[TOP_c_olt_s] = TOP_c_uge_s; CGTARG_Invert_Table[TOP_c_olt_d] = TOP_c_uge_d; CGTARG_Invert_Table[TOP_c_uge_s] = TOP_c_olt_s; CGTARG_Invert_Table[TOP_c_uge_d] = TOP_c_olt_d; CGTARG_Invert_Table[TOP_c_ult_s] = TOP_c_oge_s; CGTARG_Invert_Table[TOP_c_ult_d] = TOP_c_oge_d; CGTARG_Invert_Table[TOP_c_oge_s] = TOP_c_ult_s; CGTARG_Invert_Table[TOP_c_oge_d] = TOP_c_ult_d; CGTARG_Invert_Table[TOP_c_ole_s] = TOP_c_ugt_s; CGTARG_Invert_Table[TOP_c_ole_d] = TOP_c_ugt_d; CGTARG_Invert_Table[TOP_c_ugt_s] = TOP_c_ole_s; CGTARG_Invert_Table[TOP_c_ugt_d] = TOP_c_ole_d; CGTARG_Invert_Table[TOP_c_ule_s] = TOP_c_ogt_s; CGTARG_Invert_Table[TOP_c_ule_d] = TOP_c_ogt_d; CGTARG_Invert_Table[TOP_c_ogt_s] = TOP_c_ule_s; CGTARG_Invert_Table[TOP_c_ogt_d] = TOP_c_ule_d; CGTARG_Invert_Table[TOP_c_sf_s] = TOP_c_st_s; CGTARG_Invert_Table[TOP_c_sf_d] = TOP_c_st_d; CGTARG_Invert_Table[TOP_c_st_s] = TOP_c_sf_s; CGTARG_Invert_Table[TOP_c_st_d] = TOP_c_sf_d; CGTARG_Invert_Table[TOP_c_ngle_s] = TOP_c_gle_s; CGTARG_Invert_Table[TOP_c_ngle_d] = TOP_c_gle_d; CGTARG_Invert_Table[TOP_c_gle_s] = TOP_c_ngle_s; CGTARG_Invert_Table[TOP_c_gle_d] = TOP_c_ngle_d; CGTARG_Invert_Table[TOP_c_seq_s] = TOP_c_sne_s; CGTARG_Invert_Table[TOP_c_seq_d] = TOP_c_sne_d; CGTARG_Invert_Table[TOP_c_sne_s] = TOP_c_seq_s; CGTARG_Invert_Table[TOP_c_sne_d] = TOP_c_seq_d; CGTARG_Invert_Table[TOP_c_ngl_s] = TOP_c_gl_s; CGTARG_Invert_Table[TOP_c_ngl_d] = TOP_c_gl_d; CGTARG_Invert_Table[TOP_c_gl_s] = TOP_c_ngl_s; CGTARG_Invert_Table[TOP_c_gl_d] = TOP_c_ngl_d; CGTARG_Invert_Table[TOP_c_nlt_s] = TOP_c_lt_s; CGTARG_Invert_Table[TOP_c_nlt_d] = TOP_c_lt_d; CGTARG_Invert_Table[TOP_c_lt_s] = TOP_c_nlt_s; CGTARG_Invert_Table[TOP_c_lt_d] = TOP_c_nlt_d; CGTARG_Invert_Table[TOP_c_nge_s] = TOP_c_ge_s; CGTARG_Invert_Table[TOP_c_nge_d] = TOP_c_ge_d; CGTARG_Invert_Table[TOP_c_ge_s] = TOP_c_nge_s; CGTARG_Invert_Table[TOP_c_ge_d] = TOP_c_nge_d; CGTARG_Invert_Table[TOP_c_le_s] = TOP_c_nle_s; CGTARG_Invert_Table[TOP_c_le_d] = TOP_c_nle_d; CGTARG_Invert_Table[TOP_c_nle_s] = TOP_c_le_s; CGTARG_Invert_Table[TOP_c_nle_d] = TOP_c_le_d; CGTARG_Invert_Table[TOP_c_ngt_s] = TOP_c_gt_s; CGTARG_Invert_Table[TOP_c_ngt_d] = TOP_c_gt_d; CGTARG_Invert_Table[TOP_c_gt_s] = TOP_c_ngt_s; CGTARG_Invert_Table[TOP_c_gt_d] = TOP_c_ngt_d; CGTARG_Invert_Table[TOP_teq] = TOP_tne; CGTARG_Invert_Table[TOP_tne] = TOP_teq; CGTARG_Invert_Table[TOP_tge] = TOP_tlt; CGTARG_Invert_Table[TOP_tlt] = TOP_tge; CGTARG_Invert_Table[TOP_tgeu] = TOP_tltu; CGTARG_Invert_Table[TOP_tltu] = TOP_tgeu; CGTARG_Invert_Table[TOP_teqi] = TOP_tnei; CGTARG_Invert_Table[TOP_tnei] = TOP_teqi; CGTARG_Invert_Table[TOP_tgei] = TOP_tlti; CGTARG_Invert_Table[TOP_tlti] = TOP_tgei; CGTARG_Invert_Table[TOP_tgeiu] = TOP_tltiu; CGTARG_Invert_Table[TOP_tltiu] = TOP_tgeiu; /* Init table for CGTARG_Immed_To_Reg: */ CGTARG_Immed_To_Reg_Table[TOP_addi] = TOP_add; CGTARG_Immed_To_Reg_Table[TOP_daddi] = TOP_dadd; CGTARG_Immed_To_Reg_Table[TOP_addiu] = TOP_addu; CGTARG_Immed_To_Reg_Table[TOP_daddiu] = TOP_daddu; CGTARG_Immed_To_Reg_Table[TOP_slti] = TOP_slt; CGTARG_Immed_To_Reg_Table[TOP_sltiu] = TOP_sltu; CGTARG_Immed_To_Reg_Table[TOP_andi] = TOP_and; CGTARG_Immed_To_Reg_Table[TOP_ori] = TOP_or; CGTARG_Immed_To_Reg_Table[TOP_xori] = TOP_xor; CGTARG_Immed_To_Reg_Table[TOP_teqi] = TOP_teq; CGTARG_Immed_To_Reg_Table[TOP_tgei] = TOP_tge; CGTARG_Immed_To_Reg_Table[TOP_tgeiu] = TOP_tgeu; CGTARG_Immed_To_Reg_Table[TOP_tlti] = TOP_tlt; CGTARG_Immed_To_Reg_Table[TOP_tltiu] = TOP_tltu; CGTARG_Immed_To_Reg_Table[TOP_tnei] = TOP_tne; /* Init table for CGTARG_Inter_RegClass_Copy_Table: */ CGTARG_Inter_RegClass_Copy_Table[ISA_REGISTER_CLASS_float] [ISA_REGISTER_CLASS_integer] [FALSE] = TOP_mfc1; CGTARG_Inter_RegClass_Copy_Table[ISA_REGISTER_CLASS_float] [ISA_REGISTER_CLASS_integer] [TRUE] = TOP_dmfc1; CGTARG_Inter_RegClass_Copy_Table[ISA_REGISTER_CLASS_integer] [ISA_REGISTER_CLASS_float] [FALSE] = TOP_mtc1; CGTARG_Inter_RegClass_Copy_Table[ISA_REGISTER_CLASS_integer] [ISA_REGISTER_CLASS_float] [TRUE] = TOP_dmtc1; } /* ==================================================================== * * CGTARG_Load_From_Memory * * See interface description * * ==================================================================== */ void CGTARG_Load_From_Memory(TN *tn, ST *mem_loc, OPS *ops) { TYPE_ID mtype = TY_mtype(ST_type(mem_loc)); Exp_Load(mtype, mtype, tn, mem_loc, 0, ops, 0); } /* ==================================================================== * * CGTARG_Store_To_Memory * * See interface description * * ==================================================================== */ void CGTARG_Store_To_Memory(TN *tn, ST *mem_loc, OPS *ops) { TYPE_ID mtype = TY_mtype(ST_type(mem_loc)); Exp_Store(mtype, tn, mem_loc, 0, ops, 0); } /* ==================================================================== * * CGTARG_Init_Assoc_Base * * See interface description * * ==================================================================== */ void CGTARG_Init_Assoc_Base(void) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Copy_Operand * * See interface description * * ==================================================================== */ INT CGTARG_Copy_Operand(OP *op) { TOP opr = OP_code(op); switch (opr) { case TOP_addi: case TOP_addiu: case TOP_daddi: case TOP_daddiu: case TOP_sll: case TOP_srl: case TOP_sra: case TOP_dsll: case TOP_dsrl: case TOP_dsra: if (TN_has_value(OP_opnd(op,1)) && TN_value(OP_opnd(op,1)) == 0) return 0; break; case TOP_andi: { TN *src1 = OP_opnd( op, 1 ); if (TN_is_constant(src1)) { INT64 val; if (TN_has_value(src1)) val = TN_value(src1); else FmtAssert(FALSE,("unexpected constant in CGTARG_Copy_Operand")); if (val == -1) return 0; } break; } case TOP_ori: case TOP_xori: { TN *src1 = OP_opnd( op, 1 ); if (TN_is_constant(src1)) { INT64 val; if (TN_has_value(src1)) val = TN_value(src1); else FmtAssert(FALSE,("unexpected constant in CGTARG_Copy_Operand")); if (val == 0) return 0; } break; } case TOP_or: case TOP_xor: case TOP_addu: case TOP_daddu: if (OP_opnd( op, 1) == Zero_TN) return 0; else if (OP_opnd( op, 0) == Zero_TN) return 1; break; } if (OP_copy(op)) { if (opr == TOP_add || opr == TOP_dadd || opr == TOP_addu || opr == TOP_daddu || opr == TOP_or || opr == TOP_mov_s || opr== TOP_mov_d) return 0; } return -1; } /* ==================================================================== * * CGTARG_Can_Fit_Immediate_In_Add_Instruction * * See interface description * * ==================================================================== */ BOOL CGTARG_Can_Fit_Immediate_In_Add_Instruction (INT64 immed) { return ISA_LC_Value_In_Class (immed, LC_simm16); } /* ==================================================================== * * CGTARG_Can_Load_Immediate_In_Single_Instruction * * See interface description * * ==================================================================== */ BOOL CGTARG_Can_Load_Immediate_In_Single_Instruction (INT64 immed) { return ISA_LC_Value_In_Class (immed, LC_simm16); } #ifdef TARG_MIPS //bug, it doesn't work now. BOOL CGTARG_Can_Fit_Displacement_In_Branch_Instruction (INT64 disp){ return true; } #endif /* ==================================================================== * * CGTARG_Predicate_OP * * See interface description * * ==================================================================== */ /*ARGSUSED*/ void CGTARG_Predicate_OP(BB* bb, OP* op, TN* pred_tn) { if (OP_has_predicate(op)) { FmtAssert( FALSE, ( "CGTARG_Which_OP_Select: Unsupported Target") ); } } /* ==================================================================== * * CGTARG_Branches_On_True * * See interface description * * ==================================================================== */ BOOL CGTARG_Branches_On_True(OP* br_op, OP* cmp_op) { return FALSE; } /* ==================================================================== * * CGTARG_Parallel_Compare * * See interface description * * ==================================================================== */ TOP CGTARG_Parallel_Compare(OP* cmp_op, COMPARE_TYPE ctype) { return TOP_UNDEFINED; } /* ==================================================================== * * CGTARG_Dependence_Required * * See interface description * * ==================================================================== */ BOOL CGTARG_Dependence_Required(OP *pred_op, OP *succ_op) { /* TODO for MIPS */ #if defined(TARG_SL2) switch(OP_code(pred_op)) { case TOP_c2_thctrl_lock: case TOP_c2_thctrl_unlock: case TOP_c2_thctrl_deact: case TOP_c2_thctrl_act: case TOP_c2_thctrl_mode4: case TOP_c2_thctrl_mode5: case TOP_c2_thctrl_mode6: case TOP_c2_thctrl_mode7: case TOP_c2_fork_m: case TOP_c2_fork_n: case TOP_peripheral_rw_begin: case TOP_peripheral_rw_end: return TRUE; } switch(OP_code(succ_op)) { case TOP_c2_thctrl_lock: case TOP_c2_thctrl_unlock: case TOP_c2_thctrl_deact: case TOP_c2_thctrl_act: case TOP_c2_thctrl_mode4: case TOP_c2_thctrl_mode5: case TOP_c2_thctrl_mode6: case TOP_c2_thctrl_mode7: case TOP_c2_fork_m: case TOP_c2_fork_n: case TOP_c2_joint: case TOP_loop: case TOP_peripheral_rw_begin: case TOP_peripheral_rw_end: return TRUE; } #endif return FALSE; } /* ==================================================================== * * CGTARG_Adjust_Latency * * See interface description * * ==================================================================== */ void CGTARG_Adjust_Latency(OP *pred_op, OP *succ_op, CG_DEP_KIND kind, UINT8 opnd, INT *latency) { #if !defined(TARG_SL2) // this function is used to check if bypass can be used between pred and succ // if bypass can be used the latency is 1, producer-to-consumer latency is 3 // Following cases which can use bypass // 1. gpr to gpr // 2. instruction which use vmult, vadd // following cases which can not use bypass // 1. vmov // 2. vspel // 3. vspmacs // 4. other simd register and control register // TN* operand = NULL; if(OP_opnds(succ_op) > opnd) operand = OP_opnd(succ_op, opnd); #ifdef TARG_SL if(OP_has_bypass(pred_op)) *latency = 0; else if(operand && TN_is_register(operand) && TN_register_class(operand) == ISA_REGISTER_CLASS_cop_vreg) { *latency = 2; } #endif #endif } /* ==================================================================== * * CGTARG_Generate_Remainder_Branch * * See interface description * * ==================================================================== */ void CGTARG_Generate_Remainder_Branch(TN *trip_count, TN *label_tn, OPS *prolog_ops, OPS *body_ops) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_OP_is_counted_loop * * See interface description * * ==================================================================== */ BOOL CGTARG_OP_is_counted_loop(OP *op) { return FALSE; } /* ==================================================================== * * CGTARG_Generate_Branch_Cloop * * See interface description * * ==================================================================== */ void CGTARG_Generate_Branch_Cloop(OP *br_op, TN *unrolled_trip_count, TN *trip_count_tn, INT32 ntimes, TN *label_tn, OPS *prolog_ops, OPS *body_ops) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } static TN* asm_constraint_tn[10]; static ISA_REGISTER_SUBCLASS asm_constraint_sc[10]; static char asm_constraint_name[10][8]; static INT asm_constraint_index; // must be called once per asm void CGTARG_Init_Asm_Constraints (void) { // can use any type; it will be ignored Setup_Output_Parameter_Locations (MTYPE_To_TY(MTYPE_I8)); for (INT i = 0; i < 10; ++i) { asm_constraint_tn[i] = NULL; asm_constraint_sc[i] = ISA_REGISTER_SUBCLASS_UNDEFINED; asm_constraint_name[i][0] = '\0'; } asm_constraint_index = 0; } // ----------------------------------------------------------------------- // Given a constraint for an ASM parameter, and the load of the matching // argument passed to ASM (possibly NULL), choose an appropriate TN for it // ----------------------------------------------------------------------- extern TN* CGTARG_TN_For_Asm_Operand (const char* constraint, const WN* load, TN* pref_tn, ISA_REGISTER_SUBCLASS* subclass, const WN* asm_wn, TYPE_ID id) { // skip constraint modifiers: // = input and output parameters are separated in the WHIRL for ASM // & early_clobber flag is set in Handle_ASM // % commutativity of operands is ignored for now static const char* modifiers = "=&%"; while (strchr(modifiers, *constraint)) { constraint++; } // TODO: we should really look at multiple specified constraints // and the load in order to select the best TN, but for now we // assume that when we get here we can safely pick a TN // if 'm' is one of the choices, always prefer that one // TODO: we decide this in the front end, but it's not optimal if (*constraint != 'm') { const char* m = constraint; while (*++m) { if (*m == 'm') { constraint = m; break; } } } // prefer register/memory over immediates; this isn't optimal, // but we may not always be able to generate an immediate static const char* immediates = "in"; while (strchr(immediates, *constraint) && *(constraint+1)) { constraint++; } TN* ret_tn; // TODO: check that the operand satisifies immediate range constraint if (strchr(immediates, *constraint)) { if (load && WN_operator(load)==OPR_LDID && WN_class(load)==CLASS_PREG) { // immediate could have been put in preg by wopt load = Preg_Is_Rematerializable(WN_load_offset(load), NULL); } FmtAssert(load && WN_operator(load) == OPR_INTCONST, ("Cannot find immediate operand for ASM")); ret_tn = Gen_Literal_TN(WN_const_val(load), MTYPE_bit_size(WN_rtype(load))/8); } // digit constraint means that we should reuse a previous operand else if (isdigit(*constraint)) { INT prev_index = *constraint - '0'; FmtAssert(asm_constraint_tn[prev_index], ("numeric matching constraint refers to NULL value")); ret_tn = asm_constraint_tn[prev_index]; } else if (strchr("m", *constraint)) { TYPE_ID rtype = (load != NULL ? WN_rtype(load) : MTYPE_I4); FmtAssert(MTYPE_is_integral(rtype), ("ASM operand does not satisfy its constraint")); ret_tn = (pref_tn ? pref_tn : Build_TN_Of_Mtype(rtype)); } else if ((*constraint == 'r') || (*constraint == 'a') || (*constraint == 'b') || (*constraint == 'v') || (*constraint == 'h') || (*constraint == 'l') || (*constraint == 'd')) { TYPE_ID rtype; if (load != NULL) { rtype = WN_rtype(load); } else { /* We can't figure out what type the operand is, probably because the optimizer deleted the references to it, so return some default type based on the constraint. */ rtype = ((*constraint == 'b') ? MTYPE_B : MTYPE_I4); } ret_tn = (pref_tn ? pref_tn : Build_TN_Of_Mtype(rtype)); } else if (*constraint == 't') { FmtAssert(pref_tn && TN_is_dedicated(pref_tn) && TN_register_class(pref_tn)==ISA_REGISTER_CLASS_UNDEFINED, ("ASM constraint 't' requires a state register")); ret_tn = pref_tn; } else if (*constraint == 'f') { if (load && (WN_desc(load) != MTYPE_F4 || WN_rtype(load) != MTYPE_F4)) { FmtAssert(FALSE, ("ASM operand does not satisfy its constraint")); } ret_tn = (pref_tn ? pref_tn : Build_TN_Of_Mtype(MTYPE_F4)); } else { FmtAssert(FALSE, ("ASM constraint <%s> not supported", constraint)); } asm_constraint_tn[asm_constraint_index] = ret_tn; asm_constraint_index++; return ret_tn; } static char * Get_TN_Assembly_Name (TN *tn) { return "moo"; } void CGTARG_TN_And_Name_For_Asm_Constraint (char *constraint, TYPE_ID mtype, TYPE_ID desc, TN **tn, char **name) { INT i; if (*constraint == '=') { // ignore CGTARG_TN_And_Name_For_Asm_Constraint (constraint+1, mtype, desc, tn, name); return; } if (mtype == MTYPE_V) { // unknown parameter, so pick mtype from constraint if (*constraint == 'f') mtype = MTYPE_F8; else mtype = MTYPE_I8; } switch (*constraint) { case 'r': FmtAssert(MTYPE_is_integral(mtype), ("ASM constraint is integer but parameter is not")); break; case 'f': FmtAssert(MTYPE_is_float(mtype), ("ASM constraint is float but parameter is not")); break; case 'm': break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': i = *constraint - '0'; FmtAssert(asm_constraint_tn[i], ("numeric matching constraint refers to NULL value")); ++asm_constraint_index; *tn = asm_constraint_tn[i]; *name = asm_constraint_name[i]; return; case 'i': // let caller figure out the name *tn = NULL; *name = NULL; return; default: FmtAssert(FALSE, ("ASM constraint <%s> not supported", constraint)); } PLOC ploc = Get_Output_Parameter_Location (MTYPE_To_TY(mtype)); *tn = PREG_To_TN (MTYPE_To_PREG(mtype), PLOC_reg(ploc)); asm_constraint_tn[asm_constraint_index] = *tn; *name = Get_TN_Assembly_Name(*tn); if (*constraint == 'm') { sprintf(asm_constraint_name[asm_constraint_index], "[%s]", *name); } else { sprintf(asm_constraint_name[asm_constraint_index], "%s", *name); } *name = asm_constraint_name[asm_constraint_index]; ++asm_constraint_index; } /* ==================================================================== * target specific modifiers for printing different versions * of register names when they appear as AM operands * ==================================================================== */ char CGTARG_Asm_Opnd_Modifiers[] = { 'r' }; INT CGTARG_Num_Asm_Opnd_Modifiers = 1; const char* CGTARG_Modified_Asm_Opnd_Name(char modifier, TN* tn, char *tn_name) { if (modifier == 'r') { return tn_name; } else { FmtAssert(FALSE, ("Unknown ASM operand modifier '%c'", modifier)); } /*NOTREACHED*/ } /* ==================================================================== * * CGTARG_Postprocess_Asm_String: currently no-op for IA-64 * * ==================================================================== */ void CGTARG_Postprocess_Asm_String (char*) { } /* ==================================================================== * * CGTARG_Unconditional_Compare * * See interface description * * ==================================================================== */ BOOL CGTARG_Unconditional_Compare(OP *op, TOP* uncond_ver) { return FALSE; } /* ==================================================================== * * CGTARG_Invert_Branch * * See interface description * * ==================================================================== */ TOP CGTARG_Invert_Branch(BB* bb) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } /* ==================================================================== * * CGTARG_Init_OP_cond_def_kind * * See interface description * * ==================================================================== */ void CGTARG_Init_OP_cond_def_kind(OP *op) { if( OP_has_predicate(op) ) { FmtAssert(FALSE,("NOT YET IMPLEMENTED")); } else { { Set_OP_cond_def_kind(op, OP_ALWAYS_UNC_DEF); } } } /* ==================================================================== * * CGTARG_Get_unc_Variant * * Given a compare opcode, return the unconditional variant form. * Return the opcode if there is no such form. * * ==================================================================== */ TOP CGTARG_Get_unc_Variant(TOP top) { /* This doesn't seem to be used. */ FmtAssert(FALSE,("NOT YET IMPLEMENTED")); return TOP_UNDEFINED; } //////////////////////////////////////////////////////////////// // If a BB ends in an unconditional branch, turn it into a conditional branch // With TRUE predicate, so we can predicate with something else later. // If we can't find an unconditional branch, just give up and do nothing // void Make_Branch_Conditional(BB *bb) { return; } /* ==================================================================== * * CGTARG_Check_OP_For_HB_Suitability * * Returns TRUE if OP is a suitable candidate for HBF. Otherwise, return * FALSE. * * ==================================================================== */ BOOL CGTARG_Check_OP_For_HB_Suitability(OP *op) { switch(Eager_Level) { case EAGER_NONE: return FALSE; case EAGER_SAFE: if (OP_fadd(op) || OP_fdiv(op) || OP_fsub(op) || OP_fmul(op) || OP_load(op) || OP_store(op) || OP_prefetch(op) || // idiv, imul use hilo registers OP_idiv(op) || OP_imul(op) || (OP_code(op) == TOP_mflo) || (OP_code(op) == TOP_mfhi)) return FALSE; else return TRUE; case EAGER_ARITH: if (OP_load(op) || OP_store(op) || OP_prefetch(op) || // Divide by zero OP_fdiv(op) || OP_idiv(op) || OP_imul(op) || (OP_code(op) == TOP_mflo) || (OP_code(op) == TOP_mfhi)) return FALSE; else return TRUE; case EAGER_DIVIDE: if (OP_load(op) || OP_store(op) || OP_prefetch(op) || OP_idiv(op) || OP_imul(op) || (OP_code(op) == TOP_mflo) || (OP_code(op) == TOP_mfhi)) return FALSE; else return TRUE; case EAGER_MEMORY: case EAGER_OTHER: if (OP_idiv(op) || OP_imul(op) || (OP_code(op) == TOP_mflo) || (OP_code(op) == TOP_mfhi)) return FALSE; else return TRUE; default: FmtAssert(FALSE, ("Handle this case")); return FALSE; } }
25.761213
102
0.557713
[ "vector", "3d" ]
dc7c1578b2ae204fc04f8a98cb72dae217c28476
15,510
cpp
C++
src/Core/Script/GameObject.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
1
2020-07-23T14:23:59.000Z
2020-07-23T14:23:59.000Z
src/Core/Script/GameObject.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
null
null
null
src/Core/Script/GameObject.cpp
BestEggplant/ObEngine
4543ff027cc05de0eddede8f55b28f0cf1138189
[ "MIT" ]
null
null
null
#include <Config/Templates/GameObject.hpp> #include <Scene/Scene.hpp> #include <Script/Exceptions.hpp> #include <Script/GameObject.hpp> #include <Script/ViliLuaBridge.hpp> #include <System/Loaders.hpp> #include <Triggers/Trigger.hpp> #include <Triggers/TriggerManager.hpp> #include <Utils/StringUtils.hpp> #include <utility> #include <vili/parser/parser.hpp> namespace obe::Script { sol::table GameObject::access() const { if (m_hasScriptEngine) return m_environment["Object"].get<sol::table>(); throw Exceptions::NoSuchComponent("Script", m_type, m_id, EXC_INFO); } sol::function GameObject::getConstructor() const { if (m_hasScriptEngine) return m_environment["ObjectInit"].get<sol::function>(); throw Exceptions::NoSuchComponent("Script", m_type, m_id, EXC_INFO); } vili::node GameObjectDatabase::allDefinitions = vili::object {}; vili::node GameObjectDatabase::allRequires = vili::object {}; vili::node GameObjectDatabase::GetRequirementsForGameObject(const std::string& type) { if (allRequires[type].is_null()) { vili::node getGameObjectFile = vili::parser::from_file(System::Path("Data/GameObjects/") .add(type) .add(type + ".obj.vili") .find()); if (!getGameObjectFile["Requires"].is_null()) { vili::node& requiresData = getGameObjectFile.at("Requires"); allRequires[type] = requiresData; return requiresData; } return vili::node {}; } return allRequires.at(type); } vili::node GameObjectDatabase::GetDefinitionForGameObject(const std::string& type) { if (allDefinitions[type].is_null()) { const std::string objectDefinitionPath = System::Path("Data/GameObjects/") .add(type) .add(type + ".obj.vili") .find(); if (objectDefinitionPath.empty()) throw Exceptions::ObjectDefinitionNotFound(type, EXC_INFO); vili::node getGameObjectFile = vili::parser::from_file( objectDefinitionPath, Config::Templates::getGameObjectTemplates()); if (!getGameObjectFile[type].is_null()) { vili::node& definitionData = getGameObjectFile.at(type); allDefinitions[type] = definitionData; return definitionData; } throw Exceptions::ObjectDefinitionBlockNotFound(type, EXC_INFO); } return allDefinitions.at(type); } void GameObjectDatabase::ApplyRequirements( sol::environment environment, vili::node& requires) { /*const sol::table requireTable = environment["LuaCore"]["ObjectInitInjectionTable"].get<sol::table>();*/ environment["LuaCore"]["ObjectInitInjectionTable"] = ViliLuaBridge::viliToLua(requires); } void GameObjectDatabase::Clear() { allDefinitions.clear(); allRequires.clear(); } // GameObject GameObject::GameObject(Triggers::TriggerManager& triggers, sol::state_view lua, const std::string& type, const std::string& id) : Identifiable(id) , m_triggers(triggers) , m_lua(std::move(lua)) { m_type = type; } void GameObject::initialize() { if (!m_active) { Debug::Log->debug( "<GameObject> Initializing GameObject '{0}' ({1})", m_id, m_type); m_active = true; if (m_hasScriptEngine) { m_environment["__OBJECT_INIT"] = true; t_local->trigger("Init"); } } else Debug::Log->warn("<GameObject> GameObject '{0}' ({1}) has already " "been initialized", m_id, m_type); } GameObject::~GameObject() { Debug::Log->debug("<GameObject> Deleting GameObject '{0}' ({1})", m_id, m_type); if (m_hasScriptEngine) { m_environment = sol::lua_nil; t_local.reset(); m_triggers.removeNamespace(m_privateKey); } } void GameObject::sendInitArgFromLua( const std::string& argName, sol::object value) const { Debug::Log->debug("<GameObject> Sending Local.Init argument {0} to " "GameObject {1} ({2}) (From Lua)", argName, m_id, m_type); t_local->pushParameterFromLua("Init", argName, value); } void GameObject::registerTrigger( std::weak_ptr<Triggers::Trigger> trg, const std::string& callbackName) { m_registeredTriggers.emplace_back(trg, callbackName); } void GameObject::loadGameObject( Scene::Scene& scene, vili::node& obj, Engine::ResourceManager* resources) { Debug::Log->debug("<GameObject> Loading GameObject '{0}' ({1})", m_id, m_type); // Script if (!obj["permanent"].is_null()) { m_permanent = obj.at("permanent"); } if (!obj["Script"].is_null()) { m_hasScriptEngine = true; m_environment = sol::environment(m_lua, sol::create, m_lua.globals()); m_privateKey = Utils::String::getRandomKey(Utils::String::Alphabet, 1) + Utils::String::getRandomKey( Utils::String::Alphabet + Utils::String::Numbers, 11); m_triggers.createNamespace(m_privateKey); t_local = m_triggers.createTriggerGroup(m_privateKey, "Local"); m_environment["This"] = this; t_local->add("Init").add("Delete"); m_environment["__OBJECT_TYPE"] = m_type; m_environment["__OBJECT_ID"] = m_id; m_environment["__OBJECT_INIT"] = false; m_environment["Private"] = m_privateKey; m_lua.safe_script_file("Lib/Internal/ObjectInit.lua"_fs, m_environment); auto loadSource = [&](const std::string& path) { const std::string fullPath = System::Path(path).find(); if (fullPath.empty()) { throw Exceptions::ScriptFileNotFound(m_type, m_id, path, EXC_INFO); } m_lua.safe_script_file(fullPath, m_environment); }; if (!obj.at("Script")["source"].is_null()) { const vili::node& sourceNode = obj.at("Script").at("source"); if (sourceNode.is<vili::string>()) { loadSource(sourceNode); } else { throw Exceptions::WrongSourceAttributeType(m_type, "source", vili::string_type, vili::to_string(sourceNode.type()), EXC_INFO); } } else if (!obj.at("Script")["sources"].is_null()) { vili::node& sourceNode = obj.at("Script").at("sources"); if (sourceNode.is<vili::array>()) { for (auto source : sourceNode) { loadSource(source); } } else { throw Exceptions::WrongSourceAttributeType(m_type, "sources", vili::array_type, vili::to_string(sourceNode.type()), EXC_INFO); } } } // Sprite if (!obj["Sprite"].is_null()) { m_sprite = &scene.createSprite(m_id, false); m_objectNode.addChild(*m_sprite); m_sprite->load(obj.at("Sprite")); m_sprite->setParentId(m_id); if (m_hasScriptEngine) m_environment["Object"]["Sprite"] = m_sprite; scene.reorganizeLayers(); } if (!obj["Animator"].is_null()) { m_animator = std::make_unique<Animation::Animator>(); const std::string animatorPath = obj.at("Animator").at("path"); if (m_sprite) m_animator->setTarget(*m_sprite); if (!animatorPath.empty()) { m_animator->load(System::Path(animatorPath), resources); } if (!obj.at("Animator")["default"].is_null()) { m_animator->setKey(obj.at("Animator").at("default")); } if (m_hasScriptEngine) m_environment["Object"]["Animation"] = m_animator.get(); } // Collider if (!obj["Collider"].is_null()) { m_collider = &scene.createCollider(m_id, false); m_objectNode.addChild(*m_collider); m_collider->load(obj.at("Collider")); m_collider->setParentId(m_id); if (m_hasScriptEngine) m_environment["Object"]["Collider"] = m_collider; } } void GameObject::update() { if (m_canUpdate) { if (m_active) { if (m_animator) { if (m_animator->getKey() != "") m_animator->update(); if (m_sprite) { m_sprite->setTexture(m_animator->getTexture()); } } } else { this->initialize(); } } } std::string GameObject::getType() const { return m_type; } bool GameObject::doesHaveAnimator() const { return static_cast<bool>(m_animator); } bool GameObject::doesHaveCollider() const { return static_cast<bool>(m_collider); } bool GameObject::doesHaveSprite() const { return static_cast<bool>(m_sprite); } bool GameObject::doesHaveScriptEngine() const { return m_hasScriptEngine; } bool GameObject::getUpdateState() const { return m_canUpdate; } void GameObject::setUpdateState(bool state) { m_canUpdate = state; } Graphics::Sprite& GameObject::getSprite() const { if (m_sprite) return *m_sprite; throw Exceptions::NoSuchComponent("Sprite", m_type, m_id, EXC_INFO); } Scene::SceneNode& GameObject::getSceneNode() { return m_objectNode; } Collision::PolygonalCollider& GameObject::getCollider() const { if (m_collider) return *m_collider; throw Exceptions::NoSuchComponent("Collider", m_type, m_id, EXC_INFO); } Animation::Animator& GameObject::getAnimator() const { if (m_animator) return *m_animator.get(); throw Exceptions::NoSuchComponent("Animator", m_type, m_id, EXC_INFO); } void GameObject::useTrigger(const std::string& trNsp, const std::string& trGrp, const std::string& trName, const std::string& callAlias) { if (trName == "*") { std::vector<std::string> allTrg = m_triggers.getAllTriggersNameFromTriggerGroup(trNsp, trGrp); for (const std::string& triggerName : allTrg) { this->useTrigger(trNsp, trGrp, triggerName, (Utils::String::occurencesInString(callAlias, "*") ? Utils::String::replace(callAlias, "*", triggerName) : "")); } } else { bool triggerNotFound = true; for (auto& triggerPair : m_registeredTriggers) { if (triggerPair.first.lock() == m_triggers.getTrigger(trNsp, trGrp, trName).lock()) { triggerNotFound = false; } } if (triggerNotFound) { const std::string callbackName = (callAlias.empty()) ? trNsp + "." + trGrp + "." + trName : callAlias; this->registerTrigger( m_triggers.getTrigger(trNsp, trGrp, trName), callbackName); m_triggers.getTrigger(trNsp, trGrp, trName) .lock() ->registerEnvironment(m_id, m_environment, callbackName, &m_active); } else { const std::string callbackName = (callAlias.empty()) ? trNsp + "." + trGrp + "." + trName : callAlias; m_triggers.getTrigger(trNsp, trGrp, trName) .lock() ->unregisterEnvironment(m_environment); m_triggers.getTrigger(trNsp, trGrp, trName) .lock() ->registerEnvironment(m_id, m_environment, callbackName, &m_active); } } } void GameObject::removeTrigger(const std::string& trNsp, const std::string& trGrp, const std::string& trName) const { m_triggers.getTrigger(trNsp, trGrp, trName) .lock() ->unregisterEnvironment(m_environment); } void GameObject::exec(const std::string& query) { m_lua.safe_script(query, m_environment); } void GameObject::deleteObject() { Debug::Log->debug( "GameObject::deleteObject called for '{0}' ({1})", m_id, m_type); if (m_hasScriptEngine) t_local->trigger("Delete"); this->deletable = true; m_active = false; if (m_hasScriptEngine) { for (auto& triggerRef : m_registeredTriggers) { if (auto trigger = triggerRef.first.lock()) { trigger->unregisterEnvironment(m_environment); } } for (const auto& trigger : t_local->getTriggers()) { m_environment["__TRIGGERS"][trigger->getTriggerLuaTableName()] = sol::lua_nil; } for (auto [k, _] : m_environment) { m_environment[k] = sol::lua_nil; } } } void GameObject::setPermanent(bool permanent) { m_permanent = permanent; } bool GameObject::isPermanent() const { return m_permanent; } sol::environment GameObject::getEnvironment() const { return m_environment; } void GameObject::setState(bool state) { m_active = state; } vili::node GameObject::dump() const { vili::node result; result["type"] = this->getType(); if (auto dumpFunction = this->access()["Dump"]; dumpFunction.valid()) { const sol::table saveTableRef = dumpFunction().get<sol::table>(); vili::node saveRequirements = Script::ViliLuaBridge::luaTableToViliObject(saveTableRef); result["Requires"] = saveRequirements; } return result; } void GameObject::load(vili::node& data) { // TODO: Do something } } // namespace obe::Script
32.790698
89
0.520696
[ "object", "vector" ]
dc8165362c55362bf90786588a11bfc0943223bf
6,959
cpp
C++
tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/sim/entity/CReferee.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/sim/entity/CReferee.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/sim/entity/CReferee.cpp
dividio/projectfootball
3c0b94937de2e3cd6e7daf9d3b4942fda974f20c
[ "Zlib" ]
null
null
null
/****************************************************************************** * Copyright (C) 2008 - Ikaro Games www.ikarogames.com * * * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * * ******************************************************************************/ #include <libintl.h> #include "CReferee.h" #include "../CSimulationManager.h" #include "../message/MessageTypes.h" #include "../fsm/CStateMachine.h" #include "../../state/CStateMonitor.h" #include "../../utils/CLog.h" #include "../../engine/option/CSystemOptionManager.h" std::string CReferee::m_pCtorName = "CReferee_p_ctor"; CReferee::CReferee() : CMovingEntity() { CLog::getInstance()->debug("CReferee()"); Ogre::SceneManager *scnMgr = CStateMonitor::getInstance()->getSimulationSceneManager(); CLuaManager::getInstance()->runScript("data/scripts/referee.lua"); m_stateMachine = new CStateMachine<CReferee>(this); m_stateMachine->setGlobalState("SRf_Global"); m_stateMachine->changeState("SRf_BeforeStart"); m_homeScore = 0; m_awayScore = 0; m_kickPosition = new btVector3(0,0,0); m_homeSideLeft = true; m_matchDuration = CSystemOptionManager::getInstance()->getSimulationMatchDuration(); m_centerOfMassOffset.setOrigin(btVector3(0,-1,0)); m_entity = scnMgr->createEntity("Referee", "Human.mesh"); m_entity->setMaterialName("referee"); m_node = scnMgr->getRootSceneNode()->createChildSceneNode("RefereeNode", Ogre::Vector3(0, 0, -38)); m_node->attachObject(m_entity); m_shape = new btCylinderShape(btVector3(btScalar(1.),btScalar(1.),btScalar(1.))); btScalar mass(80.0); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) m_shape->calculateLocalInertia(mass,localInertia); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,this,m_shape,localInertia); m_body = new btRigidBody(rbInfo); m_cycle = 0; } CReferee::~CReferee() { CLog::getInstance()->debug("~CReferee()"); if(m_stateMachine != 0) { delete m_stateMachine; } delete m_kickPosition; } bool CReferee::handleMessage(const CMessage &msg) { return m_stateMachine->handleMessage(msg); } void CReferee::setMatchDuration(int cycles) { m_matchDuration = cycles; } int CReferee::getMatchDuration() const { return m_matchDuration; } void CReferee::setHomeTeamInSideLeft(bool left) { m_homeSideLeft = left; } bool CReferee::isHomeTeamInSideLeft() const { return m_homeSideLeft; } void CReferee::setKickTeam(CTeam *team) { m_kickTeam = team; } void CReferee::setKickPosition(btVector3 &pos) { m_kickPosition->setValue(pos.x(), pos.y(), pos.z()); } void CReferee::setNextTimeKickOffTeam(CTeam *team) { m_nextTimeKickOffTeam = team; } CTeam* CReferee::getKickTeam() { return m_kickTeam; } btVector3 CReferee::getKickPosition() { return *m_kickPosition; } CTeam* CReferee::getNextTimeKickOffTeam() { return m_nextTimeKickOffTeam; } void CReferee::setLastPlayerTouch(CFootballPlayer *player) { m_lastPlayerTouch = player; } CFootballPlayer* CReferee::getLastPlayerTouch() { return m_lastPlayerTouch; } void CReferee::update() { m_stateMachine->update(); } CStateMachine<CReferee>* CReferee::getFSM() { return m_stateMachine; } bool CReferee::isMoveLegal() const { return (m_currentGameMode == END || m_currentGameMode == BEFORE_START || m_currentGameMode == KICK_OFF || m_currentGameMode == HALF_TIME); } GameMode CReferee::getGameMode() { return m_currentGameMode; } int CReferee::getCycle() const { return m_cycle; } int CReferee::getMinute() const { return ((90*m_cycle) / m_matchDuration); } void CReferee::incCycle() { m_cycle++; } void CReferee::setGameMode(GameMode newGameMode) { m_currentGameMode = newGameMode; printf("Ciclo:%d GameMode: %s\n", m_cycle, getGameModeString().c_str()); } std::string CReferee::getGameModeString() { std::string mode; switch(m_currentGameMode) { case BEFORE_START: mode = gettext("Before Start"); break; case HALF_TIME: mode = gettext("Half Time"); break; case PLAY_ON: mode = gettext("Play On"); break; case END: mode = gettext("End"); break; case KICK_OFF: mode = gettext("Kick Off"); break; case KICK_IN: mode = gettext("Kick In"); break; case CORNER_KICK: mode = gettext("Corner Kick"); break; case GOAL_KICK: mode = gettext("Goal Kick"); break; default: break; } return mode; } int CReferee::getHomeScore() const { return m_homeScore; } int CReferee::getAwayScore() const { return m_awayScore; } void CReferee::addHomeGoal(CFootballPlayer *player) { CSimulationManager *sim = CStateMonitor::getInstance()->getSimulationManager(); bool ownGoal = false; CTeam *team = sim->getHomeTeam(); if(player->getTeam()->getID() != team->getID()) { ownGoal = true; } sim->goalMatchEvent(team, player, getMinute(), ownGoal); m_homeScore++; } void CReferee::addAwayGoal(CFootballPlayer *player) { CSimulationManager *sim = CStateMonitor::getInstance()->getSimulationManager(); bool ownGoal = false; CTeam *team = sim->getAwayTeam(); if(player->getTeam()->getID() != team->getID()) { ownGoal = true; } sim->goalMatchEvent(team, player, getMinute(), ownGoal); m_awayScore++; }
25.213768
103
0.597212
[ "mesh" ]
dc81918b9558ea4898470ac71fd9fecf4295eea8
4,237
cc
C++
Engine/foundation/io/logfileconsolehandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/foundation/io/logfileconsolehandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/foundation/io/logfileconsolehandler.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2008, Radon Labs GmbH Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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 "stdneb.h" #include "io/logfileconsolehandler.h" #include "io/ioserver.h" #include "timing/calendartime.h" #include "core/coreserver.h" namespace IO { __ImplementClass(IO::LogFileConsoleHandler, 'LFCH', IO::ConsoleHandler); using namespace Util; using namespace Timing; //------------------------------------------------------------------------------ /** */ LogFileConsoleHandler::LogFileConsoleHandler() { // empty } //------------------------------------------------------------------------------ /** */ LogFileConsoleHandler::~LogFileConsoleHandler() { if (this->IsOpen()) { this->Close(); } } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::Open() { ConsoleHandler::Open(); IoServer* ioServer = IoServer::Instance(); // make sure log directory exists ioServer->CreateDirectory("home:logfiles"); // build a file name for the log file String calString = CalendarTime::Format("{YEAR}_{MONTH}_{DAY}_{HOUR}_{MINUTE}_{SECOND}", CalendarTime::GetLocalTime()); String fileName; fileName.Format("home:logfiles/%s_%s.txt", Core::CoreServer::Instance()->GetAppName().Value(), calString.AsCharPtr()); // open file stream this->stream = ioServer->CreateFileStream(URI(fileName)); this->textWriter = TextWriter::Create(); this->textWriter->SetStream(this->stream); this->textWriter->Open(); } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::Close() { n_assert(this->IsOpen()); if (this->textWriter->IsOpen()) { this->textWriter->Close(); } this->textWriter = 0; this->stream = 0; ConsoleHandler::Close(); } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::Print(const String& s) { if (this->textWriter->IsOpen()) { this->textWriter->WriteString(s); } } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::Error(const String& s) { if (this->textWriter->IsOpen()) { String str("[ERROR] "); str.Append(s); this->textWriter->WriteString(str); this->stream->Flush(); } } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::Warning(const String& s) { if (this->textWriter->IsOpen()) { String str("[WARNING] "); str.Append(s); this->textWriter->WriteString(str); } } //------------------------------------------------------------------------------ /** */ void LogFileConsoleHandler::DebugOut(const String& s) { if (this->textWriter->IsOpen()) { String str("[DEBUGOUT] "); str.Append(s); this->textWriter->WriteString(str); } } } // namespace IO
27.335484
123
0.555346
[ "3d" ]
dc8589a89d0a55028275a66e17fba57909f21a67
79,531
cpp
C++
groups/bsl/bsltf/bsltf_wellbehavedmoveonlyalloctesttype.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bsl/bsltf/bsltf_wellbehavedmoveonlyalloctesttype.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bsl/bsltf/bsltf_wellbehavedmoveonlyalloctesttype.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// bsltf_wellbehavedmoveonlyalloctesttype.t.cpp -*-C++-*- #include <bsltf_wellbehavedmoveonlyalloctesttype.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_testallocator.h> #include <bslma_testallocatormonitor.h> #include <bslmf_assert.h> #include <bslmf_isbitwisemoveable.h> #include <bsls_assert.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsls_objectbuffer.h> #include <algorithm> // 'swap' in C++03 and earlier #include <new> #include <utility> // 'swap' in C++11 and later #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace BloombergLP; using namespace BloombergLP::bsltf; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // The component under test is a single unconstrained (value-semantic) // attribute class. The Primary Manipulators and Basic Accessors are // therefore, respectively, the attribute setters and getters, each of which // follows our standard unconstrained attribute-type naming conventions: // 'setAttributeName' and 'attributeName'. // // Primary Manipulators: //: o 'setData' // // Basic Accessors: //: o 'data' // // Global Concerns: //: o No memory is ever allocated from the global allocator. // // This particular attribute class also provides a value constructor capable of // creating an object in any state relevant for thorough testing, obviating the // primitive generator function, 'gg', normally used for this purpose. We will // therefore follow our standard 10-case approach to testing value-semantic // types except that we will test the value constructor in case 3 (in lieu of // the generator function), with the default constructor and primary // manipulators tested fully in case 2. // //----------------------------------------------------------------------------- // CREATORS // [ 2] Obj(bslma::Allocator *bA = 0); // [ 3] Obj(int data, bslma::Allocator *bA = 0); // [ 7] Obj(bslmf::MovableRef<Obj>); // [ 7] Obj(bslmf::MovableRef<Obj>, bslma::Allocator *); // [ 2] ~Obj(); // [ 9] Obj& operator=(Obj&&); // [ 2] void setData(int value); // [ ] void setMovedInto(MoveState::Enum value); // [ 4] int data() const; // [ 4] bslma::Allocator *allocator() const; // [ ] MoveState::Enum movedInto() const; // [ ] MoveState::Enum movedFrom() const; // [ 6] bool operator==(lhs, rhs); // [ 6] bool operator!=(lhs, rhs); // [ ] MoveState::Enum getMovedFrom(const Obj& object); // [ ] MoveState::Enum getMovedInto(const Obj& object); // [ ] void setMovedInto(Obj *obj, MoveState::Enum v); // [ 8] void swap(Obj& lhs, Obj& rhs); //----------------------------------------------------------------------------- // [ 1] BREATHING TEST // [13] USAGE EXAMPLE // [11] CONCERN: The object has the necessary type traits // [12] CONCERN: Bitwise-moved objects assert on destruction // [ *] CONCERN: In no case does memory come from the global allocator. // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) // ============================================================================ // GLOBAL TYPEDEFS FOR TESTING // ---------------------------------------------------------------------------- typedef bsltf::WellBehavedMoveOnlyAllocTestType Obj; namespace { namespace u { class EqualGuard { // DATA const Obj *d_a; const Obj *d_b; int d_line; public: // CREATORS EqualGuard(const Obj *a, const Obj *b, int line) : d_a(a) , d_b(b) , d_line(line) {} ~EqualGuard() { if (!d_a) { return; // RETURN } ASSERTV(d_line, d_a->data(), d_b->data(), *d_a == *d_b); ASSERTV(d_line, d_a->movedFrom(), MoveState::e_NOT_MOVED == d_a->movedFrom()); ASSERTV(d_line, d_b->movedFrom(), MoveState::e_NOT_MOVED == d_b->movedFrom()); ASSERTV(d_line, d_a->movedInto(), MoveState::e_NOT_MOVED == d_a->movedInto()); ASSERTV(d_line, d_b->movedInto(), MoveState::e_NOT_MOVED == d_b->movedInto()); } // MANIPULATORS void relase() { d_a = d_b = 0; } }; } // close namespace u } // close unnamed namespace // ============================================================================ // GLOBAL CONSTANTS USED FOR TESTING // ---------------------------------------------------------------------------- struct DefaultValueRow { int d_line; // source line number int d_data; }; static const DefaultValueRow DEFAULT_VALUES[] = { //LINE DATA //---- ---- // default (must be first) { L_, 0 }, // 'data' { L_, INT_MIN }, { L_, -1 }, { L_, 1 }, { L_, INT_MAX }, }; enum { DEFAULT_NUM_VALUES = sizeof DEFAULT_VALUES / sizeof *DEFAULT_VALUES }; // ============================================================================ // GLOBAL FUNCTIONS USED FOR TESTING // ---------------------------------------------------------------------------- static void exitHandler(const bsls::AssertViolation&) // Call 'exit' with the current 'testStatus' of this test driver. This // function is intended to be used as an assertion handler, registered with // 'bsls_assert'. To check that an assertion is triggered (when expected) // in a destructor, we need a code path that can exit the process directly // without returning control to the test handler. In C++11, destructors // are expected to have 'noexcept(true)' exception specifications, which is // the new default, so we cannot rely on the regular assert test handler // that indicates an expected assertion by throwing an exception. Note // that the expected effect is 'exit(0)' as 'testStatus' should be zero for // a passing test driver. However, we do not want to lose reporting any // other error detected in the current test case, so return the value of // 'testStatus'. { if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } exit(testStatus); } //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; bool veryVeryVerbose = argc > 4; bool veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); // CONCERN: In no case does memory come from the global allocator. bslma::TestAllocator globalAllocator("global", veryVeryVeryVerbose); bslma::Default::setGlobalAllocator(&globalAllocator); // Confirm no static initialization locked the global allocator ASSERT(&globalAllocator == bslma::Default::globalAllocator()); switch (test) { case 0: // Zero is always the leading case. case 13: { // -------------------------------------------------------------------- // USAGE EXAMPLE // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) printf("\nUSAGE EXAMPLE" "\n=============\n"); ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Type Traits and Move Construction /// - - - - - - - - - - - - - - - - - - - - - - // First, we observe that the type uses 'bslma::Allocator's: //.. ASSERT(true == bslma::UsesBslmaAllocator< bsltf::WellBehavedMoveOnlyAllocTestType>::value); //.. // Then, we observe that the type is not copy-constructible: //.. ASSERT(false == bsl::is_copy_constructible< bsltf::WellBehavedMoveOnlyAllocTestType>::value); //.. // Next, we observe that the type is not bitwise movable: //.. ASSERT(false == bslmf::IsBitwiseMoveable< bsltf::WellBehavedMoveOnlyAllocTestType>::value); //.. // Then, we create an instance of our type with the value '5': //.. bsltf::WellBehavedMoveOnlyAllocTestType a(5); //.. // Next, we move-construct another instance from the first: //.. bsltf::WellBehavedMoveOnlyAllocTestType b(bslmf::MovableRefUtil::move(a)); //.. // Now, we observe the salient state of both objects: //.. ASSERT(0 == a.data()); ASSERT(5 == b.data()); //.. // And finally, the non-salient state: //.. ASSERT(bsltf::MoveState::e_MOVED == a.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == b.movedInto()); // ASSERT(bsltf::MoveState::e_NOT_MOVED == a.movedInto()); ASSERT(bsltf::MoveState::e_NOT_MOVED == b.movedFrom()); //.. } break; case 12: { // -------------------------------------------------------------------- // TESTING ASSERTION ON BITWISE MOVE // The 'WellBehavedMoveOnlyAllocTestType' object is specifically // designed to NOT be bitwise-moveable, so that it can be used to // verify code is correctly testing the 'bslmf::IsBitwiseMoveable' // trait before using such a technique. The destructor for this class // is mined with a check that the current value of 'this' is the same // as when the object was first created. If this test fails, an // ASSERT_OPT is triggered. In C++03 we might test for this using the // familiar 'bsls_asserttest' facility, but in C++11 destructors become // implicitly 'noexcept', and throwing a testing exception from the // assertion handler will cause 'terminate' to be called for violating // the exception specification. Therefore, this test case will install // a custom assert handler directly before calling the destructor of a // (illegally) bitwise-moved object, that calls 'exit(0)' to indicate // success, honoring the contract than an assertion handler should not // return to the caller. As this will end the process, it must be the // last test in this test case, on a successful run. Following the // destructor, we must ASSERT to signal an error that the destructor // was *not* supposed to return control back to the test case. // // Concerns: //: 1 Bitwise moving this object will cause the destructor to raise an //: assertion. // // Plan: //: 1 Create an memory buffer and create a new object with //: placement-new. //: //: 2 Install an assertion handler that will call 'exit' if triggered. //: //: 3 Bitwise-move the created object to another location in the //: buffer. Explicitly call the object's destructor, which should //: exit via the assertion handler.. (C-1) //: //: 4 ASSERT after destruction to highlight an error if the destructor //: returns. // // Testing: // CONCERN: Bitwise-moved objects assert on destruction // -------------------------------------------------------------------- if (verbose) printf("\nTESTING ASSERTION ON BITWISE MOVE" "\n=================================\n"); { bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); // The next test has an unusual code-path, and will directly call // 'exit' from an assertion handler on success. It must be the // last part of this test case, as it will exit the process on // success without returning control to this test case. if (verbose) printf("\n"); { bsls::AssertFailureHandlerGuard hG(&exitHandler); bsls::ObjectBuffer<Obj> aBuffer, bBuffer; Obj& a = aBuffer.object(); Obj& b = bBuffer.object(); new (&a) Obj(5); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wclass-memaccess" ::memcpy(&b, &a, sizeof(a)); # pragma GCC diagnostic pop ASSERT(5 == b.data()); b.~Obj(); // This should 'exit' if asserts are enabled ASSERTV("The preceding destructor should 'exit' the process", false); } } } break; case 11: { // -------------------------------------------------------------------- // TESTING TYPE TRAITS // // Concerns: //: 1 Ensure that 'WellBehavedMoveOnlyAllocTestType' has the necessary //: trait values to guarantee its expected behavior. //: //: 2 The object has the 'bslma::UsesBslmaAllocator' trait. //: //: 3 The object is not bitwise-moveable. //: //: 4 The object is not copy constructible. //: //: 5 The object is nothrow move constructible. // // Plan: //: 1 Use 'BSLMF_ASSERT' to verify all the type traits exists. (C-1) // // Testing: // CONCERN: The object has the necessary type traits // -------------------------------------------------------------------- if (verbose) printf("\nTESTING TYPE TRAITS" "\n===================\n"); BSLMF_ASSERT( bslma::UsesBslmaAllocator<Obj>::value); BSLMF_ASSERT(!bslmf::IsBitwiseMoveable<Obj>::value); BSLMF_ASSERT(!bsl::is_copy_constructible<Obj>::value); BSLMF_ASSERT( bsl::is_nothrow_move_constructible<Obj>::value); } break; case 10: { // -------------------------------------------------------------------- // TESTING BSLX STREAMING // N/A // -------------------------------------------------------------------- if (verbose) printf("\nTESTING BSLX STREAMING" "\n======================\n"); if (verbose) printf("\nOperations not supported for this type.\n"); } break; case 9: { // -------------------------------------------------------------------- // TESTING MOVE-ASSIGNMENT OPERATOR // Ensure that we can move assign the value of any object of the // class to any object of the class. // // Concerns: //: 1 The assignment operator can change the value of any modifiable //: target object to the original value of any source object. //: //: 2 The allocator address held by the target object is unchanged. //: //: 3 Any memory allocation is from the target object's allocator. //: //: 4 The signature and return type are standard. //: //: 5 The reference returned is to the target object (i.e., '*this'). //: //: 6 The value of the source object is not modified if the allocators //: of the source and target don't match. //: //: 7 The allocator address held by the source object is unchanged. //: //: 8 Any memory allocation is exception neutral. //: //: 9 Assigning an object to itself behaves as expected (alias-safety). //: //: 10 Every object releases any allocated memory at destruction. // // Plan: //: 1 Use the address of 'operator=' to initialize a member-function //: pointer having the appropriate signature and return type for the //: copy-assignment operator defined in this component. (C-4) //: //: 2 Create a 'bslma::TestAllocator' object, and install it as the //: default allocator (note that a ubiquitous test allocator is //: already installed as the global allocator). //: //: 3 Using the table-driven technique, specify a set of distinct //: object values (one per row) in terms of their attributes. //: //: 4 For each row 'R1' (representing a distinct object value, 'DATA1') //: in the table described in P-3: (C-1..2, 5..8, 11) //: //: 1 Use the value constructor and a "scratch" allocator to create //: one 'const' 'Obj', ZZ', each having the value 'DATA1'. //: //: 2 Execute an inner loop that iterates over each row 'R2' //: (representing a distinct object value, 'DATA2') in the table //: described in P-3: //: //: 3 For each of the iterations (P-4.2): (C-1..2, 5..8, 11) //: //: 1 Create a 'bslma::TestAllocator' object, 'oa'. //: //: 2 Use the value constructor and 'oa' to create a modifiable //: 'Obj', 'mX', and 'const Obj' 'XX' having the value 'DATA2'. //: //: 3 Create an allocation exception block based on 'oa'. //: //: 4 Create a modifiable 'Obj' 'mZ' set to 'DATA1'. //: //: 5 Set up equality guards that will compare 'ZZ' to 'Z' and //: 'XX' to 'X' upon destruction, to check that the strong //: exception guarantee is provided. //: //: 6 Move-assign 'mX' from 'Z' in the presence, which will throw. //: //: 7 Verify that the address of the return value is the same as //: that of 'mX'. (C-5) //: //: 8 Use the equality-comparison operator to verify that: (C-1, 6) //: //: 1 The target object, 'mX', now has the same value as that of //: 'ZZ'. (C-1) //: //: 1 The source object, 'Z', still has the same value as that of //: 'ZZ'. (C-6) //: //: 9 Use the 'allocator' accessor of both 'mX' and 'Z' to verify //: that the respective allocator addresses held by the target //: and source objects are unchanged. (C-2, 7) //: //: 10 Observe that neither the source nor the destination were //: marked 'moved' into or from. //: //: 11 Observe that at least one throw due to memory allocation //: occurred. //: //: 12 Observe from a 'TestAllocatorMonitor' that allocation(s) //: have occurred, and the net memory use is unchanged. //: //: 5 Still in the inner loop with 'DATA2' set, start a new block with //: and create a new 'mX' set to 'DATA2' and 'mZ' set to 'DATA1', //: both using allocator 'oa' this time. //: //: 1 Move assign 'mZ' to 'mX'. //: //: 2 Verify that the address of the return value is the same as that //: of 'mX'. (C-5) //: //: 3 Use the equality-comparison operator to verify that: (C-1, 6) //: 1 The target object, 'mX', now has the same value as that of //: 'ZZ'. (C-1) //: //: 4 Use the 'allocator' accessor of both 'mX' and 'Z' to verify //: that the respective allocator addresses held by the target and //: source objects are unchanged. (C-2, 7) //: //: 5 Observe that the source was moved from, and the target was //: moved into. //: //: 6 Observe from a 'TestAllocatorMonitor' that no new allocation(s) //: have occurred, and the net memory use is down. //: //: 7 Observe that the default allocator has not been used. //: //: 6 Leave the innermost loop. //: //: 7 Still in the outermost loop, create an object 'mX' initialized to //: 'DATA1', and assign it to itself. //: //: 1 Verify that the address of the return value is the same as that //: of 'mX'. (C-5) //: //: 2 Observe the allocator of 'mX' is unchanged. //: //: 3 Observe that the value of 'mX' is unchanged. //: //: 4 Observe that no memory allocation happened. // // Testing: // Obj& operator=(Obj&&); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING MOVE-ASSIGNMENT OPERATOR" "\n================================\n"); if (verbose) printf("\nAssign the address of the operator to a variable.\n"); { typedef Obj& (Obj::*operatorPtr)(bslmf::MovableRef<Obj>); // Verify that the signature and return type are standard. operatorPtr operatorAssignment = &Obj::operator=; (void) operatorAssignment; // quash potential compiler warning } bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); const int NUM_VALUES = DEFAULT_NUM_VALUES; const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES; for (int ti = 0; ti < NUM_VALUES; ++ti) { const int LINE1 = VALUES[ti].d_line; const int DATA1 = VALUES[ti].d_data; if (veryVerbose) { T_ P_(LINE1) P(DATA1) } bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose); const Obj ZZ(DATA1, &scratch); for (int tj = 0; tj < NUM_VALUES; ++tj) { const int LINE2 = VALUES[tj].d_line; const int DATA2 = VALUES[tj].d_data; if (veryVerbose) { T_ T_ P_(LINE2) P(DATA2) } bslma::TestAllocator oa("object", veryVeryVeryVerbose); if (veryVerbose) printf("\t\tAssign: different allocators\n"); { Obj mX(DATA2, &oa); const Obj& X = mX; const Obj XX(DATA2, &scratch); if (veryVerbose) { T_ P_(LINE2) P(X.data()) } bslma::TestAllocatorMonitor oam(&oa); int numThrows = -1; BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) { ++numThrows; Obj mZ(DATA1, &scratch); const Obj& Z = mZ; u::EqualGuard guardZ(&ZZ, &Z, L_); u::EqualGuard guardX(&XX, &X, L_); ASSERTV(LINE1, LINE2, Z.data(), X.data(), (Z == X) == (LINE1 == LINE2)); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &scratch, Z.allocator(), &scratch == Z.allocator()); if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } Obj *mR = &(mX = bslmf::MovableRefUtil::move(mZ)); ASSERTV(LINE1, LINE2, Z.data(), X.data(), ZZ == X); ASSERTV(LINE1, LINE2, X.data(), ZZ == Z); ASSERTV(LINE1, LINE2, mR, &mX, mR == &mX); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &scratch, Z.allocator(), &scratch == Z.allocator()); guardX.relase(); // Verify the move-flags correctly observed the move. ASSERTV(LINE1, LINE2, X.movedFrom(), MoveState::e_NOT_MOVED == X.movedFrom()); ASSERTV(LINE1, LINE2, X.movedInto(), MoveState::e_NOT_MOVED == X.movedInto()); ASSERTV(LINE1, LINE2, Z.movedFrom(), MoveState::e_NOT_MOVED == Z.movedFrom()); ASSERTV(LINE1, LINE2, Z.movedInto(), MoveState::e_NOT_MOVED == Z.movedInto()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END; ASSERT(0 < numThrows); ASSERTV(LINE1, LINE2, ZZ.data(), X.data(), ZZ == X); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, oam.isInUseSame()); ASSERTV(LINE1, LINE2, oam.isTotalUp()); ASSERTV(LINE1, LINE2, 0 == da.numBlocksTotal()); } if (veryVerbose) printf("\t\tAssign: matching allocators\n"); { Obj mX(DATA2, &oa); const Obj& X = mX; if (veryVerbose) { T_ P_(LINE2) P(X.data()) } Obj mZ(DATA1, &oa); const Obj& Z = mZ; ASSERTV(LINE1, LINE2, Z.data(), X.data(), (Z == X) == (LINE1 == LINE2)); bslma::TestAllocatorMonitor oam(&oa); Obj *mR = &(mX = bslmf::MovableRefUtil::move(mZ)); ASSERTV(LINE1, LINE2, ZZ.data(), X.data(), ZZ == X); ASSERTV(LINE1, LINE2, Z.data(), 0 == Z.data()); ASSERTV(LINE1, LINE2, mR, &mX, mR == &mX); // Verify the move-flags correctly observed the move. ASSERTV(LINE1, LINE2, X.movedFrom(), MoveState::e_NOT_MOVED == X.movedFrom()); ASSERTV(LINE1, LINE2, X.movedInto(), MoveState::e_MOVED == X.movedInto()); ASSERTV(LINE1, LINE2, Z.movedFrom(), MoveState::e_MOVED == Z.movedFrom()); ASSERTV(LINE1, LINE2, Z.movedInto(), MoveState::e_NOT_MOVED == Z.movedInto()); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, oam.isTotalSame()); ASSERTV(LINE1, LINE2, oam.isInUseDown()); ASSERTV(LINE1, LINE2, 0 == da.numBlocksTotal()); } // Verify all memory is released on object destruction. ASSERTV(LINE1, LINE2, oa.numBlocksInUse(), 0 == oa.numBlocksInUse()); } if (veryVerbose) printf("self-assignment\n"); { bslma::TestAllocator oa( "object", veryVeryVeryVerbose); bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose); Obj mX(DATA1, &oa); const Obj ZZ(DATA1, &scratch); Obj& mZ = mX; const Obj& Z = mX; ASSERTV(LINE1, ZZ.data(), Z.data(), ZZ == Z); bslma::TestAllocatorMonitor oam(&oa); if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } Obj *mR = &(mX = bslmf::MovableRefUtil::move(mZ)); LOOP3_ASSERT(LINE1, ZZ.data(), Z.data(), ZZ == Z); ASSERTV(LINE1, mR, &mX, mR == &mX); ASSERTV(LINE1, Z.movedFrom(), MoveState::e_NOT_MOVED == Z.movedFrom()); ASSERTV(LINE1, Z.movedInto(), MoveState::e_NOT_MOVED == Z.movedInto()); ASSERTV(LINE1, &oa, Z.allocator(), &oa == Z.allocator()); ASSERTV(LINE1, oam.isTotalSame()); ASSERTV(LINE1, oam.isInUseSame()); ASSERTV(LINE1, 0 == da.numBlocksTotal()); } } } break; case 8: { // -------------------------------------------------------------------- // TESTING SWAP FREE FUNCTION // There is no member 'swap' function, but the free function in the // 'bsltf' namespace needs testing. // // Concerns: //: 1 'swap' exchanges the state of two distinct objects, and, if the //: memory allocators match, leaves both in a state that is both //: 'movedFrom' and 'movedInto', and if not, leaves both in a state //: that is neither 'movedFrom' nor 'movedInto'. //: //: 2 'swap'ping an object with itself retains state, and leaves that //: object in a state that is both 'movedFrom' and 'movedInto'. //: //: 3 'swap' does not propagate allocators when two objects have //: different allocators. //: //: 4 'swap' might throw when allocators are different, but in no event //: does it leak memory, or mis-report an object being moved-into if //: no change of state occurs. // // Plan: //: 1 ... // // Testing: // void swap(Obj& lhs, Obj& rhs); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING SWAP FREE FUNCTION" "\n==========================\n"); bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); const int NUM_VALUES = DEFAULT_NUM_VALUES; const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES; for (int ti = 0; ti < NUM_VALUES; ++ti) { const int LINE1 = VALUES[ti].d_line; const int DATA1 = VALUES[ti].d_data; if (veryVerbose) { T_ P_(LINE1) P(DATA1) } bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose); const Obj Z1(DATA1, &scratch); for (int tj = 0; tj < NUM_VALUES; ++tj) { const int LINE2 = VALUES[tj].d_line; const int DATA2 = VALUES[tj].d_data; if (veryVerbose) { T_ T_ P_(LINE2) P(DATA2) } const Obj Z2(DATA2, &scratch); bslma::TestAllocator oa("object", veryVeryVeryVerbose); if (veryVeryVerbose) printf("\twith the same allocator\n"); { Obj mX(DATA1, &oa); const Obj& X = mX; Obj mY(DATA2, &oa); const Obj& Y = mY; ASSERTV(LINE1, LINE2, Z1.data(), X.data(), Z1 == X); ASSERTV(LINE1, LINE2, Z2.data(), Y.data(), Z2 == Y); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &oa, Y.allocator(), &oa == Y.allocator()); oa.setAllocationLimit(0); using std::swap; swap(mX, mY); oa.setAllocationLimit(-1); ASSERTV(LINE1, LINE2, Z2.data(), X.data(), Z2 == X); ASSERTV(LINE1, LINE2, Z1.data(), Y.data(), Z1 == Y); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &oa, Y.allocator(), &oa == Y.allocator()); ASSERTV(LINE1, LINE2, X.movedFrom(), MoveState::e_NOT_MOVED == X.movedFrom()); ASSERTV(LINE1, LINE2, X.movedInto(), MoveState::e_MOVED == X.movedInto()); ASSERTV(LINE1, LINE2, Y.movedFrom(), MoveState::e_NOT_MOVED == Y.movedFrom()); ASSERTV(LINE1, LINE2, Y.movedInto(), MoveState::e_MOVED == Y.movedInto()); } if (veryVeryVerbose) printf("\twith different allocators\n"); { bslma::TestAllocatorMonitor oam(&oa); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) { Obj mX(DATA1, &oa); const Obj& X = mX; Obj mY(DATA2, &scratch); const Obj& Y = mY; ASSERTV(LINE1, LINE2, Z1.data(), X.data(), Z1 == X); ASSERTV(LINE1, LINE2, Z2.data(), Y.data(), Z2 == Y); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &scratch, Y.allocator(), &scratch == Y.allocator()); if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } using std::swap; swap(mX, mY); ASSERTV(LINE1, LINE2, Z2.data(), X.data(), Z2 == X); ASSERTV(LINE1, LINE2, Z1.data(), Y.data(), Z1 == Y); ASSERTV(LINE1, LINE2, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE1, LINE2, &scratch, Y.allocator(), &scratch == Y.allocator()); ASSERTV(LINE1, LINE2, X.movedFrom(), MoveState::e_NOT_MOVED == X.movedFrom()); ASSERTV(LINE1, LINE2, X.movedInto(), MoveState::e_NOT_MOVED == X.movedInto()); ASSERTV(LINE1, LINE2, Y.movedFrom(), MoveState::e_NOT_MOVED == Y.movedFrom()); ASSERTV(LINE1, LINE2, Y.movedInto(), MoveState::e_NOT_MOVED == Y.movedInto()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END; ASSERTV(LINE1, LINE2, oam.isInUseSame()); ASSERTV(LINE1, LINE2, da.numBlocksTotal(), 0 == da.numBlocksTotal()); // Verify all memory is released on object destruction. ASSERTV(LINE1, LINE2, oa.numBlocksInUse(), 0 == oa.numBlocksInUse()); } if (veryVeryVerbose) printf("\taliasing\n"); { Obj mX(DATA1, &oa); const Obj& X = mX; ASSERTV(LINE1, LINE2, Z1.data(), X.data(), Z1 == X); using std::swap; swap(mX, mX); ASSERTV(LINE1, Z1.data(), X.data(), Z1 == X); ASSERTV(LINE1, X.movedFrom(), MoveState::e_NOT_MOVED == X.movedFrom()); ASSERTV(LINE1, X.movedInto(), MoveState::e_NOT_MOVED == X.movedInto()); Obj mY(bslmf::MovableRefUtil::move(mX)); (void) mY; ASSERTV(LINE1, LINE2, X.data(), 0 == X.data()); ASSERTV(LINE1, X.movedFrom(), MoveState::e_MOVED == X.movedFrom()); ASSERTV(LINE1, X.movedInto(), MoveState::e_NOT_MOVED == X.movedInto()); swap(mX, mX); ASSERTV(LINE1, LINE2, X.data(), 0 == X.data()); ASSERTV(LINE1, X.movedFrom(), MoveState::e_MOVED == X.movedFrom()); ASSERTV(LINE1, X.movedInto(), MoveState::e_NOT_MOVED == X.movedInto()); } } } } break; case 7: { // -------------------------------------------------------------------- // TESTING MOVE CONSTRUCTOR // Ensure that we can create a distinct object of the class from any // other one, such that the value of the target object will match the // original value of the source object. // // Concerns: //: 1 The move constructor creates an object having the same value as //: the original value of the supplied original object. //: //: 2 If an allocator is NOT supplied to the copy constructor, the //: target object uses the same allocator as the source object. //: //: 3 If an allocator IS supplied to the copy constructor, that //: allocator becomes the object allocator for the resulting object. //: 1 If the allocator supplied matches the allocator of the source //: object, the behavior is the same as if no allocator is passed. //: //: 2 If the allocators don't match, a copy and not a move occurs. //: //: 4 Supplying a null allocator address has the same effect as not //: passing the default allocator. //: //: 5 Any memory allocation is from the object allocator. //: //: 6 If no allocator is passed or if the allocators match //: 1 no allocations occur //: //: 2 the target is marked moved-into. //: //: 3 the source is marked moved-from. //: //: 7 If a non-matching allocator is passed //: 1 the c'tor is exception-neutral w.r.t. memory allocation //: //: 2 the value of the source is unchanged //: //: 3 neither the source nor the target are marked moved. //: //: 8 The allocator address held by the original object is unchanged. // // Plan: //: 1 Using the table-driven technique, specify a set of distinct //: object values (one per row) in terms of their attributes. //: //: 2 For each row (representing a distinct object value, 'DATA') in //: the table described in P-1: (C-1..10) //: //: 1 Use the value constructor and a "scratch" allocator to create //: two 'const' 'Obj', 'Z' and 'ZZ', each having the value 'V'. //: //: 2 Execute an inner loop creating three distinct objects in turn, //: each using the copy constructor in the presence of injected //: exceptions (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' //: macros) on 'Z' from P-2.1, but configured differently: (a) //: without passing an allocator, (b) passing a null allocator //: address explicitly, and (c) passing the address of the same //: allocator the source used, and (d) passing the address of a //: test allocator other than the default allocator of the source //: object's allocator. (C-7) //: //: 3 For each of these three iterations (P-2.2): (C-1..10) //: //: 1 Create four 'bslma::TestAllocator' objects, and install one //: as the current default allocator (note that a ubiquitous test //: allocator is already installed as the global allocator). //: //: 2 Use the copy constructor to dynamically create an object 'X', //: with its object allocator configured appropriately (see //: P-2.2), supplying it the 'const' object 'Z' (see P-2.1); use //: a distinct test allocator for the object's footprint. (C-8) //: //: 3 Use the equality-comparison operator to verify that: //: (C-1, 5, 9) //: //: 1 The newly constructed object, 'X', has the same value as //: that of 'Z'. (C-1, 5) //: //: 2 'Z' still has the same value as that of 'ZZ'. (C-9 //: //: 4 Use the 'allocator' accessor of each underlying attribute //: capable of allocating memory to ensure that its object //: allocator is properly installed; also use the 'allocator' //: accessor of 'X' to verify that its object allocator is //: properly installed, and use the 'allocator' accessor of 'Z' //: to verify that the allocator address that it holds is //: unchanged. (C-6, 10) //: //: 5 Use the appropriate test allocators to verify that: (C-2..4, //: 7..8) //: //: 1 An object allocates memory from the object allocator only. //: (C-2..4) //: //: 3 If an allocator was supplied at construction (P-2.1c), the //: current default allocator doesn't allocate any memory. //: (C-3) //: //: 4 No temporary memory is allocated from the object allocator. //: (C-7) //: //: 5 All object memory is released when the object is destroyed. //: (C-8) // // Testing: // Obj(bslmf::MovableRef<Obj>); // Obj(bslmf::MovableRef<Obj>, bslma::Allocator *); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING MOVE CONSTRUCTOR" "\n========================\n"); const int NUM_VALUES = DEFAULT_NUM_VALUES; const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES; for (int ti = 0; ti < NUM_VALUES; ++ti) { const int LINE = VALUES[ti].d_line; const int DATA = VALUES[ti].d_data; if (0 == DATA) continue; if (veryVerbose) { T_ P_(LINE) P(DATA) } bslma::TestAllocator scratch("scratch", veryVeryVeryVerbose); const Obj ZZ(DATA, &scratch); // reference value for (char cfg = 'a'; cfg <= 'd'; ++cfg) { const char CONFIG = cfg; // how we specify the allocator bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator fa("footprint", veryVeryVeryVerbose); bslma::TestAllocator sa("source", veryVeryVeryVerbose); bslma::TestAllocator ta("target", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj *srcPtr = new (fa) Obj(DATA, &sa); // object to move from Obj& mZ = *srcPtr; const Obj& Z = mZ; Obj *objPtr = 0; // test object to construct bslma::TestAllocator *objAllocatorPtr = 0; bool allocMatch = true; switch (CONFIG) { case 'a': { objAllocatorPtr = &sa; } break; case 'b': { objAllocatorPtr = &da; allocMatch = false; } break; case 'c': { objAllocatorPtr = &sa; } break; case 'd': { objAllocatorPtr = &ta; allocMatch = false; } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } break; } bslma::TestAllocator& oa = *objAllocatorPtr; BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) { if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } bslma::TestAllocatorMonitor tam(&oa); switch (CONFIG) { case 'a': { objPtr = new (fa) Obj(bslmf::MovableRefUtil::move(mZ)); } break; case 'b': { objPtr = new (fa) Obj(bslmf::MovableRefUtil::move(mZ), 0); } break; case 'c': { objPtr = new (fa) Obj(bslmf::MovableRefUtil::move(mZ), &sa); } break; case 'd': { objPtr = new (fa) Obj(bslmf::MovableRefUtil::move(mZ), &ta); } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } break; } ASSERTV(CONFIG, (&sa != &oa) == tam.isInUseUp()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END; if (veryVerbose) { T_ P_(LINE) P(DATA) } ASSERTV(LINE, CONFIG, 2 * sizeof(Obj) == fa.numBytesInUse()); Obj& mX = *objPtr; const Obj& X = mX; ASSERT(ZZ == X); ASSERT(DATA == X.data()); ASSERT(0 != X.data()); if (allocMatch) { ASSERTV(Z.data(), 0 == Z.data()); ASSERTV(Z.data(), X.data(), Z != X); ASSERTV(Z.data(), ZZ.data(), Z != ZZ); } else { ASSERTV(X.data(), ZZ.data(), X == ZZ); ASSERTV(X.data(), ZZ.data(), X == Z); } // Also invoke the object's 'allocator' accessor, as well as // that of 'Z'. ASSERTV(LINE, CONFIG, &oa, X.allocator(), &oa == X.allocator()); ASSERTV(LINE, CONFIG, &sa, Z.allocator(), &sa == Z.allocator()); // Verify the move-flags have correctly observed the move. ASSERTV(CONFIG, X.movedFrom(), X.movedFrom() == MoveState::e_NOT_MOVED); ASSERTV(CONFIG, Z.movedInto(), Z.movedInto() == MoveState::e_NOT_MOVED); MoveState::Enum expMove = allocMatch ? MoveState::e_MOVED : MoveState::e_NOT_MOVED; ASSERTV(CONFIG, X.movedInto(), allocMatch, expMove, X.movedInto() == expMove); ASSERTV(CONFIG, Z.movedFrom(), allocMatch, expMove, Z.movedFrom() == expMove); // Verify no allocation from the non-object allocators. ASSERTV(LINE, CONFIG, da.numBlocksTotal(), (CONFIG == 'b' ? 1 : 0) == da.numBlocksTotal()); ASSERTV(LINE, CONFIG, da.numBlocksTotal(), (CONFIG == 'd' ? 1 : 0) == ta.numBlocksTotal()); ASSERTV(LINE, CONFIG, ta.numBlocksTotal(), 1 == sa.numBlocksTotal()); ASSERTV(LINE, CONFIG, ta.numBlocksTotal(), 1 == oa.numBlocksTotal()); // Verify no temporary memory is allocated from the object // allocator. ASSERTV(LINE, CONFIG, oa.numBlocksTotal(), oa.numBlocksInUse(), oa.numBlocksTotal() == oa.numBlocksInUse()); fa.deleteObject(srcPtr); // Verify expected object-memory allocations. ASSERTV(LINE, CONFIG, 1, oa.numBlocksInUse(), oa.numBlocksInUse() == 1); // Reclaim dynamically allocated object under test. fa.deleteObject(objPtr); // d'tors of test allocators verify all memory has been freed. } } } break; case 6: { // -------------------------------------------------------------------- // TESTING EQUALITY-COMPARISON OPERATORS // Ensure that '==' and '!=' are the operational definition of value. // // Concerns: //: 1 Two objects, 'X' and 'Y', compare equal if and only if they point //: to the same node in the same tree. //: //: 2 'true == (X == X)' (i.e., identity) //: //: 3 'false == (X != X)' (i.e., identity) //: //: 4 'X == Y' if and only if 'Y == X' (i.e., commutativity) //: //: 5 'X != Y' if and only if 'Y != X' (i.e., commutativity) //: //: 6 'X != Y' if and only if '!(X == Y)' //: //: 7 Comparison is symmetric with respect to user-defined conversion //: (i.e., both comparison operators are free functions). //: //: 8 Non-modifiable objects can be compared (i.e., objects or //: references providing only non-modifiable access). //: //; 9 The equality operator's signature and return type are standard. //: //:10 The inequality operator's signature and return type are standard. //: //:11 No memory allocation occurs as a result of comparison (e.g., the //: arguments are not passed by value). //: //:12 The equality operator's signature and return type are standard. //: //:13 The inequality operator's signature and return type are standard. // // Plan: //: 1 Use the respective addresses of 'operator==' and 'operator!=' to //: initialize function pointers having the appropriate signatures //: and return types for the two homogeneous, free equality- //: comparison operators defined in this component. //: (C-7..10, 12..13) //: //: 2 Using the table-driven technique, specify a set of distinct //: object values (one per row) in terms of their attributes. //: //: 4 For each row 'R1' in the table of P-2: (C-1..6) //: //: 1 Create a single object, and use it to verify the reflexive //: (anti-reflexive) property of equality (inequality) in the //: presence of aliasing. (C-2..3) //: //: 2 Verify that no memory is ever allocated after object //: construction. (C-11) //: //: 3 For each row 'R2' in the table of P-2: (C-1, 4..6) //: //: 1 Record, in 'EXP', whether or not distinct objects created //: from 'R1' and 'R2', respectively, are expected to have the //: same value. //: //: 2 Create an object 'X' having the value of 'R1'. Create //: another object 'Y' having the value of 'R2'. //: //: 3 Verify the commutativity property and the expected return //: value for both '==' and '!='. (C-1, 4..6) //: //: 4 Verify that no memory is ever allocated after object //: construction. (C-11) // // Testing: // bool operator==(lhs, rhs); // bool operator!=(lhs, rhs); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING EQUALITY-COMPARISON OPERATORS" "\n=====================================\n"); if (verbose) printf("\nAssign the address of each operator to a variable.\n"); { typedef bool (*operatorPtr)(const Obj&, const Obj&); // Verify that the signatures and return types are standard. operatorPtr operatorEq = operator==; operatorPtr operatorNe = operator!=; (void) operatorEq; // quash potential compiler warnings (void) operatorNe; } // Create a test allocator and install it as the default. bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); const int NUM_VALUES = DEFAULT_NUM_VALUES; const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES; for (int ti = 0; ti < NUM_VALUES; ++ti) { const int LINE1 = VALUES[ti].d_line; const int DATA1 = VALUES[ti].d_data; if (veryVerbose) { T_ P_(LINE1) P(DATA1) } Obj mX(DATA1); const Obj& X = mX; bslma::TestAllocatorMonitor tam(&da); // Ensure an object compares correctly with itself (alias test). ASSERTV(X.data(), X == X); ASSERTV(X.data(), !(X != X)); ASSERT(tam.isTotalSame()); for (int tj = 0; tj < NUM_VALUES; ++tj) { const int LINE2 = VALUES[tj].d_line; const int DATA2 = VALUES[tj].d_data; bool EXP = ti == tj; if (veryVerbose) { T_ T_ P_(LINE2) P_(DATA2) P(EXP) } Obj mY(DATA2); const Obj& Y = mY; bslma::TestAllocatorMonitor tam(&da); // Verify value, commutativity ASSERTV(X.data(), Y.data(), EXP == (X == Y)); ASSERTV(X.data(), Y.data(), EXP == (Y == X)); ASSERTV(X.data(), Y.data(), !EXP == (X != Y)); ASSERTV(X.data(), Y.data(), !EXP == (Y != X)); ASSERT(tam.isTotalSame()); } } } break; case 5: { // -------------------------------------------------------------------- // TESTING PRINT AND OUTPUT OPERATOR // N/A // -------------------------------------------------------------------- if (verbose) printf("\nTESTING PRINT AND OUTPUT OPERATOR" "\n=================================\n"); if (verbose) printf("\nOperations not supported for this type.\n"); } break; case 4: { // -------------------------------------------------------------------- // TESTING BASIC ACCESSORS // Ensure each basic accessor properly interprets object state. // // Concerns: //: 1 Each accessor returns the value of the corresponding attribute //: of the object. //: //: 2 Each accessor method is declared 'const'. //: //: 3 No accessor allocates any memory. // // Plan: //: 1 Use the default constructor, create an object having default //: attribute values. Verify that the accessor for the 'data' //: attribute invoked on a reference providing non-modifiable access //: to the object return the expected value. (C-1) //: //: 2 Set the 'data' attribute of the object to another value. Verify //: that the accessor for the 'data' attribute invoked on a reference //: providing non-modifiable access to the object return the expected //: value. (C-1, 2) //: //: 3 Verify that no memory is ever allocated after default //: construction. (C-3) // // Testing: // int data() const; // bslma::Allocator *allocator() const; // -------------------------------------------------------------------- if (verbose) printf("\nTESTING BASIC ACCESSORS" "\n=======================\n"); bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj mX; const Obj& X = mX; bslma::TestAllocatorMonitor tam(&da); ASSERTV(X.data(), 0 == X.data()); mX.setData(1); ASSERTV(X.data(), 1 == X.data()); ASSERT(X.allocator() == &da); ASSERT(tam.isTotalSame()); } break; case 3: { // -------------------------------------------------------------------- // TESTING VALUE CONSTRUCTOR // Ensure that we can put an object into any initial state relevant // for thorough testing. // // Concerns: //: 1 The value constructor can create an object having any value that //: does not violate the documented constraints. //: //: 2 If an allocator is NOT supplied to the value constructor, the //: default allocator in effect at the time of construction becomes //: the object allocator for the resulting object. //: //: 3 If an allocator IS supplied to the value constructor, that //: allocator becomes the object allocator for the resulting object. //: //: 4 Supplying a null allocator address has the same effect as not //: supplying an allocator. //: //: 5 Supplying an allocator to the value constructor has no effect //: on subsequent object values. //: //: 6 Any memory allocation is from the object allocator. //: //: 7 There is no temporary memory allocation from any allocator. //: //: 8 Every object releases any allocated memory at destruction. //: //: 9 Any memory allocation is exception neutral. // // Plan: //: 1 Using the table-driven technique, specify a set of distinct //: object values (one per row) in terms of their attributes. //: //: 2 For each row (representing a distinct object value, 'V') in the //: table of P-1: //: //: 1 Execute an inner loop creating three distinct objects, in turn, //: each object having the same value of 'R1', but configured //: differently: (a) without passing an allocator, (b) passing a //: null allocator address explicitly, and (c) passing the address //: of a test allocator distinct from the default allocator. //: //: 1 Create three 'bslma::TestAllocator' objects, and install one //: as the current default allocator (note that a ubiquitous test //: allocator is already installed as the global allocator). //: //: 2 Use the value constructor to dynamically create an object //: having the value 'V' in the presence of injected exceptions //: (using the 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros) //: with its object allocator configured appropriately (see //: P-2.1); use a distinct test allocator for the object's //: footprint. (C-9) //: //: 3 Use the (as yet unproven) salient attribute accessors to //: verify that all of the attributes of each object have their //: expected values. (C-1, 5) //: //: 4 Use the 'allocator' accessor of each underlying attribute //: capable of allocating memory to ensure that its object //: allocator is properly installed; also invoke the (as yet //: unproven) 'allocator' accessor of the object under test. //: (C-6) //: //: 5 Use the appropriate test allocators to verify that: //: (C-2..4, 7..8) //: //: 1 An object that IS expected to allocate memory does so //: from the object allocator only (irrespective of the //: specific number of allocations or the total amount of //: memory allocated). (C-2..4) //: //: 4 No temporary memory is allocated from the object allocator. //: (C-7) //: //: 5 All object memory is released when the object is destroyed. //: (C-8) // // Testing: // Obj(int data, bslma::Allocator *bA = 0); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING VALUE CONSTRUCTOR" "\n=========================\n"); const int NUM_VALUES = DEFAULT_NUM_VALUES; const DefaultValueRow (&VALUES)[NUM_VALUES] = DEFAULT_VALUES; for (int ti = 0; ti < NUM_VALUES; ++ti) { const int LINE = VALUES[ti].d_line; const int DATA = VALUES[ti].d_data; for (char cfg = 'a'; cfg <= 'c'; ++cfg) { const char CONFIG = cfg; // how we specify the allocator bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator fa("footprint", veryVeryVeryVerbose); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj *objPtr = 0; bslma::TestAllocator *objAllocatorPtr = 0; switch (CONFIG) { case 'a': { objAllocatorPtr = &da; } break; case 'b': { objAllocatorPtr = &da; } break; case 'c': { objAllocatorPtr = &sa; } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } return testStatus; // RETURN } bslma::TestAllocator& oa = *objAllocatorPtr; bslma::TestAllocator& noa = 'c' != CONFIG ? sa : da; BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) { if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } bslma::TestAllocatorMonitor tam(&oa); switch (CONFIG) { case 'a': { objPtr = new (fa) Obj(DATA); } break; case 'b': { objPtr = new (fa) Obj(DATA, 0); } break; case 'c': { objPtr = new (fa) Obj(DATA, &sa); } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } return testStatus; // RETURN } ASSERTV(CONFIG, tam.isInUseUp()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END; if (veryVerbose) { T_ P_(LINE) P(DATA) } ASSERTV(LINE, CONFIG, sizeof(Obj) == fa.numBytesInUse()); Obj& mX = *objPtr; const Obj& X = mX; // Verify the object's attribute values. ASSERTV(CONFIG, DATA, X.data(), DATA == X.data()); ASSERTV(CONFIG, X.movedFrom(), X.movedFrom() == MoveState::e_NOT_MOVED); ASSERTV(CONFIG, X.movedInto(), X.movedInto() == MoveState::e_NOT_MOVED); // Verify any attribute allocators are installed properly. ASSERTV(CONFIG, &oa, X.allocator(), &oa == X.allocator()); // Verify no allocation from the non-object allocators. ASSERTV(CONFIG, noa.numBlocksTotal(), 0 == noa.numBlocksTotal()); // Verify no temporary memory is allocated from the object // allocator. ASSERTV(CONFIG, oa.numBlocksTotal(), oa.numBlocksInUse(), oa.numBlocksTotal() == oa.numBlocksInUse()); // Reclaim dynamically allocated object under test. fa.deleteObject(objPtr); // Verify all memory is released on object destruction. ASSERTV(LINE, CONFIG, da.numBlocksInUse(), 0 == da.numBlocksInUse()); ASSERTV(LINE, CONFIG, fa.numBlocksInUse(), 0 == fa.numBlocksInUse()); ASSERTV(LINE, CONFIG, sa.numBlocksInUse(), 0 == sa.numBlocksInUse()); } } } break; case 2: { // -------------------------------------------------------------------- // TESTING DEFAULT CTOR & PRIMARY MANIPULATORS // Ensure that we can use the default constructor to create an object // (having the default constructed value). Also ensure that we can // use the primary manipulators to put that object into any state // relevant for thorough testing. // // Concerns: //: 1 An object created with the default constructor has the //: contractually specified default value. //: //: 2 If an allocator is NOT supplied to the default constructor, the //: default allocator in effect at the time of construction becomes //: the object allocator for the resulting object. //: //: 3 If an allocator IS supplied to the default constructor, that //: allocator becomes the object allocator for the resulting object. //: //: 4 Supplying a null allocator address has the same effect as not //: supplying an allocator. //: //: 5 Supplying an allocator to the default constructor has no effect //: on subsequent object values. //: //: 6 Any memory allocation is from the object allocator. //: //: 7 There is no temporary allocation from any allocator. //: //: 8 Every object releases any allocated memory at destruction. //: //: 9 The default constructor is exception-neutral w.r.t. memory //: allocation. //: //:10 Each attribute can be set to represent any value that does not //: violate that attribute's documented constraints. // // Plan: //: 1 Create three attribute values for the 'data' attribute 'D', 'A', //: and 'B'. 'D' should be the default value. 'A' and 'B' should be //: the boundary values. //: //: 2 Using a loop-based approach, default-construct three distinct //: objects, in turn, but configured differently: (a) without passing //: an allocator, (b) passing a null allocator address explicitly, //: and (c) passing the address of a test allocator distinct from the //: default. For each of these three iterations: //: //: 1 Create three 'bslma::TestAllocator' objects, and install one as //: as the current default allocator (note that a ubiquitous test //: allocator is already installed as the global allocator). //: //: 2 Use the default constructor to dynamically create an object 'X' //: in the presence of exception (using the //: 'BSLMA_TESTALLOCATOR_EXCEPTION_TEST_*' macros), with its object //: allocator configured appropriately (see P-2); use a distinct //: test allocator for the object's footprint. (C-9) //: //: 3 Use the 'allocator' accessor of each underlying attribute //: capable of allocating memory to ensure that its object //: allocator is properly installed; also invoke the (as yet //: unproven) 'allocator' accessor of the object under test. //: (C-2..4) //: //: 4 Use the appropriate test allocators to verify that the //: appropriate amount of memory is allocated by the default //: constructor. (C-9) //: //: 5 Use the individual (as yet unproven) salient attribute //: accessors to verify the default-constructed value. (C-1) //: //: 6 Set 'data' attribute to 'A', 'B', and 'D'. Verify that no //: memory allocation occurs. Use the individual (as yet //: unproven) salient attribute accessors to verify the attribute //: has been changed. (C-5..6) //: //: 7 Verify that no temporary memory is allocated from the object //: allocator. (C-7) //: //: 8 Verify that all object memory is released when the object is //: destroyed. (C-8) // // Testing: // Obj(bslma::Allocator *bA = 0); // ~Obj(); // void setData(int value); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING DEFAULT CTOR & PRIMARY MANIPULATORS" "\n===========================================\n"); const int D = 0; const int A = INT_MIN; const int B = INT_MAX; if (verbose) printf("\nTesting with various allocator configurations.\n"); for (char cfg = 'a'; cfg <= 'c'; ++cfg) { const char CONFIG = cfg; // how we specify the allocator bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator fa("footprint", veryVeryVeryVerbose); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj *objPtr = 0; bslma::TestAllocator *objAllocatorPtr = 0; switch (CONFIG) { case 'a': { objAllocatorPtr = &da; } break; case 'b': { objAllocatorPtr = &da; } break; case 'c': { objAllocatorPtr = &sa; } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } return testStatus; // RETURN } bslma::TestAllocator& oa = *objAllocatorPtr; bslma::TestAllocator& noa = 'c' != CONFIG ? sa : da; BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(oa) { if (veryVeryVerbose) { T_ T_ Q(ExceptionTestBody) } bslma::TestAllocatorMonitor tam(&oa); switch (CONFIG) { case 'a': { objPtr = new (fa) Obj(); } break; case 'b': { objPtr = new (fa) Obj(0); } break; case 'c': { objPtr = new (fa) Obj(&sa); } break; default: { ASSERTV(CONFIG, !"Bad allocator config."); } return testStatus; // RETURN } ASSERTV(CONFIG, tam.isInUseUp()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END; ASSERTV(CONFIG, sizeof(Obj) == fa.numBytesInUse()); Obj& mX = *objPtr; const Obj& X = mX; // Verify any attribute allocators are installed properly. ASSERTV(CONFIG, &oa, X.allocator(), &oa == X.allocator()); // Verify no allocation from the non-object allocators. ASSERTV(CONFIG, noa.numBlocksTotal(), 0 == noa.numBlocksTotal()); // Verify the object's attribute values. ASSERTV(CONFIG, D, X.data(), D == X.data()); ASSERTV(CONFIG, X.movedFrom(), X.movedFrom() == MoveState::e_NOT_MOVED); ASSERTV(CONFIG, X.movedInto(), X.movedInto() == MoveState::e_NOT_MOVED); // 'data' { bslma::TestAllocatorMonitor tam(&oa); mX.setData(A); ASSERTV(CONFIG, A == X.data()); mX.setData(B); ASSERTV(CONFIG, B == X.data()); mX.setData(D); ASSERTV(CONFIG, D == X.data()); ASSERTV(CONFIG, tam.isTotalSame()); } // Verify no temporary memory is allocated from the object // allocator. ASSERTV(CONFIG, oa.numBlocksTotal(), oa.numBlocksInUse(), oa.numBlocksTotal() == oa.numBlocksInUse()); // Reclaim dynamically allocated object under test. fa.deleteObject(objPtr); // Verify all memory is released on object destruction. ASSERTV(fa.numBlocksInUse(), 0 == fa.numBlocksInUse()); ASSERTV(oa.numBlocksInUse(), 0 == oa.numBlocksInUse()); ASSERTV(noa.numBlocksTotal(), 0 == noa.numBlocksTotal()); // Double check that some object memory was allocated. ASSERTV(CONFIG, 1 <= oa.numBlocksTotal()); } } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This case exercises (but does not fully test) basic functionality. // // Concerns: //: 1 The class is sufficiently functional to enable comprehensive //: testing in subsequent test cases. // // Plan: //: 1 Perform and ad-hoc test of the primary modifiers and accessors. // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) printf("\nBREATHING TEST" "\n==============\n"); Obj X; ASSERT(X.data() == 0); X.setData(1); ASSERT(X.data() == 1); Obj Y(2); ASSERT(Y.data() == 2); Obj Z(bslmf::MovableRefUtil::move(Y)); ASSERT(Z != Y); ASSERT(Z.data() == 2); ASSERT(Y.data() == 0); ASSERT(X != Y); ASSERT(bsltf::MoveState::e_MOVED == Y.movedFrom()); ASSERT(bsltf::MoveState::e_NOT_MOVED == Y.movedInto()); ASSERT(bsltf::MoveState::e_NOT_MOVED == Z.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == Z.movedInto()); Obj ZZ(bslmf::MovableRefUtil::move(Y)); ASSERT(Z != Y); ASSERT(ZZ.data() == 0); ASSERT(Y.data() == 0); ASSERT(X != Y); ASSERT(bsltf::MoveState::e_MOVED == Y.movedFrom()); ASSERT(bsltf::MoveState::e_NOT_MOVED == Y.movedInto()); ASSERT(bsltf::MoveState::e_MOVED == ZZ.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == ZZ.movedInto()); X = bslmf::MovableRefUtil::move(Z); ASSERT(Z != X); ASSERT(Z == Y); ASSERT(X.data() == 2); ASSERT(Z.data() == 0); ASSERT(bsltf::MoveState::e_MOVED == Z.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == Z.movedInto()); ASSERT(bsltf::MoveState::e_NOT_MOVED == X.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == X.movedInto()); ZZ.setData(3); ZZ = bslmf::MovableRefUtil::move(Z); ASSERTV(ZZ.data(), X.data(), ZZ != X); ASSERT(ZZ == Z); ASSERT(ZZ.data() == 0); ASSERT(bsltf::MoveState::e_MOVED == Z.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == Z.movedInto()); ASSERT(bsltf::MoveState::e_MOVED == ZZ.movedFrom()); ASSERT(bsltf::MoveState::e_MOVED == ZZ.movedInto()); } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } // CONCERN: In no case does memory come from the global allocator. LOOP_ASSERT(globalAllocator.numBlocksTotal(), 0 == globalAllocator.numBlocksTotal()); if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
40.868962
79
0.489218
[ "object" ]
dc87bd8a45fe090cb2b054e496326204df7ecabc
708
cpp
C++
1-7-1Lect.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-7-1Lect.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-7-1Lect.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
// // Created by grey on 17.10.2019. // #include <iostream> #include <vector> using namespace std; void foo_1_7_1Lect(){ int n; cin >> n; vector <int> a; //input for (int i = 0; i < n; i++) { int temp; cin >> temp; if (temp > 0){ a.push_back(temp); } } //processing for (int j = 0; j < n; j++) { int num_min = j; for (int i = j; i < a.size(); i++) { if (a[i] < a[num_min]) { num_min = i; } } int temp; temp = a[j]; a[j] = a[num_min]; a[num_min] = temp; } //output for (auto now : a){ cout << now << " "; } }
17.7
44
0.39548
[ "vector" ]
dc8833c169387d09f179aec3079db78d16ce7b8b
560,697
cpp
C++
alglib_3_17_0_cpp/tests/test_i.cpp
TimJonesB/wesad-live
c708e5f8e4648d029bc72e4c1bd9446d0a1231b7
[ "MIT" ]
null
null
null
alglib_3_17_0_cpp/tests/test_i.cpp
TimJonesB/wesad-live
c708e5f8e4648d029bc72e4c1bd9446d0a1231b7
[ "MIT" ]
null
null
null
alglib_3_17_0_cpp/tests/test_i.cpp
TimJonesB/wesad-live
c708e5f8e4648d029bc72e4c1bd9446d0a1231b7
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <math.h> #include "alglibinternal.h" #include "alglibmisc.h" #include "diffequations.h" #include "linalg.h" #include "optimization.h" #include "solvers.h" #include "statistics.h" #include "dataanalysis.h" #include "specialfunctions.h" #include "integration.h" #include "fasttransforms.h" #include "interpolation.h" using namespace alglib; bool doc_test_bool(bool v, bool t) { return (v && t) || (!v && !t); } bool doc_test_int(ae_int_t v, ae_int_t t) { return v==t; } bool doc_test_real(double v, double t, double _threshold) { double s = _threshold>=0 ? 1.0 : fabs(t); double threshold = fabs(_threshold); return fabs(v-t)/s<=threshold; } bool doc_test_complex(alglib::complex v, alglib::complex t, double _threshold) { double s = _threshold>=0 ? 1.0 : alglib::abscomplex(t); double threshold = fabs(_threshold); return abscomplex(v-t)/s<=threshold; } bool doc_test_bool_vector(const boolean_1d_array &v, const boolean_1d_array &t) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i<v.length(); i++) if( v(i)!=t(i) ) return false; return true; } bool doc_test_bool_matrix(const boolean_2d_array &v, const boolean_2d_array &t) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i<v.rows(); i++) for(j=0; j<v.cols(); j++) if( v(i,j)!=t(i,j) ) return false; return true; } bool doc_test_int_vector(const integer_1d_array &v, const integer_1d_array &t) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i<v.length(); i++) if( v(i)!=t(i) ) return false; return true; } bool doc_test_int_matrix(const integer_2d_array &v, const integer_2d_array &t) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i<v.rows(); i++) for(j=0; j<v.cols(); j++) if( v(i,j)!=t(i,j) ) return false; return true; } bool doc_test_real_vector(const real_1d_array &v, const real_1d_array &t, double _threshold) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i<v.length(); i++) { double s = _threshold>=0 ? 1.0 : fabs(t(i)); double threshold = fabs(_threshold); if( fabs(v(i)-t(i))/s>threshold ) return false; } return true; } bool doc_test_real_matrix(const real_2d_array &v, const real_2d_array &t, double _threshold) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i<v.rows(); i++) for(j=0; j<v.cols(); j++) { double s = _threshold>=0 ? 1.0 : fabs(t(i,j)); double threshold = fabs(_threshold); if( fabs(v(i,j)-t(i,j))/s>threshold ) return false; } return true; } bool doc_test_complex_vector(const complex_1d_array &v, const complex_1d_array &t, double _threshold) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i<v.length(); i++) { double s = _threshold>=0 ? 1.0 : alglib::abscomplex(t(i)); double threshold = fabs(_threshold); if( abscomplex(v(i)-t(i))/s>threshold ) return false; } return true; } bool doc_test_complex_matrix(const complex_2d_array &v, const complex_2d_array &t, double _threshold) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i<v.rows(); i++) for(j=0; j<v.cols(); j++) { double s = _threshold>=0 ? 1.0 : alglib::abscomplex(t(i,j)); double threshold = fabs(_threshold); if( abscomplex(v(i,j)-t(i,j))/s>threshold ) return false; } return true; } template<class T> void spoil_vector_by_adding_element(T &x) { ae_int_t i; T y = x; x.setlength(y.length()+1); for(i=0; i<y.length(); i++) x(i) = y(i); x(y.length()) = 0; } template<class T> void spoil_vector_by_deleting_element(T &x) { ae_int_t i; T y = x; x.setlength(y.length()-1); for(i=0; i<y.length()-1; i++) x(i) = y(i); } template<class T> void spoil_matrix_by_adding_row(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows()+1, y.cols()); for(i=0; i<y.rows(); i++) for(j=0; j<y.cols(); j++) x(i,j) = y(i,j); for(j=0; j<y.cols(); j++) x(y.rows(),j) = 0; } template<class T> void spoil_matrix_by_deleting_row(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows()-1, y.cols()); for(i=0; i<y.rows()-1; i++) for(j=0; j<y.cols(); j++) x(i,j) = y(i,j); } template<class T> void spoil_matrix_by_adding_col(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows(), y.cols()+1); for(i=0; i<y.rows(); i++) for(j=0; j<y.cols(); j++) x(i,j) = y(i,j); for(i=0; i<y.rows(); i++) x(i,y.cols()) = 0; } template<class T> void spoil_matrix_by_deleting_col(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows(), y.cols()-1); for(i=0; i<y.rows(); i++) for(j=0; j<y.cols()-1; j++) x(i,j) = y(i,j); } template<class T> void spoil_vector_by_nan(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_nan; } template<class T> void spoil_vector_by_posinf(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_posinf; } template<class T> void spoil_vector_by_neginf(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_neginf; } template<class T> void spoil_matrix_by_nan(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_nan; } template<class T> void spoil_matrix_by_posinf(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_posinf; } template<class T> void spoil_matrix_by_neginf(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_neginf; } void function1_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); } void function1_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // and its derivatives df/d0 and df/dx1 // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 400*pow(x[0]+3,3); grad[1] = 4*pow(x[1]-3,3); } void function1_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // its derivatives df/d0 and df/dx1 // and its Hessian. // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 400*pow(x[0]+3,3); grad[1] = 4*pow(x[1]-3,3); hess[0][0] = 1200*pow(x[0]+3,2); hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 12*pow(x[1]-3,2); } void function1_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // f0(x0,x1) = 100*(x0+3)^4, // f1(x0,x1) = (x1-3)^4 // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); } void function1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // f0(x0,x1) = 100*(x0+3)^4, // f1(x0,x1) = (x1-3)^4 // and Jacobian matrix J = [dfi/dxj] // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); jac[0][0] = 20*(x[0]+3); jac[0][1] = 0; jac[1][0] = 0; jac[1][1] = 2*(x[1]-3); } void function2_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); } void function2_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // and its derivatives df/d0 and df/dx1 // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); grad[0] = 4*(x[0]*x[0]+1)*x[0]; grad[1] = 2*(x[1]-1); } void function2_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // its gradient and Hessian // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); grad[0] = 4*(x[0]*x[0]+1)*x[0]; grad[1] = 2*(x[1]-1); hess[0][0] = 12*x[0]*x[0]+4; hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 2; } void function2_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // f0(x0,x1) = x0^2+1 // f1(x0,x1) = x1-1 // fi[0] = x[0]*x[0]+1; fi[1] = x[1]-1; } void function2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // f0(x0,x1) = x0^2+1 // f1(x0,x1) = x1-1 // and Jacobian matrix J = [dfi/dxj] // fi[0] = x[0]*x[0]+1; fi[1] = x[1]-1; jac[0][0] = 2*x[0]; jac[0][1] = 0; jac[1][0] = 0; jac[1][1] = 1; } void nlcfunc1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1) = -x0+x1 // f1(x0,x1) = x0^2+x1^2-1 // // and Jacobian matrix J = [dfi/dxj] // fi[0] = -x[0]+x[1]; fi[1] = x[0]*x[0] + x[1]*x[1] - 1.0; jac[0][0] = -1.0; jac[0][1] = +1.0; jac[1][0] = 2*x[0]; jac[1][1] = 2*x[1]; } void nlcfunc2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1,x2) = x0+x1 // f1(x0,x1,x2) = x2-exp(x0) // f2(x0,x1,x2) = x0^2+x1^2-1 // // and Jacobian matrix J = [dfi/dxj] // fi[0] = x[0]+x[1]; fi[1] = x[2]-exp(x[0]); fi[2] = x[0]*x[0] + x[1]*x[1] - 1.0; jac[0][0] = 1.0; jac[0][1] = 1.0; jac[0][2] = 0.0; jac[1][0] = -exp(x[0]); jac[1][1] = 0.0; jac[1][2] = 1.0; jac[2][0] = 2*x[0]; jac[2][1] = 2*x[1]; jac[2][2] = 0.0; } void nsfunc1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1) = 2*|x0|+x1 // // and Jacobian matrix J = [df0/dx0 df0/dx1] // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); jac[0][0] = 2*alglib::sign(x[0]); jac[0][1] = alglib::sign(x[1]); } void nsfunc1_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // // f0(x0,x1) = 2*|x0|+x1 // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); } void nsfunc2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates function vector // // f0(x0,x1) = 2*|x0|+x1 // f1(x0,x1) = x0-1 // f2(x0,x1) = -x1-1 // // and Jacobian matrix J // // [ df0/dx0 df0/dx1 ] // J = [ df1/dx0 df1/dx1 ] // [ df2/dx0 df2/dx1 ] // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); jac[0][0] = 2*alglib::sign(x[0]); jac[0][1] = alglib::sign(x[1]); fi[1] = x[0]-1; jac[1][0] = 1; jac[1][1] = 0; fi[2] = -x[1]-1; jac[2][0] = 0; jac[2][1] = -1; } void bad_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); } void bad_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 40*pow(x[0]+3,3); grad[1] = 40*pow(x[1]-3,3); } void bad_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 40*pow(x[0]+3,3); grad[1] = 40*pow(x[1]-3,3); hess[0][0] = 120*pow(x[0]+3,2); hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 120*pow(x[1]-3,2); } void bad_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); } void bad_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); jac[0][0] = 2*(x[0]+3); jac[0][1] = 1; jac[1][0] = 0; jac[1][1] = 20*(x[1]-3); } void function_cx_1_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)) // where x is a position on X-axis and c is adjustable parameter func = exp(-c[0]*pow(x[0],2)); } void function_cx_1_grad(const real_1d_array &c, const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)) and gradient G={df/dc[i]} // where x is a position on X-axis and c is adjustable parameter. // IMPORTANT: gradient is calculated with respect to C, not to X func = exp(-c[0]*pow(x[0],2)); grad[0] = -pow(x[0],2)*func; } void function_cx_1_hess(const real_1d_array &c, const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)), gradient G={df/dc[i]} and Hessian H={d2f/(dc[i]*dc[j])} // where x is a position on X-axis and c is adjustable parameter. // IMPORTANT: gradient/Hessian are calculated with respect to C, not to X func = exp(-c[0]*pow(x[0],2)); grad[0] = -pow(x[0],2)*func; hess[0][0] = pow(x[0],4)*func; } void ode_function_1_diff(const real_1d_array &y, double x, real_1d_array &dy, void *ptr) { // this callback calculates f(y[],x)=-y[0] dy[0] = -y[0]; } void int_function_1_func(double x, double xminusa, double bminusx, double &y, void *ptr) { // this callback calculates f(x)=exp(x) y = exp(x); } void function_debt_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(c,x)=c[0]*(1+c[1]*(pow(x[0]-1999,c[2])-1)) // func = c[0]*(1+c[1]*(pow(x[0]-1999,c[2])-1)); } void s1_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x) = (1+x)^(-0.2) + (1-x)^(-0.3) + 1000*x and its gradient. // // function is trimmed when we calculate it near the singular points or outside of the [-1,+1]. // Note that we do NOT calculate gradient in this case. // if( (x[0]<=-0.999999999999) || (x[0]>=+0.999999999999) ) { func = 1.0E+300; return; } func = pow(1+x[0],-0.2) + pow(1-x[0],-0.3) + 1000*x[0]; grad[0] = -0.2*pow(1+x[0],-1.2) +0.3*pow(1-x[0],-1.3) + 1000; } int main() { bool _TotalResult = true; bool _TestResult; int _spoil_scenario; printf("C++ tests. Please wait...\n"); #if AE_MALLOC==AE_BASIC_STATIC_MALLOC const ae_int_t _static_pool_size = 1000000; ae_int_t _static_pool_used = 0, _static_pool_free = 0; void *_static_pool = malloc(_static_pool_size); alglib_impl::set_memory_pool(_static_pool, _static_pool_size); alglib_impl::memory_pool_stats(&_static_pool_used, &_static_pool_free); if( _static_pool_used!=0 || _static_pool_free<0.95*_static_pool_size || _static_pool_free>_static_pool_size ) { _TotalResult = false; printf("FAILURE: memory pool usage stats are inconsistent!\n"); return 1; } { alglib::real_2d_array a("[[1,2],[3,4]]"); ae_int_t _static_pool_used2 = 0, _static_pool_free2 = 0; alglib_impl::memory_pool_stats(&_static_pool_used2, &_static_pool_free2); if( _static_pool_used2<=_static_pool_used || _static_pool_free2>=_static_pool_free || _static_pool_used+_static_pool_free!=_static_pool_used2+_static_pool_free2 ) { _TotalResult = false; printf("FAILURE: memory pool usage stats are inconsistent!\n"); return 1; } a.setlength(1,1); // make sure that destructor of /a/ is never called prior to this point } #endif #ifdef AE_USE_ALLOC_COUNTER printf("Allocation counter activated...\n"); alglib_impl::_use_alloc_counter = ae_true; if( alglib_impl::_alloc_counter!=0 ) { _TotalResult = false; printf("FAILURE: alloc_counter is non-zero on start!\n"); } { { alglib::real_1d_array x; x.setlength(1); if( alglib_impl::_alloc_counter==0 ) printf(":::: WARNING: ALLOC_COUNTER IS INACTIVE!!! :::::\n"); } if( alglib_impl::_alloc_counter!=0 ) { printf("FAILURE: alloc_counter does not decrease!\n"); return 1; } } #endif try { // // TEST nneighbor_d_1 // Nearest neighbor search, KNN queries // printf("0/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt; real_1d_array x; real_2d_array r = "[[]]"; ae_int_t k; kdtreebuild(a, nx, ny, normtype, kdt); x = "[-1,0]"; k = kdtreequeryknn(kdt, x, 1); _TestResult = _TestResult && doc_test_int(k, 1); kdtreequeryresultsx(kdt, r); _TestResult = _TestResult && doc_test_real_matrix(r, "[[0,0]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nneighbor_t_2 // Subsequent queries; buffered functions must use previously allocated storage (if large enough), so buffer may contain some info from previous call // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt; real_1d_array x; real_2d_array rx = "[[]]"; ae_int_t k; kdtreebuild(a, nx, ny, normtype, kdt); x = "[+2,0]"; k = kdtreequeryknn(kdt, x, 2, true); _TestResult = _TestResult && doc_test_int(k, 2); kdtreequeryresultsx(kdt, rx); _TestResult = _TestResult && doc_test_real_matrix(rx, "[[1,0],[1,1]]", 0.05); x = "[-2,0]"; k = kdtreequeryknn(kdt, x, 1, true); _TestResult = _TestResult && doc_test_int(k, 1); kdtreequeryresultsx(kdt, rx); _TestResult = _TestResult && doc_test_real_matrix(rx, "[[0,0],[1,1]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nneighbor_d_2 // Serialization of KD-trees // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt0; kdtree kdt1; std::string s; real_1d_array x; real_2d_array r0 = "[[]]"; real_2d_array r1 = "[[]]"; // // Build tree and serialize it // kdtreebuild(a, nx, ny, normtype, kdt0); alglib::kdtreeserialize(kdt0, s); alglib::kdtreeunserialize(s, kdt1); // // Compare results from KNN queries // x = "[-1,0]"; kdtreequeryknn(kdt0, x, 1); kdtreequeryresultsx(kdt0, r0); kdtreequeryknn(kdt1, x, 1); kdtreequeryresultsx(kdt1, r1); _TestResult = _TestResult && doc_test_real_matrix(r0, "[[0,0]]", 0.05); _TestResult = _TestResult && doc_test_real_matrix(r1, "[[0,0]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST odesolver_d1 // Solving y'=-y with ODE solver // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<13; _spoil_scenario++) { try { real_1d_array y = "[1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); real_1d_array x = "[0, 1, 2, 3]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(x); if( _spoil_scenario==5 ) spoil_vector_by_posinf(x); if( _spoil_scenario==6 ) spoil_vector_by_neginf(x); double eps = 0.00001; if( _spoil_scenario==7 ) eps = fp_nan; if( _spoil_scenario==8 ) eps = fp_posinf; if( _spoil_scenario==9 ) eps = fp_neginf; double h = 0; if( _spoil_scenario==10 ) h = fp_nan; if( _spoil_scenario==11 ) h = fp_posinf; if( _spoil_scenario==12 ) h = fp_neginf; odesolverstate s; ae_int_t m; real_1d_array xtbl; real_2d_array ytbl; odesolverreport rep; odesolverrkck(y, x, eps, h, s); alglib::odesolversolve(s, ode_function_1_diff); odesolverresults(s, m, xtbl, ytbl, rep); _TestResult = _TestResult && doc_test_int(m, 4); _TestResult = _TestResult && doc_test_real_vector(xtbl, "[0, 1, 2, 3]", 0.005); _TestResult = _TestResult && doc_test_real_matrix(ytbl, "[[1], [0.367], [0.135], [0.050]]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "odesolver_d1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST sparse_d_1 // Basic operations with sparse matrices // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<1; _spoil_scenario++) { try { // // This example demonstrates creation/initialization of the sparse matrix // and matrix-vector multiplication. // // First, we have to create matrix and initialize it. Matrix is initially created // in the Hash-Table format, which allows convenient initialization. We can modify // Hash-Table matrix with sparseset() and sparseadd() functions. // // NOTE: Unlike CRS format, Hash-Table representation allows you to initialize // elements in the arbitrary order. You may see that we initialize a[0][0] first, // then move to the second row, and then move back to the first row. // sparsematrix s; sparsecreate(2, 2, s); sparseset(s, 0, 0, 2.0); sparseset(s, 1, 1, 1.0); sparseset(s, 0, 1, 1.0); sparseadd(s, 1, 1, 4.0); // // Now S is equal to // [ 2 1 ] // [ 5 ] // Lets check it by reading matrix contents with sparseget(). // You may see that with sparseget() you may read both non-zero // and zero elements. // double v; v = sparseget(s, 0, 0); _TestResult = _TestResult && doc_test_real(v, 2.0000, 0.005); v = sparseget(s, 0, 1); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.005); v = sparseget(s, 1, 0); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.005); v = sparseget(s, 1, 1); _TestResult = _TestResult && doc_test_real(v, 5.0000, 0.005); // // After successful creation we can use our matrix for linear operations. // // However, there is one more thing we MUST do before using S in linear // operations: we have to convert it from HashTable representation (used for // initialization and dynamic operations) to CRS format with sparseconverttocrs() // call. If you omit this call, ALGLIB will generate exception on the first // attempt to use S in linear operations. // sparseconverttocrs(s); // // Now S is in the CRS format and we are ready to do linear operations. // Lets calculate A*x for some x. // real_1d_array x = "[1,-1]"; if( _spoil_scenario==0 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[]"; sparsemv(s, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,-5.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "sparse_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST sparse_d_crs // Advanced topic: creation in the CRS format. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<2; _spoil_scenario++) { try { // // This example demonstrates creation/initialization of the sparse matrix in the // CRS format. // // Hash-Table format used by default is very convenient (it allows easy // insertion of elements, automatic memory reallocation), but has // significant memory and performance overhead. Insertion of one element // costs hundreds of CPU cycles, and memory consumption is several times // higher than that of CRS. // // When you work with really large matrices and when you can tell in // advance how many elements EXACTLY you need, it can be beneficial to // create matrix in the CRS format from the very beginning. // // If you want to create matrix in the CRS format, you should: // * use sparsecreatecrs() function // * know row sizes in advance (number of non-zero entries in the each row) // * initialize matrix with sparseset() - another function, sparseadd(), is not allowed // * initialize elements from left to right, from top to bottom, each // element is initialized only once. // sparsematrix s; integer_1d_array row_sizes = "[2,2,2,1]"; if( _spoil_scenario==0 ) spoil_vector_by_deleting_element(row_sizes); sparsecreatecrs(4, 4, row_sizes, s); sparseset(s, 0, 0, 2.0); sparseset(s, 0, 1, 1.0); sparseset(s, 1, 1, 4.0); sparseset(s, 1, 2, 2.0); sparseset(s, 2, 2, 3.0); sparseset(s, 2, 3, 1.0); sparseset(s, 3, 3, 9.0); // // Now S is equal to // [ 2 1 ] // [ 4 2 ] // [ 3 1 ] // [ 9 ] // // We should point that we have initialized S elements from left to right, // from top to bottom. CRS representation does NOT allow you to do so in // the different order. Try to change order of the sparseset() calls above, // and you will see that your program generates exception. // // We can check it by reading matrix contents with sparseget(). // However, you should remember that sparseget() is inefficient on // CRS matrices (it may have to pass through all elements of the row // until it finds element you need). // double v; v = sparseget(s, 0, 0); _TestResult = _TestResult && doc_test_real(v, 2.0000, 0.005); v = sparseget(s, 2, 3); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.005); // you may see that you can read zero elements (which are not stored) with sparseget() v = sparseget(s, 3, 2); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.005); // // After successful creation we can use our matrix for linear operations. // Lets calculate A*x for some x. // real_1d_array x = "[1,-1,1,-1]"; if( _spoil_scenario==1 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[]"; sparsemv(s, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,-2.000,2.000,-9]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "sparse_d_crs"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_d_gemm // Matrix multiplication (single-threaded) // _TestResult = true; try { real_2d_array a = "[[2,1],[1,3]]"; real_2d_array b = "[[2,1],[0,1]]"; real_2d_array c = "[[0,0],[0,0]]"; // // rmatrixgemm() function allows us to calculate matrix product C:=A*B or // to perform more general operation, C:=alpha*op1(A)*op2(B)+beta*C, // where A, B, C are rectangular matrices, op(X) can be X or X^T, // alpha and beta are scalars. // // This function: // * can apply transposition and/or multiplication by scalar to operands // * can use arbitrary part of matrices A/B (given by submatrix offset) // * can store result into arbitrary part of C // * for performance reasons requires C to be preallocated // // Parameters of this function are: // * M, N, K - sizes of op1(A) (which is MxK), op2(B) (which // is KxN) and C (which is MxN) // * Alpha - coefficient before A*B // * A, IA, JA - matrix A and offset of the submatrix // * OpTypeA - transformation type: // 0 - no transformation // 1 - transposition // * B, IB, JB - matrix B and offset of the submatrix // * OpTypeB - transformation type: // 0 - no transformation // 1 - transposition // * Beta - coefficient before C // * C, IC, JC - preallocated matrix C and offset of the submatrix // // Below we perform simple product C:=A*B (alpha=1, beta=0) // // IMPORTANT: this function works with preallocated C, which must be large // enough to store multiplication result. // ae_int_t m = 2; ae_int_t n = 2; ae_int_t k = 2; double alpha = 1.0; ae_int_t ia = 0; ae_int_t ja = 0; ae_int_t optypea = 0; ae_int_t ib = 0; ae_int_t jb = 0; ae_int_t optypeb = 0; double beta = 0.0; ae_int_t ic = 0; ae_int_t jc = 0; rmatrixgemm(m, n, k, alpha, a, ia, ja, optypea, b, ib, jb, optypeb, beta, c, ic, jc); _TestResult = _TestResult && doc_test_real_matrix(c, "[[4,3],[2,4]]", 0.0001); // // Now we try to apply some simple transformation to operands: C:=A*B^T // optypeb = 1; rmatrixgemm(m, n, k, alpha, a, ia, ja, optypea, b, ib, jb, optypeb, beta, c, ic, jc); _TestResult = _TestResult && doc_test_real_matrix(c, "[[5,1],[5,3]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_d_gemm"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_d_syrk // Symmetric rank-K update (single-threaded) // _TestResult = true; try { // // rmatrixsyrk() function allows us to calculate symmetric rank-K update // C := beta*C + alpha*A'*A, where C is square N*N matrix, A is square K*N // matrix, alpha and beta are scalars. It is also possible to update by // adding A*A' instead of A'*A. // // Parameters of this function are: // * N, K - matrix size // * Alpha - coefficient before A // * A, IA, JA - matrix and submatrix offsets // * OpTypeA - multiplication type: // * 0 - A*A^T is calculated // * 2 - A^T*A is calculated // * Beta - coefficient before C // * C, IC, JC - preallocated input/output matrix and submatrix offsets // * IsUpper - whether upper or lower triangle of C is updated; // this function updates only one half of C, leaving // other half unchanged (not referenced at all). // // Below we will show how to calculate simple product C:=A'*A // // NOTE: beta=0 and we do not use previous value of C, but still it // MUST be preallocated. // ae_int_t n = 2; ae_int_t k = 1; double alpha = 1.0; ae_int_t ia = 0; ae_int_t ja = 0; ae_int_t optypea = 2; double beta = 0.0; ae_int_t ic = 0; ae_int_t jc = 0; bool isupper = true; real_2d_array a = "[[1,2]]"; // preallocate space to store result real_2d_array c = "[[0,0],[0,0]]"; // calculate product, store result into upper part of c rmatrixsyrk(n, k, alpha, a, ia, ja, optypea, beta, c, ic, jc, isupper); // output result. // IMPORTANT: lower triangle of C was NOT updated! _TestResult = _TestResult && doc_test_real_matrix(c, "[[1,2],[0,4]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_d_syrk"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_t_complex // Basis test for complex matrix functions (correctness and presence of SMP support) // _TestResult = true; try { complex_2d_array a; complex_2d_array b; complex_2d_array c; // test cmatrixgemm() a = "[[2i,1i],[1,3]]"; b = "[[2,1],[0,1]]"; c = "[[0,0],[0,0]]"; cmatrixgemm(2, 2, 2, 1.0, a, 0, 0, 0, b, 0, 0, 0, 0.0, c, 0, 0); _TestResult = _TestResult && doc_test_complex_matrix(c, "[[4i,3i],[2,4]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_t_complex"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_r1 // Real matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { real_2d_array a = "[[1,-1],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; rmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_matrix(a, "[[0.5,0.5],[-0.5,0.5]]", 0.00005); _TestResult = _TestResult && doc_test_real(rep.r1, 0.5, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.5, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_r1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_c1 // Complex matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { complex_2d_array a = "[[1i,-1],[1i,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; cmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_complex_matrix(a, "[[-0.5i,-0.5i],[-0.5,0.5]]", 0.00005); _TestResult = _TestResult && doc_test_real(rep.r1, 0.5, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.5, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_c1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_spd1 // SPD matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { real_2d_array a = "[[2,1],[1,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; spdmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_matrix(a, "[[0.666666,-0.333333],[-0.333333,0.666666]]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_spd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_hpd1 // HPD matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { complex_2d_array a = "[[2,1],[1,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; hpdmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_complex_matrix(a, "[[0.666666,-0.333333],[-0.333333,0.666666]]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_hpd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_t_r1 // Real matrix inverse: singular matrix // _TestResult = true; try { real_2d_array a = "[[1,-1],[-2,2]]"; ae_int_t info; matinvreport rep; rmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, -3); _TestResult = _TestResult && doc_test_real(rep.r1, 0.0, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.0, 0.00005); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_t_r1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_t_c1 // Complex matrix inverse: singular matrix // _TestResult = true; try { complex_2d_array a = "[[1i,-1i],[-2,2]]"; ae_int_t info; matinvreport rep; cmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, -3); _TestResult = _TestResult && doc_test_real(rep.r1, 0.0, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.0, 0.00005); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_t_c1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_e_spd1 // Attempt to use SPD function on nonsymmetrix matrix // _TestResult = true; try { real_2d_array a = "[[1,0],[1,1]]"; ae_int_t info; matinvreport rep; spdmatrixinverse(a, info, rep); _TestResult = false; } catch(ap_error) {} if( !_TestResult) { printf("%-32s FAILED\n", "matinv_e_spd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_e_hpd1 // Attempt to use SPD function on nonsymmetrix matrix // _TestResult = true; try { complex_2d_array a = "[[1,0],[1,1]]"; ae_int_t info; matinvreport rep; hpdmatrixinverse(a, info, rep); _TestResult = false; } catch(ap_error) {} if( !_TestResult) { printf("%-32s FAILED\n", "matinv_e_hpd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_d_1 // Nonlinear optimization by L-BFGS // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using LBFGS method, with: // * initial point x=[0,0] // * unit scale being set for all variables (see minlbfgssetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgscreate(1, x, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); minlbfgssetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minlbfgsoptguardsmoothness(state); minlbfgsoptguardgradient(state, 0.001); // // Optimize and examine results. // minlbfgsreport rep; alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minlbfgsoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_d_2 // Nonlinear optimization with additional settings and restarts // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // using LBFGS method. // // Several advanced techniques are demonstrated: // * upper limit on step size // * restart from new point // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double stpmax = 0.1; if( _spoil_scenario==15 ) stpmax = fp_nan; if( _spoil_scenario==16 ) stpmax = fp_posinf; if( _spoil_scenario==17 ) stpmax = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgsreport rep; // create and tune optimizer minlbfgscreate(1, x, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); minlbfgssetstpmax(state, stpmax); minlbfgssetscale(state, s); // Set up OptGuard integrity checker which catches errors // like nonsmooth targets or errors in the analytic gradient. // // OptGuard is essential at the early prototyping stages. // // NOTE: gradient verification needs 3*N additional function // evaluations; DO NOT USE IT IN THE PRODUCTION CODE // because it leads to unnecessary slowdown of your app. minlbfgsoptguardsmoothness(state); minlbfgsoptguardgradient(state, 0.001); // first run alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // second run - algorithm is restarted x = "[10,10]"; if( _spoil_scenario==18 ) spoil_vector_by_nan(x); if( _spoil_scenario==19 ) spoil_vector_by_posinf(x); if( _spoil_scenario==20 ) spoil_vector_by_neginf(x); minlbfgsrestartfrom(state, x); alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // check OptGuard integrity report. Why do we need it at all? // Well, try breaking the gradient by adding 1.0 to some // of its components - OptGuard should report it as error. // And it may also catch unintended errors too :) optguardreport ogrep; minlbfgsoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_numdiff // Nonlinear optimization by L-BFGS with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // using numerical differentiation to calculate gradient. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsg = 0.0000000001; if( _spoil_scenario==3 ) epsg = fp_nan; if( _spoil_scenario==4 ) epsg = fp_posinf; if( _spoil_scenario==5 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==6 ) epsf = fp_nan; if( _spoil_scenario==7 ) epsf = fp_posinf; if( _spoil_scenario==8 ) epsf = fp_neginf; double epsx = 0; if( _spoil_scenario==9 ) epsx = fp_nan; if( _spoil_scenario==10 ) epsx = fp_posinf; if( _spoil_scenario==11 ) epsx = fp_neginf; double diffstep = 1.0e-6; if( _spoil_scenario==12 ) diffstep = fp_nan; if( _spoil_scenario==13 ) diffstep = fp_posinf; if( _spoil_scenario==14 ) diffstep = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgsreport rep; minlbfgscreatef(1, x, diffstep, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); alglib::minlbfgsoptimize(state, function1_func); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST linlsqr_d_1 // Solution of sparse linear systems with CG // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<4; _spoil_scenario++) { try { // // This example illustrates solution of sparse linear least squares problem // with LSQR algorithm. // // Suppose that we have least squares problem min|A*x-b| with sparse A // represented by sparsematrix object // [ 1 1 ] // [ 1 1 ] // A = [ 2 1 ] // [ 1 ] // [ 1 ] // and right part b // [ 4 ] // [ 2 ] // b = [ 4 ] // [ 1 ] // [ 2 ] // and we want to solve this system in the least squares sense using // LSQR algorithm. In order to do so, we have to create left part // (sparsematrix object) and right part (dense array). // // Initially, sparse matrix is created in the Hash-Table format, // which allows easy initialization, but do not allow matrix to be // used in the linear solvers. So after construction you should convert // sparse matrix to CRS format (one suited for linear operations). // sparsematrix a; sparsecreate(5, 2, a); sparseset(a, 0, 0, 1.0); sparseset(a, 0, 1, 1.0); sparseset(a, 1, 0, 1.0); sparseset(a, 1, 1, 1.0); sparseset(a, 2, 0, 2.0); sparseset(a, 2, 1, 1.0); sparseset(a, 3, 0, 1.0); sparseset(a, 4, 1, 1.0); // // Now our matrix is fully initialized, but we have to do one more // step - convert it from Hash-Table format to CRS format (see // documentation on sparse matrices for more information about these // formats). // // If you omit this call, ALGLIB will generate exception on the first // attempt to use A in linear operations. // sparseconverttocrs(a); // // Initialization of the right part // real_1d_array b = "[4,2,4,1,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); // // Now we have to create linear solver object and to use it for the // solution of the linear system. // linlsqrstate s; linlsqrreport rep; real_1d_array x; linlsqrcreate(5, 2, s); linlsqrsolvesparse(s, a, b); linlsqrresults(s, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[1.000,2.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "linlsqr_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_d_1 // Nonlinear optimization with bound constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using BLEIC optimizer with: // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; minbleicstate state; minbleiccreate(x, state); minbleicsetbc(state, bndl, bndu); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbleicoptguardsmoothness(state); minbleicoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_grad); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_d_2 // Nonlinear optimization with linear inequality constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<22; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to inequality constraints // // * x>=2 (posed as general linear constraint), // * x+y>=6 // // using BLEIC optimizer with // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set linear constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[5,5]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_2d_array c = "[[1,0,2],[1,1,6]]"; if( _spoil_scenario==7 ) spoil_matrix_by_nan(c); if( _spoil_scenario==8 ) spoil_matrix_by_posinf(c); if( _spoil_scenario==9 ) spoil_matrix_by_neginf(c); if( _spoil_scenario==10 ) spoil_matrix_by_deleting_row(c); if( _spoil_scenario==11 ) spoil_matrix_by_deleting_col(c); integer_1d_array ct = "[1,1]"; if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(ct); minbleicstate state; double epsg = 0; if( _spoil_scenario==13 ) epsg = fp_nan; if( _spoil_scenario==14 ) epsg = fp_posinf; if( _spoil_scenario==15 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==16 ) epsf = fp_nan; if( _spoil_scenario==17 ) epsf = fp_posinf; if( _spoil_scenario==18 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==19 ) epsx = fp_nan; if( _spoil_scenario==20 ) epsx = fp_posinf; if( _spoil_scenario==21 ) epsx = fp_neginf; ae_int_t maxits = 0; minbleiccreate(x, state); minbleicsetlc(state, c, ct); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbleicoptguardsmoothness(state); minbleicoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_grad); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[2,4]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_numdiff // Nonlinear optimization with bound constraints and numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using BLEIC optimizer with: // * numerical differentiation being used // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbleicstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; double diffstep = 1.0e-6; if( _spoil_scenario==20 ) diffstep = fp_nan; if( _spoil_scenario==21 ) diffstep = fp_posinf; if( _spoil_scenario==22 ) diffstep = fp_neginf; minbleiccreatef(x, diffstep, state); minbleicsetbc(state, bndl, bndu); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tries to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // minbleicoptguardsmoothness(state); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_func); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_u1 // Unconstrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<17; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // // Exact solution is [x0,x1] = [3,2] // // We provide algorithm with starting point, although in this case // (dense matrix, no constraints) it can work without such information. // // Several QP solvers are tried: QuickQP, BLEIC, DENSE-AUL. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x0); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(s); if( _spoil_scenario==14 ) spoil_vector_by_posinf(s); if( _spoil_scenario==15 ) spoil_vector_by_neginf(s); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(s); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints (general linear constraints are not supported), but it can // also be efficiently used on unconstrained problems. // // Default stopping criteria are used, Newton phase is active. // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // Of course, unconstrained problems can be solved too. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_u1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_bc1 // Bound constrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // subject to bound constraints 0<=x0<=2.5, 0<=x1<=2.5 // // Exact solution is [x0,x1] = [2.5,2] // // We provide algorithm with starting point. With such small problem good starting // point is not really necessary, but with high-dimensional problem it can save us // a lot of time. // // Several QP solvers are tried: QuickQP, BLEIC, DENSE-AUL. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x0); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(s); if( _spoil_scenario==14 ) spoil_vector_by_posinf(s); if( _spoil_scenario==15 ) spoil_vector_by_neginf(s); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[0.0,0.0]"; if( _spoil_scenario==17 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[2.5,2.5]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); minqpsetbc(state, bndl, bndu); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints (general linear constraints are not supported). // // Default stopping criteria are used, Newton phase is active. // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_bc1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_lc1 // Linearly constrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<16; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // subject to linear constraint x0+x1<=2 // // Exact solution is [x0,x1] = [1.5,0.5] // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_posinf(s); if( _spoil_scenario==11 ) spoil_vector_by_neginf(s); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(s); real_2d_array c = "[[1.0,1.0,2.0]]"; if( _spoil_scenario==13 ) spoil_matrix_by_nan(c); if( _spoil_scenario==14 ) spoil_matrix_by_posinf(c); if( _spoil_scenario==15 ) spoil_matrix_by_neginf(c); integer_1d_array ct = "[-1]"; real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetlc(state, c, ct); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[1.500,0.500]", 0.05); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[1.500,0.500]", 0.05); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints, and... // // ...Oops! It does not support general linear constraints, -5 returned as completion code! // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, -5); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_lc1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_u2 // Unconstrained sparse quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1, // with quadratic term given by sparse matrix structure. // // Exact solution is [x0,x1] = [3,2] // // We provide algorithm with starting point, although in this case // (dense matrix, no constraints) it can work without such information. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // sparsematrix a; real_1d_array b = "[-6,-4]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(x0); if( _spoil_scenario==5 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==6 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(s); if( _spoil_scenario==9 ) spoil_vector_by_posinf(s); if( _spoil_scenario==10 ) spoil_vector_by_neginf(s); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(s); real_1d_array x; minqpstate state; minqpreport rep; // initialize sparsematrix structure sparsecreate(2, 2, 0, a); sparseset(a, 0, 0, 2.0); sparseset(a, 1, 1, 2.0); // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadratictermsparse(state, a, true); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // It also supports sparse problems. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_u2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_nonconvex // Nonconvex quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of nonconvex function // F(x0,x1) = -(x0^2+x1^2) // subject to constraints x0,x1 in [1.0,2.0] // Exact solution is [x0,x1] = [2,2]. // // Non-convex problems are harded to solve than convex ones, and they // may have more than one local minimum. However, ALGLIB solves may deal // with such problems (altough they do not guarantee convergence to // global minimum). // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=-(x0^2+x1^2), but we rewrite it as // f(x) = 0.5*(-2*x0^2-2*x1^2) // and pass diag(-2,-2) as quadratic term - NOT diag(-1,-1)! // real_2d_array a = "[[-2,0],[0,-2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array x0 = "[1,1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(x0); if( _spoil_scenario==6 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==7 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_posinf(s); if( _spoil_scenario==11 ) spoil_vector_by_neginf(s); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[1.0,1.0]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[2.0,2.0]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms, constraints minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetstartingpoint(state, x0); minqpsetbc(state, bndl, bndu); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: there also exists minqpsetscaleautodiag() function // which automatically determines variable scales; however, // it does NOT work for non-convex problems. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // It may solve non-convex problems as long as they are bounded from // below under constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Algorithm convergence is guaranteed only for convex case, but you may // expect that it will work for non-convex problems too (because near the // solution they are locally convex). // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2,2]", 0.005); // Hmm... this problem is bounded from below (has solution) only under constraints. // What it we remove them? // // You may see that BLEIC algorithm detects unboundedness of the problem, // -4 is returned as completion code. However, DENSE-AUL is unable to detect // such situation and it will cycle forever (we do not test it here). real_1d_array nobndl = "[-inf,-inf]"; if( _spoil_scenario==17 ) spoil_vector_by_nan(nobndl); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(nobndl); real_1d_array nobndu = "[+inf,+inf]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(nobndu); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(nobndu); minqpsetbc(state, nobndl, nobndu); minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, -4); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_nonconvex"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlp_basic // Basic linear programming example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates how to minimize // // F(x0,x1) = -0.1*x0 - x1 // // subject to box constraints // // -1 <= x0,x1 <= +1 // // and general linear constraints // // x0 - x1 >= -1 // x0 + x1 <= 1 // // We use dual simplex solver provided by ALGLIB for this task. Box // constraints are specified by means of constraint vectors bndl and // bndu (we have bndl<=x<=bndu). General linear constraints are // specified as AL<=A*x<=AU, with AL/AU being 2x1 vectors and A being // 2x2 matrix. // // NOTE: some/all components of AL/AU can be +-INF, same applies to // bndl/bndu. You can also have AL[I]=AU[i] (as well as // BndL[i]=BndU[i]). // real_2d_array a = "[[1,-1],[1,+1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==2 ) spoil_matrix_by_deleting_col(a); real_1d_array al = "[-1,-inf]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(al); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(al); real_1d_array au = "[+inf,+1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(au); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(au); real_1d_array c = "[-0.1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(c); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(c); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==11 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minlpstate state; minlpreport rep; minlpcreate(2, state); // // Set cost vector, box constraints, general linear constraints. // // Box constraints can be set in one call to minlpsetbc() or minlpsetbcall() // (latter sets same constraints for all variables and accepts two scalars // instead of two vectors). // // General linear constraints can be specified in several ways: // * minlpsetlc2dense() - accepts dense 2D array as input; sometimes this // approach is more convenient, although less memory-efficient. // * minlpsetlc2() - accepts sparse matrix as input // * minlpaddlc2dense() - appends one row to the current set of constraints; // row being appended is specified as dense vector // * minlpaddlc2() - appends one row to the current set of constraints; // row being appended is specified as sparse set of elements // Independently from specific function being used, LP solver uses sparse // storage format for internal representation of constraints. // minlpsetcost(state, c); minlpsetbc(state, bndl, bndu); minlpsetlc2dense(state, a, al, au, 2); // // Set scale of the parameters. // // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // minlpsetscale(state, s); // Solve minlpoptimize(state); minlpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[0,1]", 0.0005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlp_basic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_inequality // Nonlinearly constrained optimization (inequality constraints) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = -x0+x1 // // subject to box constraints // // x0>=0, x1>=0 // // and nonlinear inequality constraint // // x0^2 + x1^2 - 1 <= 0 // real_1d_array x0 = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; real_1d_array bndl = "[0,0]"; real_1d_array bndu = "[+inf,+inf]"; minnlcstate state; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale; it is important to // tell optimizer about scales of your variables - it // greatly accelerates convergence and helps to perform // some important integrity checks. // minnlccreate(2, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SQP - sequential quadratic programming NLP solver // * AUL - augmented Lagrangian NLP solver // * SLP - successive linear programming NLP solver // // Different solvers have different properties: // * SQP needs less function evaluations than any other solver, but it // has much higher iteration cost than other solvers (a QP subproblem // has to be solved during each step) // * AUL solver has cheaper iterations, but needs more target function // evaluations // * SLP is the most robust solver provided by ALGLIB, but it performs // order of magnitude more iterations than SQP. // // In the code below we set solver to be AUL but then override it with SLP, // and then with SQP, so the effective choice is to use SLP. We recommend // you to use SQP at least for early prototyping stages, and then switch // to AUL if possible. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); minnlcsetalgosqp(state); // // Set constraints: // // 1. boundary constraints are passed with minnlcsetbc() call // // 2. nonlinear constraints are more tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetlc() function. // minnlcsetbc(state, bndl, bndu); minnlcsetnlc(state, 0, 1); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1} = { -x0+x1 , x0^2+x1^2-1 } // // with Jacobian // // [ -1 +1 ] // J = [ ] // [ 2*x0 2*x1 ] // // with f0 being target function, f1 being constraining function. Number // of equality/inequality constraints is specified by minnlcsetnlc(), // with equality ones always being first, inequality ones being last. // minnlcreport rep; real_1d_array x1; alglib::minnlcoptimize(state, nlcfunc1_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_inequality"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_equality // Nonlinearly constrained optimization (equality constraints) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = -x0+x1 // // subject to nonlinear equality constraint // // x0^2 + x1^2 - 1 = 0 // real_1d_array x0 = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minnlcstate state; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale // minnlccreate(2, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SLP - successive linear programming NLP solver // * AUL - augmented Lagrangian NLP solver // // Different solvers have different properties: // * SLP is the most robust solver provided by ALGLIB: it can solve both // convex and nonconvex optimization problems, it respects box and // linear constraints (after you find feasible point it won't move away // from the feasible area) and tries to respect nonlinear constraints // as much as possible. It also usually needs less function evaluations // to converge than AUL. // However, it solves LP subproblems at each iterations which adds // significant overhead to its running time. Sometimes it can be as much // as 7x times slower than AUL. // * AUL solver is less robust than SLP - it can violate box and linear // constraints at any moment, and it is intended for convex optimization // problems (although in many cases it can deal with nonconvex ones too). // Also, unlike SLP it needs some tuning (penalty factor and number of // outer iterations). // However, it is often much faster than the current version of SLP. // // In the code below we set solver to be AUL but then override it with SLP, // so the effective choice is to use SLP. We recommend you to use SLP at // least for early prototyping stages. // // You can comment out line with SLP if you want to solve your problem with // AUL solver. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); // // Set constraints: // // Nonlinear constraints are tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetbc() and // minnlcsetlc() functions. // minnlcsetnlc(state, 1, 0); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1} = { -x0+x1 , x0^2+x1^2-1 } // // with Jacobian // // [ -1 +1 ] // J = [ ] // [ 2*x0 2*x1 ] // // with f0 being target function, f1 being constraining function. Number // of equality/inequality constraints is specified by minnlcsetnlc(), // with equality ones always being first, inequality ones being last. // minnlcreport rep; real_1d_array x1; alglib::minnlcoptimize(state, nlcfunc1_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.70710,-0.70710]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_equality"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_mixed // Nonlinearly constrained optimization with mixed equality/inequality constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = x0+x1 // // subject to nonlinear inequality constraint // // x0^2 + x1^2 - 1 <= 0 // // and nonlinear equality constraint // // x2-exp(x0) = 0 // real_1d_array x0 = "[0,0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minnlcstate state; minnlcreport rep; real_1d_array x1; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale // * upper limit on step length is specified (to avoid probing locations where exp() is large) // minnlccreate(3, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); minnlcsetstpmax(state, 10.0); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SLP - successive linear programming NLP solver // * AUL - augmented Lagrangian NLP solver // // Different solvers have different properties: // * SLP is the most robust solver provided by ALGLIB: it can solve both // convex and nonconvex optimization problems, it respects box and // linear constraints (after you find feasible point it won't move away // from the feasible area) and tries to respect nonlinear constraints // as much as possible. It also usually needs less function evaluations // to converge than AUL. // However, it solves LP subproblems at each iterations which adds // significant overhead to its running time. Sometimes it can be as much // as 7x times slower than AUL. // * AUL solver is less robust than SLP - it can violate box and linear // constraints at any moment, and it is intended for convex optimization // problems (although in many cases it can deal with nonconvex ones too). // Also, unlike SLP it needs some tuning (penalty factor and number of // outer iterations). // However, it is often much faster than the current version of SLP. // // In the code below we set solver to be AUL but then override it with SLP, // so the effective choice is to use SLP. We recommend you to use SLP at // least for early prototyping stages. // // You can comment out line with SLP if you want to solve your problem with // AUL solver. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); // // Set constraints: // // Nonlinear constraints are tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with boundary or general linear constraints, but you // can easily find it in documentation on minnlcsetbc() and // minnlcsetlc() functions. // minnlcsetnlc(state, 1, 1); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1,f2} = { x0+x1 , x2-exp(x0) , x0^2+x1^2-1 } // // with Jacobian // // [ +1 +1 0 ] // J = [-exp(x0) 0 1 ] // [ 2*x0 2*x1 0 ] // // with f0 being target function, f1 being equality constraint "f1=0", // f2 being inequality constraint "f2<=0". Number of equality/inequality // constraints is specified by minnlcsetnlc(), with equality ones always // being first, inequality ones being last. // alglib::minnlcoptimize(state, nlcfunc2_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[-0.70710,-0.70710,0.49306]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_mixed"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbc_d_1 // Nonlinear optimization with box constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using MinBC optimizer with: // * initial point x=[0,0] // * unit scale being set for all variables (see minbcsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbcstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; minbccreate(x, state); minbcsetbc(state, bndl, bndu); minbcsetscale(state, s); minbcsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbcoptguardsmoothness(state); minbcoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbcreport rep; alglib::minbcoptimize(state, function1_grad); minbcresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbc_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbc_numdiff // Nonlinear optimization with bound constraints and numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using MinBC optimizer with: // * numerical differentiation being used // * initial point x=[0,0] // * unit scale being set for all variables (see minbcsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbcstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; double diffstep = 1.0e-6; if( _spoil_scenario==20 ) diffstep = fp_nan; if( _spoil_scenario==21 ) diffstep = fp_posinf; if( _spoil_scenario==22 ) diffstep = fp_neginf; // // Now we are ready to actually optimize something: // * first we create optimizer // * we add boundary constraints // * we tune stopping conditions // * and, finally, optimize and obtain results... // minbccreatef(x, diffstep, state); minbcsetbc(state, bndl, bndu); minbcsetscale(state, s); minbcsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tries to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // minbcoptguardsmoothness(state); // // Optimize and evaluate results // minbcreport rep; alglib::minbcoptimize(state, function1_func); minbcresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; minbcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbc_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_unconstrained // Nonsmooth unconstrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // using nonsmooth nonlinear optimizer. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==9 ) radius = fp_nan; if( _spoil_scenario==10 ) radius = fp_posinf; if( _spoil_scenario==11 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==12 ) rho = fp_nan; if( _spoil_scenario==13 ) rho = fp_posinf; if( _spoil_scenario==14 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector and 1xN Jacobian matrix. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // // with Jacobian // // [ ] // J = [ 2*sign(x0) sign(x1) ] // [ ] // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // alglib::minnsoptimize(state, nsfunc1_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_unconstrained"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_diff // Nonsmooth unconstrained optimization with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<18; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // using nonsmooth nonlinear optimizer with numerical // differentiation provided by ALGLIB. // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double diffstep = 0.000001; if( _spoil_scenario==9 ) diffstep = fp_nan; if( _spoil_scenario==10 ) diffstep = fp_posinf; if( _spoil_scenario==11 ) diffstep = fp_neginf; double radius = 0.1; if( _spoil_scenario==12 ) radius = fp_nan; if( _spoil_scenario==13 ) radius = fp_posinf; if( _spoil_scenario==14 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==15 ) rho = fp_nan; if( _spoil_scenario==16 ) rho = fp_posinf; if( _spoil_scenario==17 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreatef(2, x0, diffstep, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Optimize and test results. // // Optimizer object accepts vector function, with first component // being target function, and next components being nonlinear equality // and inequality constraints (box/linear ones are passed separately // by means of minnssetbc() and minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // alglib::minnsoptimize(state, nsfunc1_fvec); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_diff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_bc // Nonsmooth box constrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<17; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // subject to box constraints // // 1 <= x0 < +INF // -INF <= x1 < +INF // // using nonsmooth nonlinear optimizer. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); real_1d_array bndl = "[1,-inf]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(bndl); real_1d_array bndu = "[+inf,+inf]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndu); double epsx = 0.00001; if( _spoil_scenario==8 ) epsx = fp_nan; if( _spoil_scenario==9 ) epsx = fp_posinf; if( _spoil_scenario==10 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==11 ) radius = fp_nan; if( _spoil_scenario==12 ) radius = fp_posinf; if( _spoil_scenario==13 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==14 ) rho = fp_nan; if( _spoil_scenario==15 ) rho = fp_posinf; if( _spoil_scenario==16 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Set box constraints. // // General linear constraints are set in similar way (see comments on // minnssetlc() function for more information). // // You may combine box, linear and nonlinear constraints in one optimization // problem. // minnssetbc(state, bndl, bndu); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector and 1xN Jacobian matrix. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // // with Jacobian // // [ ] // J = [ 2*sign(x0) sign(x1) ] // [ ] // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // // alglib::minnsoptimize(state, nsfunc1_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_bc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_nlc // Nonsmooth nonlinearly constrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // subject to combination of equality and inequality constraints // // x0 = 1 // x1 >= -1 // // using nonsmooth nonlinear optimizer. Although these constraints // are linear, we treat them as general nonlinear ones in order to // demonstrate nonlinearly constrained optimization setup. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==9 ) radius = fp_nan; if( _spoil_scenario==10 ) radius = fp_posinf; if( _spoil_scenario==11 ) radius = fp_neginf; double rho = 50.0; if( _spoil_scenario==12 ) rho = fp_nan; if( _spoil_scenario==13 ) rho = fp_posinf; if( _spoil_scenario==14 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=50.0 penalty coefficient for nonlinear constraints. It is your // responsibility to choose good one - large enough that it // enforces constraints, but small enough in order to avoid // extreme slowdown due to ill-conditioning. // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Set general nonlinear constraints. // // This part is more tricky than working with box/linear constraints - you // can not "pack" general nonlinear function into double precision array. // That's why minnssetnlc() does not accept constraints itself - only // constraint COUNTS are passed: first parameter is number of equality // constraints, second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNS optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetlc() function. // minnssetnlc(state, 1, 1); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // Nonlinear equality constraints have form Gi(x)=0, inequality ones // have form Hi(x)<=0, so we may have to "normalize" constraints prior // to passing them to optimizer (right side is zero, constraints are // sorted, multiplied by -1 when needed). // // So, our vector function has form // // {f0,f1,f2} = { 2*|x0|+|x1|, x0-1, -x1-1 } // // with Jacobian // // [ 2*sign(x0) sign(x1) ] // J = [ 1 0 ] // [ 0 -1 ] // // which means that we have optimization problem // // min{f0} subject to f1=0, f2<=0 // // which is essentially same as // // min { 2*|x0|+|x1| } subject to x0=1, x1>=-1 // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // alglib::minnsoptimize(state, nsfunc2_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_nlc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_d_1 // Nonlinear optimization by CG // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using nonlinear conjugate gradient method with: // * initial point x=[0,0] // * unit scale being set for all variables (see mincgsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgcreate(x, state); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // mincgoptguardsmoothness(state); mincgoptguardgradient(state, 0.001); // // Optimize and evaluate results // mincgreport rep; alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_d_2 // Nonlinear optimization with additional settings and restarts // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // with nonlinear conjugate gradient method. // // Several advanced techniques are demonstrated: // * upper limit on step size // * restart from new point // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double stpmax = 0.1; if( _spoil_scenario==15 ) stpmax = fp_nan; if( _spoil_scenario==16 ) stpmax = fp_posinf; if( _spoil_scenario==17 ) stpmax = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgreport rep; // create and tune optimizer mincgcreate(x, state); mincgsetscale(state, s); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetstpmax(state, stpmax); // Set up OptGuard integrity checker which catches errors // like nonsmooth targets or errors in the analytic gradient. // // OptGuard is essential at the early prototyping stages. // // NOTE: gradient verification needs 3*N additional function // evaluations; DO NOT USE IT IN THE PRODUCTION CODE // because it leads to unnecessary slowdown of your app. mincgoptguardsmoothness(state); mincgoptguardgradient(state, 0.001); // first run alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // second run - algorithm is restarted with mincgrestartfrom() x = "[10,10]"; if( _spoil_scenario==18 ) spoil_vector_by_nan(x); if( _spoil_scenario==19 ) spoil_vector_by_posinf(x); if( _spoil_scenario==20 ) spoil_vector_by_neginf(x); mincgrestartfrom(state, x); alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // check OptGuard integrity report. Why do we need it at all? // Well, try breaking the gradient by adding 1.0 to some // of its components - OptGuard should report it as error. // And it may also catch unintended errors too :) optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_numdiff // Nonlinear optimization by CG with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<18; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using numerical differentiation to calculate gradient. // // We also show how to use OptGuard integrity checker to catch common // problem statement errors like accidentally specifying nonsmooth target // function. // // First, we set up optimizer... // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double diffstep = 1.0e-6; if( _spoil_scenario==15 ) diffstep = fp_nan; if( _spoil_scenario==16 ) diffstep = fp_posinf; if( _spoil_scenario==17 ) diffstep = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgcreatef(x, diffstep, state); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetscale(state, s); // // Then, we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tried to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // mincgoptguardsmoothness(state); // // Now we are ready to run the optimization // mincgreport rep; alglib::mincgoptimize(state, function1_func); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // ...and to check OptGuard integrity report. // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_v // Nonlinear least squares optimization using function vector only // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using "V" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // // No other information (Jacobian, gradient, etc.) is needed. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.0000000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; // // Create optimizer, tell it to: // * use numerical differentiation with step equal to 0.0001 // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // minlmcreatev(2, x, 0.0001, state); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Optimize // alglib::minlmoptimize(state, function1_fvec); // // Test optimization results // // NOTE: because we use numerical differentiation, we do not // verify Jacobian correctness - it is always "correct". // However, if you switch to analytic gradient, consider // checking it with OptGuard (see other examples). // minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_v"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_vj // Nonlinear least squares optimization using function vector and Jacobian // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using "VJ" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // * Jacobian matrix J = {dfi/dxj}. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.0000000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; // // Create optimizer, tell it to: // * use analytic gradient provided by user // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // minlmcreatevj(2, x, state); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to detect erroneous analytic Jacobian, // i.e. one inconsistent with actual change in the target function. // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: JACOBIAN VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // minlmoptguardgradient(state, 0.001); // // Optimize // alglib::minlmoptimize(state, function1_fvec, function1_jac); // // Test optimization results // minlmreport rep; minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // // NOTE: unfortunately, specifics of LM optimization do not allow us // to detect errors like nonsmoothness (like we do with other // optimizers). So, only Jacobian correctness is verified. // optguardreport ogrep; minlmoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_vj"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_fgh // Nonlinear Hessian-based optimization for general functions // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = 100*(x0+3)^4+(x1-3)^4 // using "FGH" mode of the Levenberg-Marquardt optimizer. // // F is treated like a monolitic function without internal structure, // i.e. we do NOT represent it as a sum of squares. // // Optimization algorithm uses: // * function value F(x0,x1) // * gradient G={dF/dxi} // * Hessian H={d2F/(dxi*dxj)} // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefgh(x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_grad, function1_hess); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_fgh"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_vb // Bound constrained nonlinear least squares optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<13; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // with boundary constraints // // -1 <= x0 <= +1 // -1 <= x1 <= +1 // // using "V" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // // No other information (Jacobian, gradient, etc.) is needed. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(bndu); double epsx = 0.0000000001; if( _spoil_scenario==10 ) epsx = fp_nan; if( _spoil_scenario==11 ) epsx = fp_posinf; if( _spoil_scenario==12 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; // // Create optimizer, tell it to: // * use numerical differentiation with step equal to 1.0 // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // * set box constraints // minlmcreatev(2, x, 0.0001, state); minlmsetbc(state, bndl, bndu); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Optimize // alglib::minlmoptimize(state, function1_fvec); // // Test optimization results // // NOTE: because we use numerical differentiation, we do not // verify Jacobian correctness - it is always "correct". // However, if you switch to analytic gradient, consider // checking it with OptGuard (see other examples). // minlmreport rep; minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,+1]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_vb"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_restarts // Efficient restarts of LM optimizer // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using several starting points and efficient restarts. // real_1d_array x; double epsx = 0.0000000001; if( _spoil_scenario==0 ) epsx = fp_nan; if( _spoil_scenario==1 ) epsx = fp_posinf; if( _spoil_scenario==2 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; // // create optimizer using minlmcreatev() // x = "[10,10]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(x); if( _spoil_scenario==4 ) spoil_vector_by_posinf(x); if( _spoil_scenario==5 ) spoil_vector_by_neginf(x); minlmcreatev(2, x, 0.0001, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_fvec); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); // // restart optimizer using minlmrestartfrom() // // we can use different starting point, different function, // different stopping conditions, but problem size // must remain unchanged. // x = "[4,4]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(x); if( _spoil_scenario==7 ) spoil_vector_by_posinf(x); if( _spoil_scenario==8 ) spoil_vector_by_neginf(x); minlmrestartfrom(state, x); alglib::minlmoptimize(state, function2_fvec); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[0,1]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_restarts"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_t_1 // Nonlinear least squares optimization, FJ scheme (obsolete, but supported) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefj(2, x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_jac); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_t_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_t_2 // Nonlinear least squares optimization, FGJ scheme (obsolete, but supported) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefgj(2, x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_grad, function1_jac); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_base // Basic functionality (moments, adev, median, percentile) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double mean; double variance; double skewness; double kurtosis; double adev; double p; double v; // // Here we demonstrate calculation of sample moments // (mean, variance, skewness, kurtosis) // samplemoments(x, mean, variance, skewness, kurtosis); _TestResult = _TestResult && doc_test_real(mean, 28.5, 0.01); _TestResult = _TestResult && doc_test_real(variance, 801.1667, 0.01); _TestResult = _TestResult && doc_test_real(skewness, 0.5751, 0.01); _TestResult = _TestResult && doc_test_real(kurtosis, -1.2666, 0.01); // // Average deviation // sampleadev(x, adev); _TestResult = _TestResult && doc_test_real(adev, 23.2, 0.01); // // Median and percentile // samplemedian(x, v); _TestResult = _TestResult && doc_test_real(v, 20.5, 0.01); p = 0.5; if( _spoil_scenario==3 ) p = fp_nan; if( _spoil_scenario==4 ) p = fp_posinf; if( _spoil_scenario==5 ) p = fp_neginf; samplepercentile(x, p, v); _TestResult = _TestResult && doc_test_real(v, 20.5, 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_base"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_c2 // Correlation (covariance) between two random variables // printf("50/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { // // We have two samples - x and y, and want to measure dependency between them // real_1d_array x = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); double v; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // v = cov2(x, y); _TestResult = _TestResult && doc_test_real(v, 82.5, 0.001); v = pearsoncorr2(x, y); _TestResult = _TestResult && doc_test_real(v, 0.9627, 0.001); v = spearmancorr2(x, y); _TestResult = _TestResult && doc_test_real(v, 1.000, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_c2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_cm // Correlation (covariance) between components of random vector // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // X is a sample matrix: // * I-th row corresponds to I-th observation // * J-th column corresponds to J-th variable // real_2d_array x = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); real_2d_array c; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // // Result is stored into C, with C[i,j] equal to correlation // (covariance) between I-th and J-th variables of X. // covm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.80,0.60,-1.40],[0.60,0.70,-0.80],[-1.40,-0.80,14.70]]", 0.01); pearsoncorrm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.000,0.535,-0.272],[0.535,1.000,-0.249],[-0.272,-0.249,1.000]]", 0.01); spearmancorrm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.000,0.556,-0.306],[0.556,1.000,-0.750],[-0.306,-0.750,1.000]]", 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_cm"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_cm2 // Correlation (covariance) between two random vectors // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // X and Y are sample matrices: // * I-th row corresponds to I-th observation // * J-th column corresponds to J-th variable // real_2d_array x = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); real_2d_array y = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==3 ) spoil_matrix_by_nan(y); if( _spoil_scenario==4 ) spoil_matrix_by_posinf(y); if( _spoil_scenario==5 ) spoil_matrix_by_neginf(y); real_2d_array c; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // // Result is stored into C, with C[i,j] equal to correlation // (covariance) between I-th variable of X and J-th variable of Y. // covm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[4.100,-3.250],[2.450,-1.500],[13.450,-5.750]]", 0.01); pearsoncorrm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.519,-0.699],[0.497,-0.518],[0.596,-0.433]]", 0.01); spearmancorrm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.541,-0.649],[0.216,-0.433],[0.433,-0.135]]", 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_cm2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_t_base // Tests ability to detect errors in inputs // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<34; _spoil_scenario++) { try { double mean; double variance; double skewness; double kurtosis; double adev; double p; double v; // // first, we test short form of functions // real_1d_array x1 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x1); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x1); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x1); samplemoments(x1, mean, variance, skewness, kurtosis); real_1d_array x2 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(x2); if( _spoil_scenario==4 ) spoil_vector_by_posinf(x2); if( _spoil_scenario==5 ) spoil_vector_by_neginf(x2); sampleadev(x2, adev); real_1d_array x3 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(x3); if( _spoil_scenario==7 ) spoil_vector_by_posinf(x3); if( _spoil_scenario==8 ) spoil_vector_by_neginf(x3); samplemedian(x3, v); real_1d_array x4 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x4); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x4); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x4); p = 0.5; if( _spoil_scenario==12 ) p = fp_nan; if( _spoil_scenario==13 ) p = fp_posinf; if( _spoil_scenario==14 ) p = fp_neginf; samplepercentile(x4, p, v); // // and then we test full form // real_1d_array x5 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(x5); if( _spoil_scenario==16 ) spoil_vector_by_posinf(x5); if( _spoil_scenario==17 ) spoil_vector_by_neginf(x5); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(x5); samplemoments(x5, 10, mean, variance, skewness, kurtosis); real_1d_array x6 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(x6); if( _spoil_scenario==20 ) spoil_vector_by_posinf(x6); if( _spoil_scenario==21 ) spoil_vector_by_neginf(x6); if( _spoil_scenario==22 ) spoil_vector_by_deleting_element(x6); sampleadev(x6, 10, adev); real_1d_array x7 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==23 ) spoil_vector_by_nan(x7); if( _spoil_scenario==24 ) spoil_vector_by_posinf(x7); if( _spoil_scenario==25 ) spoil_vector_by_neginf(x7); if( _spoil_scenario==26 ) spoil_vector_by_deleting_element(x7); samplemedian(x7, 10, v); real_1d_array x8 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==27 ) spoil_vector_by_nan(x8); if( _spoil_scenario==28 ) spoil_vector_by_posinf(x8); if( _spoil_scenario==29 ) spoil_vector_by_neginf(x8); if( _spoil_scenario==30 ) spoil_vector_by_deleting_element(x8); p = 0.5; if( _spoil_scenario==31 ) p = fp_nan; if( _spoil_scenario==32 ) p = fp_posinf; if( _spoil_scenario==33 ) p = fp_neginf; samplepercentile(x8, 10, p, v); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_t_base"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_t_covcorr // Tests ability to detect errors in inputs // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<126; _spoil_scenario++) { try { double v; real_2d_array c; // // 2-sample short-form cov/corr are tested // real_1d_array x1 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x1); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x1); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x1); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x1); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x1); real_1d_array y1 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y1); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y1); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y1); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y1); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y1); v = cov2(x1, y1); real_1d_array x2 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(x2); if( _spoil_scenario==11 ) spoil_vector_by_posinf(x2); if( _spoil_scenario==12 ) spoil_vector_by_neginf(x2); if( _spoil_scenario==13 ) spoil_vector_by_adding_element(x2); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(x2); real_1d_array y2 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(y2); if( _spoil_scenario==16 ) spoil_vector_by_posinf(y2); if( _spoil_scenario==17 ) spoil_vector_by_neginf(y2); if( _spoil_scenario==18 ) spoil_vector_by_adding_element(y2); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(y2); v = pearsoncorr2(x2, y2); real_1d_array x3 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==20 ) spoil_vector_by_nan(x3); if( _spoil_scenario==21 ) spoil_vector_by_posinf(x3); if( _spoil_scenario==22 ) spoil_vector_by_neginf(x3); if( _spoil_scenario==23 ) spoil_vector_by_adding_element(x3); if( _spoil_scenario==24 ) spoil_vector_by_deleting_element(x3); real_1d_array y3 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==25 ) spoil_vector_by_nan(y3); if( _spoil_scenario==26 ) spoil_vector_by_posinf(y3); if( _spoil_scenario==27 ) spoil_vector_by_neginf(y3); if( _spoil_scenario==28 ) spoil_vector_by_adding_element(y3); if( _spoil_scenario==29 ) spoil_vector_by_deleting_element(y3); v = spearmancorr2(x3, y3); // // 2-sample full-form cov/corr are tested // real_1d_array x1a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==30 ) spoil_vector_by_nan(x1a); if( _spoil_scenario==31 ) spoil_vector_by_posinf(x1a); if( _spoil_scenario==32 ) spoil_vector_by_neginf(x1a); if( _spoil_scenario==33 ) spoil_vector_by_deleting_element(x1a); real_1d_array y1a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==34 ) spoil_vector_by_nan(y1a); if( _spoil_scenario==35 ) spoil_vector_by_posinf(y1a); if( _spoil_scenario==36 ) spoil_vector_by_neginf(y1a); if( _spoil_scenario==37 ) spoil_vector_by_deleting_element(y1a); v = cov2(x1a, y1a, 10); real_1d_array x2a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==38 ) spoil_vector_by_nan(x2a); if( _spoil_scenario==39 ) spoil_vector_by_posinf(x2a); if( _spoil_scenario==40 ) spoil_vector_by_neginf(x2a); if( _spoil_scenario==41 ) spoil_vector_by_deleting_element(x2a); real_1d_array y2a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==42 ) spoil_vector_by_nan(y2a); if( _spoil_scenario==43 ) spoil_vector_by_posinf(y2a); if( _spoil_scenario==44 ) spoil_vector_by_neginf(y2a); if( _spoil_scenario==45 ) spoil_vector_by_deleting_element(y2a); v = pearsoncorr2(x2a, y2a, 10); real_1d_array x3a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==46 ) spoil_vector_by_nan(x3a); if( _spoil_scenario==47 ) spoil_vector_by_posinf(x3a); if( _spoil_scenario==48 ) spoil_vector_by_neginf(x3a); if( _spoil_scenario==49 ) spoil_vector_by_deleting_element(x3a); real_1d_array y3a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==50 ) spoil_vector_by_nan(y3a); if( _spoil_scenario==51 ) spoil_vector_by_posinf(y3a); if( _spoil_scenario==52 ) spoil_vector_by_neginf(y3a); if( _spoil_scenario==53 ) spoil_vector_by_deleting_element(y3a); v = spearmancorr2(x3a, y3a, 10); // // vector short-form cov/corr are tested. // real_2d_array x4 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==54 ) spoil_matrix_by_nan(x4); if( _spoil_scenario==55 ) spoil_matrix_by_posinf(x4); if( _spoil_scenario==56 ) spoil_matrix_by_neginf(x4); covm(x4, c); real_2d_array x5 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==57 ) spoil_matrix_by_nan(x5); if( _spoil_scenario==58 ) spoil_matrix_by_posinf(x5); if( _spoil_scenario==59 ) spoil_matrix_by_neginf(x5); pearsoncorrm(x5, c); real_2d_array x6 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==60 ) spoil_matrix_by_nan(x6); if( _spoil_scenario==61 ) spoil_matrix_by_posinf(x6); if( _spoil_scenario==62 ) spoil_matrix_by_neginf(x6); spearmancorrm(x6, c); // // vector full-form cov/corr are tested. // real_2d_array x7 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==63 ) spoil_matrix_by_nan(x7); if( _spoil_scenario==64 ) spoil_matrix_by_posinf(x7); if( _spoil_scenario==65 ) spoil_matrix_by_neginf(x7); if( _spoil_scenario==66 ) spoil_matrix_by_deleting_row(x7); if( _spoil_scenario==67 ) spoil_matrix_by_deleting_col(x7); covm(x7, 5, 3, c); real_2d_array x8 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==68 ) spoil_matrix_by_nan(x8); if( _spoil_scenario==69 ) spoil_matrix_by_posinf(x8); if( _spoil_scenario==70 ) spoil_matrix_by_neginf(x8); if( _spoil_scenario==71 ) spoil_matrix_by_deleting_row(x8); if( _spoil_scenario==72 ) spoil_matrix_by_deleting_col(x8); pearsoncorrm(x8, 5, 3, c); real_2d_array x9 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==73 ) spoil_matrix_by_nan(x9); if( _spoil_scenario==74 ) spoil_matrix_by_posinf(x9); if( _spoil_scenario==75 ) spoil_matrix_by_neginf(x9); if( _spoil_scenario==76 ) spoil_matrix_by_deleting_row(x9); if( _spoil_scenario==77 ) spoil_matrix_by_deleting_col(x9); spearmancorrm(x9, 5, 3, c); // // cross-vector short-form cov/corr are tested. // real_2d_array x10 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==78 ) spoil_matrix_by_nan(x10); if( _spoil_scenario==79 ) spoil_matrix_by_posinf(x10); if( _spoil_scenario==80 ) spoil_matrix_by_neginf(x10); real_2d_array y10 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==81 ) spoil_matrix_by_nan(y10); if( _spoil_scenario==82 ) spoil_matrix_by_posinf(y10); if( _spoil_scenario==83 ) spoil_matrix_by_neginf(y10); covm2(x10, y10, c); real_2d_array x11 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==84 ) spoil_matrix_by_nan(x11); if( _spoil_scenario==85 ) spoil_matrix_by_posinf(x11); if( _spoil_scenario==86 ) spoil_matrix_by_neginf(x11); real_2d_array y11 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==87 ) spoil_matrix_by_nan(y11); if( _spoil_scenario==88 ) spoil_matrix_by_posinf(y11); if( _spoil_scenario==89 ) spoil_matrix_by_neginf(y11); pearsoncorrm2(x11, y11, c); real_2d_array x12 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==90 ) spoil_matrix_by_nan(x12); if( _spoil_scenario==91 ) spoil_matrix_by_posinf(x12); if( _spoil_scenario==92 ) spoil_matrix_by_neginf(x12); real_2d_array y12 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==93 ) spoil_matrix_by_nan(y12); if( _spoil_scenario==94 ) spoil_matrix_by_posinf(y12); if( _spoil_scenario==95 ) spoil_matrix_by_neginf(y12); spearmancorrm2(x12, y12, c); // // cross-vector full-form cov/corr are tested. // real_2d_array x13 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==96 ) spoil_matrix_by_nan(x13); if( _spoil_scenario==97 ) spoil_matrix_by_posinf(x13); if( _spoil_scenario==98 ) spoil_matrix_by_neginf(x13); if( _spoil_scenario==99 ) spoil_matrix_by_deleting_row(x13); if( _spoil_scenario==100 ) spoil_matrix_by_deleting_col(x13); real_2d_array y13 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==101 ) spoil_matrix_by_nan(y13); if( _spoil_scenario==102 ) spoil_matrix_by_posinf(y13); if( _spoil_scenario==103 ) spoil_matrix_by_neginf(y13); if( _spoil_scenario==104 ) spoil_matrix_by_deleting_row(y13); if( _spoil_scenario==105 ) spoil_matrix_by_deleting_col(y13); covm2(x13, y13, 5, 3, 2, c); real_2d_array x14 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==106 ) spoil_matrix_by_nan(x14); if( _spoil_scenario==107 ) spoil_matrix_by_posinf(x14); if( _spoil_scenario==108 ) spoil_matrix_by_neginf(x14); if( _spoil_scenario==109 ) spoil_matrix_by_deleting_row(x14); if( _spoil_scenario==110 ) spoil_matrix_by_deleting_col(x14); real_2d_array y14 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==111 ) spoil_matrix_by_nan(y14); if( _spoil_scenario==112 ) spoil_matrix_by_posinf(y14); if( _spoil_scenario==113 ) spoil_matrix_by_neginf(y14); if( _spoil_scenario==114 ) spoil_matrix_by_deleting_row(y14); if( _spoil_scenario==115 ) spoil_matrix_by_deleting_col(y14); pearsoncorrm2(x14, y14, 5, 3, 2, c); real_2d_array x15 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==116 ) spoil_matrix_by_nan(x15); if( _spoil_scenario==117 ) spoil_matrix_by_posinf(x15); if( _spoil_scenario==118 ) spoil_matrix_by_neginf(x15); if( _spoil_scenario==119 ) spoil_matrix_by_deleting_row(x15); if( _spoil_scenario==120 ) spoil_matrix_by_deleting_col(x15); real_2d_array y15 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==121 ) spoil_matrix_by_nan(y15); if( _spoil_scenario==122 ) spoil_matrix_by_posinf(y15); if( _spoil_scenario==123 ) spoil_matrix_by_neginf(y15); if( _spoil_scenario==124 ) spoil_matrix_by_deleting_row(y15); if( _spoil_scenario==125 ) spoil_matrix_by_deleting_col(y15); spearmancorrm2(x15, y15, 5, 3, 2, c); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_t_covcorr"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_basic // Simple SSA analysis demo // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate SSA trend/noise separation for some toy problem: // small monotonically growing series X are analyzed with 3-tick window // and "top-K" version of SSA, which selects K largest singular vectors // for analysis, with K=1. // ssamodel s; real_1d_array x = "[0,0.5,1,1,1.5,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // First, we create SSA model, set its properties and add dataset. // // We use window with width=3 and configure model to use direct SSA // algorithm - one which runs exact O(N*W^2) analysis - to extract // one top singular vector. Well, it is toy problem :) // // NOTE: SSA model may store and analyze more than one sequence // (say, different sequences may correspond to data collected // from different devices) // ssacreate(s); ssasetwindow(s, 3); ssaaddsequence(s, x); ssasetalgotopkdirect(s, 1); // // Now we begin analysis. Internally SSA model stores everything it needs: // data, settings, solvers and so on. Right after first call to analysis- // related function it will analyze dataset, build basis and perform analysis. // // Subsequent calls to analysis functions will reuse previously computed // basis, unless you invalidate it by changing model settings (or dataset). // real_1d_array trend; real_1d_array noise; ssaanalyzesequence(s, x, trend, noise); _TestResult = _TestResult && doc_test_real_vector(trend, "[0.3815,0.5582,0.7810,1.0794,1.5041,2.0105]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "ssa_d_basic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_forecast // Simple SSA forecasting demo // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate SSA forecasting on some toy problem with clearly // visible linear trend and small amount of noise. // ssamodel s; real_1d_array x = "[0.05,0.96,2.04,3.11,3.97,5.03,5.98,7.02,8.02]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // First, we create SSA model, set its properties and add dataset. // // We use window with width=3 and configure model to use direct SSA // algorithm - one which runs exact O(N*W^2) analysis - to extract // two top singular vectors. Well, it is toy problem :) // // NOTE: SSA model may store and analyze more than one sequence // (say, different sequences may correspond to data collected // from different devices) // ssacreate(s); ssasetwindow(s, 3); ssaaddsequence(s, x); ssasetalgotopkdirect(s, 2); // // Now we begin analysis. Internally SSA model stores everything it needs: // data, settings, solvers and so on. Right after first call to analysis- // related function it will analyze dataset, build basis and perform analysis. // // Subsequent calls to analysis functions will reuse previously computed // basis, unless you invalidate it by changing model settings (or dataset). // // In this example we show how to use ssaforecastlast() function, which // predicts changed in the last sequence of the dataset. If you want to // perform prediction for some other sequence, use ssaforecastsequence(). // real_1d_array trend; ssaforecastlast(s, 3, trend); // // Well, we expected it to be [9,10,11]. There exists some difference, // which can be explained by the artificial noise in the dataset. // _TestResult = _TestResult && doc_test_real_vector(trend, "[9.0005,9.9322,10.8051]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "ssa_d_forecast"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_realtime // Real-time SSA algorithm with fast incremental updates // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // Suppose that you have a constant stream of incoming data, and you want // to regularly perform singular spectral analysis of this stream. // // One full run of direct algorithm costs O(N*Width^2) operations, so // the more points you have, the more it costs to rebuild basis from // scratch. // // Luckily we have incremental SSA algorithm which can perform quick // updates of already computed basis in O(K*Width^2) ops, where K // is a number of singular vectors extracted. Usually it is orders of // magnitude faster than full update of the basis. // // In this example we start from some initial dataset x0. Then we // start appending elements one by one to the end of the last sequence. // // NOTE: direct algorithm also supports incremental updates, but // with O(Width^3) cost. Typically K<<Width, so specialized // incremental algorithm is still faster. // ssamodel s1; real_2d_array a1; real_1d_array sv1; ae_int_t w; ae_int_t k; real_1d_array x0 = "[0.009,0.976,1.999,2.984,3.977,5.002]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); ssacreate(s1); ssasetwindow(s1, 3); ssaaddsequence(s1, x0); // set algorithm to the real-time version of top-K, K=2 ssasetalgotopkrealtime(s1, 2); // one more interesting feature of the incremental algorithm is "power-up" cycle. // even with incremental algorithm initial basis calculation costs O(N*Width^2) ops. // if such startup cost is too high for your real-time app, then you may divide // initial basis calculation across several model updates. It results in better // latency at the price of somewhat lesser precision during first few updates. ssasetpoweruplength(s1, 3); // now, after we prepared everything, start to add incoming points one by one; // in the real life, of course, we will perform some work between subsequent update // (analyze something, predict, and so on). // // After each append we perform one iteration of the real-time solver. Usually // one iteration is more than enough to update basis. If you have REALLY tight // performance constraints, you may specify fractional amount of iterations, // which means that iteration is performed with required probability. double updateits = 1.0; if( _spoil_scenario==3 ) updateits = fp_nan; if( _spoil_scenario==4 ) updateits = fp_posinf; if( _spoil_scenario==5 ) updateits = fp_neginf; ssaappendpointandupdate(s1, 5.951, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 7.074, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 7.925, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 8.992, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 9.942, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 11.051, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 11.965, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 13.047, updateits); ssagetbasis(s1, a1, sv1, w, k); ssaappendpointandupdate(s1, 13.970, updateits); ssagetbasis(s1, a1, sv1, w, k); // Ok, we have our basis in a1[] and singular values at sv1[]. // But is it good enough? Let's print it. _TestResult = _TestResult && doc_test_real_matrix(a1, "[[0.510607,0.753611],[0.575201,0.058445],[0.639081,-0.654717]]", 0.0005); // Ok, two vectors with 3 components each. // But how to understand that is it really good basis? // Let's compare it with direct SSA algorithm on the entire sequence. ssamodel s2; real_2d_array a2; real_1d_array sv2; real_1d_array x2 = "[0.009,0.976,1.999,2.984,3.977,5.002,5.951,7.074,7.925,8.992,9.942,11.051,11.965,13.047,13.970]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(x2); if( _spoil_scenario==7 ) spoil_vector_by_posinf(x2); if( _spoil_scenario==8 ) spoil_vector_by_neginf(x2); ssacreate(s2); ssasetwindow(s2, 3); ssaaddsequence(s2, x2); ssasetalgotopkdirect(s2, 2); ssagetbasis(s2, a2, sv2, w, k); // it is exactly the same as one calculated with incremental approach! _TestResult = _TestResult && doc_test_real_matrix(a2, "[[0.510607,0.753611],[0.575201,0.058445],[0.639081,-0.654717]]", 0.0005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "ssa_d_realtime"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST linreg_d_basic // Linear regression used to build the very basic model and unpack coefficients // _TestResult = true; try { // // In this example we demonstrate linear fitting by f(x|a) = a*exp(0.5*x). // // We have: // * xy - matrix of basic function values (exp(0.5*x)) and expected values // real_2d_array xy = "[[0.606531,1.133719],[0.670320,1.306522],[0.740818,1.504604],[0.818731,1.554663],[0.904837,1.884638],[1.000000,2.072436],[1.105171,2.257285],[1.221403,2.534068],[1.349859,2.622017],[1.491825,2.897713],[1.648721,3.219371]]"; ae_int_t info; ae_int_t nvars; linearmodel model; lrreport rep; real_1d_array c; lrbuildz(xy, 11, 1, info, model, rep); _TestResult = _TestResult && doc_test_int(info, 1); lrunpack(model, c, nvars); _TestResult = _TestResult && doc_test_real_vector(c, "[1.98650,0.00000]", 0.00005); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "linreg_d_basic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST filters_d_sma // SMA(k) filter // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate SMA(k) filtering for time series. // real_1d_array x = "[5,6,7,8]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // Apply filter. // We should get [5, 5.5, 6.5, 7.5] as result // filtersma(x, 2); _TestResult = _TestResult && doc_test_real_vector(x, "[5,5.5,6.5,7.5]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "filters_d_sma"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST filters_d_ema // EMA(alpha) filter // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate EMA(0.5) filtering for time series. // real_1d_array x = "[5,6,7,8]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // Apply filter. // We should get [5, 5.5, 6.25, 7.125] as result // filterema(x, 0.5); _TestResult = _TestResult && doc_test_real_vector(x, "[5,5.5,6.25,7.125]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "filters_d_ema"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST filters_d_lrma // LRMA(k) filter // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate LRMA(3) filtering for time series. // real_1d_array x = "[7,8,8,9,12,12]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // Apply filter. // We should get [7.0000, 8.0000, 8.1667, 8.8333, 11.6667, 12.5000] as result // filterlrma(x, 3); _TestResult = _TestResult && doc_test_real_vector(x, "[7.0000,8.0000,8.1667,8.8333,11.6667,12.5000]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "filters_d_lrma"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mcpd_simple1 // Simple unconstrained MCPD model (no entry/exit states) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // The very simple MCPD example // // We have a loan portfolio. Our loans can be in one of two states: // * normal loans ("good" ones) // * past due loans ("bad" ones) // // We assume that: // * loans can transition from any state to any other state. In // particular, past due loan can become "good" one at any moment // with same (fixed) probability. Not realistic, but it is toy example :) // * portfolio size does not change over time // // Thus, we have following model // state_new = P*state_old // where // ( p00 p01 ) // P = ( ) // ( p10 p11 ) // // We want to model transitions between these two states using MCPD // approach (Markov Chains for Proportional/Population Data), i.e. // to restore hidden transition matrix P using actual portfolio data. // We have: // * poportional data, i.e. proportion of loans in the normal and past // due states (not portfolio size measured in some currency, although // it is possible to work with population data too) // * two tracks, i.e. two sequences which describe portfolio // evolution from two different starting states: [1,0] (all loans // are "good") and [0.8,0.2] (only 80% of portfolio is in the "good" // state) // mcpdstate s; mcpdreport rep; real_2d_array p; real_2d_array track0 = "[[1.00000,0.00000],[0.95000,0.05000],[0.92750,0.07250],[0.91738,0.08263],[0.91282,0.08718]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(track0); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(track0); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(track0); real_2d_array track1 = "[[0.80000,0.20000],[0.86000,0.14000],[0.88700,0.11300],[0.89915,0.10085]]"; if( _spoil_scenario==3 ) spoil_matrix_by_nan(track1); if( _spoil_scenario==4 ) spoil_matrix_by_posinf(track1); if( _spoil_scenario==5 ) spoil_matrix_by_neginf(track1); mcpdcreate(2, s); mcpdaddtrack(s, track0); mcpdaddtrack(s, track1); mcpdsolve(s); mcpdresults(s, p, rep); // // Hidden matrix P is equal to // ( 0.95 0.50 ) // ( ) // ( 0.05 0.50 ) // which means that "good" loans can become "bad" with 5% probability, // while "bad" loans will return to good state with 50% probability. // _TestResult = _TestResult && doc_test_real_matrix(p, "[[0.95,0.50],[0.05,0.50]]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mcpd_simple1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mcpd_simple2 // Simple MCPD model (no entry/exit states) with equality constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // Simple MCPD example // // We have a loan portfolio. Our loans can be in one of three states: // * normal loans // * past due loans // * charged off loans // // We assume that: // * normal loan can stay normal or become past due (but not charged off) // * past due loan can stay past due, become normal or charged off // * charged off loan will stay charged off for the rest of eternity // * portfolio size does not change over time // Not realistic, but it is toy example :) // // Thus, we have following model // state_new = P*state_old // where // ( p00 p01 ) // P = ( p10 p11 ) // ( p21 1 ) // i.e. four elements of P are known a priori. // // Although it is possible (given enough data) to In order to enforce // this property we set equality constraints on these elements. // // We want to model transitions between these two states using MCPD // approach (Markov Chains for Proportional/Population Data), i.e. // to restore hidden transition matrix P using actual portfolio data. // We have: // * poportional data, i.e. proportion of loans in the current and past // due states (not portfolio size measured in some currency, although // it is possible to work with population data too) // * two tracks, i.e. two sequences which describe portfolio // evolution from two different starting states: [1,0,0] (all loans // are "good") and [0.8,0.2,0.0] (only 80% of portfolio is in the "good" // state) // mcpdstate s; mcpdreport rep; real_2d_array p; real_2d_array track0 = "[[1.000000,0.000000,0.000000],[0.950000,0.050000,0.000000],[0.927500,0.060000,0.012500],[0.911125,0.061375,0.027500],[0.896256,0.060900,0.042844]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(track0); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(track0); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(track0); real_2d_array track1 = "[[0.800000,0.200000,0.000000],[0.860000,0.090000,0.050000],[0.862000,0.065500,0.072500],[0.851650,0.059475,0.088875],[0.838805,0.057451,0.103744]]"; if( _spoil_scenario==3 ) spoil_matrix_by_nan(track1); if( _spoil_scenario==4 ) spoil_matrix_by_posinf(track1); if( _spoil_scenario==5 ) spoil_matrix_by_neginf(track1); mcpdcreate(3, s); mcpdaddtrack(s, track0); mcpdaddtrack(s, track1); mcpdaddec(s, 0, 2, 0.0); mcpdaddec(s, 1, 2, 0.0); mcpdaddec(s, 2, 2, 1.0); mcpdaddec(s, 2, 0, 0.0); mcpdsolve(s); mcpdresults(s, p, rep); // // Hidden matrix P is equal to // ( 0.95 0.50 ) // ( 0.05 0.25 ) // ( 0.25 1.00 ) // which means that "good" loans can become past due with 5% probability, // while past due loans will become charged off with 25% probability or // return back to normal state with 50% probability. // _TestResult = _TestResult && doc_test_real_matrix(p, "[[0.95,0.50,0.00],[0.05,0.25,0.00],[0.00,0.25,1.00]]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mcpd_simple2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_regr // Regression problem with one output (2=>1) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple example on neural network: network is trained to reproduce // small 2x2 multiplication table. // // NOTE: we use network with excessive amount of neurons, which guarantees // almost exact reproduction of the training set. Generalization ability // of such network is rather low, but we are not concerned with such // questions in this basic demo. // mlptrainer trn; multilayerperceptron network; mlpreport rep; // // Training set: // * one row corresponds to one record A*B=C in the multiplication table // * first two columns store A and B, last column stores C // // [1 * 1 = 1] // [1 * 2 = 2] // [2 * 1 = 2] // [2 * 2 = 4] // real_2d_array xy = "[[1,1,1],[1,2,2],[2,1,2],[2,2,4]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // Network is created. // Trainer object is created. // Dataset is attached to trainer object. // mlpcreatetrainer(2, 1, trn); mlpcreate1(2, 5, 1, network); mlpsetdataset(trn, xy, 4); // // Network is trained with 5 restarts from random positions // mlptrainnetwork(trn, network, 5, rep); // // 2*2=? // real_1d_array x = "[2,2]"; real_1d_array y = "[0]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[4.000]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_regr"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_regr_n // Regression problem with multiple outputs (2=>2) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Network with 2 inputs and 2 outputs is trained to reproduce vector function: // (x0,x1) => (x0+x1, x0*x1) // // Informally speaking, we want neural network to simultaneously calculate // both sum of two numbers and their product. // // NOTE: we use network with excessive amount of neurons, which guarantees // almost exact reproduction of the training set. Generalization ability // of such network is rather low, but we are not concerned with such // questions in this basic demo. // mlptrainer trn; multilayerperceptron network; mlpreport rep; // // Training set. One row corresponds to one record [A,B,A+B,A*B]. // // [ 1 1 1+1 1*1 ] // [ 1 2 1+2 1*2 ] // [ 2 1 2+1 2*1 ] // [ 2 2 2+2 2*2 ] // real_2d_array xy = "[[1,1,2,1],[1,2,3,2],[2,1,3,2],[2,2,4,4]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // Network is created. // Trainer object is created. // Dataset is attached to trainer object. // mlpcreatetrainer(2, 2, trn); mlpcreate1(2, 5, 2, network); mlpsetdataset(trn, xy, 4); // // Network is trained with 5 restarts from random positions // mlptrainnetwork(trn, network, 5, rep); // // 2+1=? // 2*1=? // real_1d_array x = "[2,1]"; real_1d_array y = "[0,0]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[3.000,2.000]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_regr_n"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_cls2 // Binary classification problem // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Suppose that we want to classify numbers as positive (class 0) and negative // (class 1). We have training set which includes several strictly positive // or negative numbers - and zero. // // The problem is that we are not sure how to classify zero, so from time to // time we mark it as positive or negative (with equal probability). Other // numbers are marked in pure deterministic setting. How will neural network // cope with such classification task? // // NOTE: we use network with excessive amount of neurons, which guarantees // almost exact reproduction of the training set. Generalization ability // of such network is rather low, but we are not concerned with such // questions in this basic demo. // mlptrainer trn; multilayerperceptron network; mlpreport rep; real_1d_array x = "[0]"; real_1d_array y = "[0,0]"; // // Training set. One row corresponds to one record [A => class(A)]. // // Classes are denoted by numbers from 0 to 1, where 0 corresponds to positive // numbers and 1 to negative numbers. // // [ +1 0] // [ +2 0] // [ -1 1] // [ -2 1] // [ 0 0] !! sometimes we classify 0 as positive, sometimes as negative // [ 0 1] !! // real_2d_array xy = "[[+1,0],[+2,0],[-1,1],[-2,1],[0,0],[0,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // // When we solve classification problems, everything is slightly different from // the regression ones: // // 1. Network is created. Because we solve classification problem, we use // mlpcreatec1() function instead of mlpcreate1(). This function creates // classifier network with SOFTMAX-normalized outputs. This network returns // vector of class membership probabilities which are normalized to be // non-negative and sum to 1.0 // // 2. We use mlpcreatetrainercls() function instead of mlpcreatetrainer() to // create trainer object. Trainer object process dataset and neural network // slightly differently to account for specifics of the classification // problems. // // 3. Dataset is attached to trainer object. Note that dataset format is slightly // different from one used for regression. // mlpcreatetrainercls(1, 2, trn); mlpcreatec1(1, 5, 2, network); mlpsetdataset(trn, xy, 6); // // Network is trained with 5 restarts from random positions // mlptrainnetwork(trn, network, 5, rep); // // Test our neural network on strictly positive and strictly negative numbers. // // IMPORTANT! Classifier network returns class membership probabilities instead // of class indexes. Network returns two values (probabilities) instead of one // (class index). // // Thus, for +1 we expect to get [P0,P1] = [1,0], where P0 is probability that // number is positive (belongs to class 0), and P1 is probability that number // is negative (belongs to class 1). // // For -1 we expect to get [P0,P1] = [0,1] // // Following properties are guaranteed by network architecture: // * P0>=0, P1>=0 non-negativity // * P0+P1=1 normalization // x = "[1]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,0.000]", 0.05); x = "[-1]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,1.000]", 0.05); // // But what our network will return for 0, which is between classes 0 and 1? // // In our dataset it has two different marks assigned (class 0 AND class 1). // So network will return something average between class 0 and class 1: // 0 => [0.5, 0.5] // x = "[0]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.500,0.500]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_cls2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_cls3 // Multiclass classification problem // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Suppose that we want to classify numbers as positive (class 0) and negative // (class 1). We also have one more class for zero (class 2). // // NOTE: we use network with excessive amount of neurons, which guarantees // almost exact reproduction of the training set. Generalization ability // of such network is rather low, but we are not concerned with such // questions in this basic demo. // mlptrainer trn; multilayerperceptron network; mlpreport rep; real_1d_array x = "[0]"; real_1d_array y = "[0,0,0]"; // // Training set. One row corresponds to one record [A => class(A)]. // // Classes are denoted by numbers from 0 to 2, where 0 corresponds to positive // numbers, 1 to negative numbers, 2 to zero // // [ +1 0] // [ +2 0] // [ -1 1] // [ -2 1] // [ 0 2] // real_2d_array xy = "[[+1,0],[+2,0],[-1,1],[-2,1],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // // When we solve classification problems, everything is slightly different from // the regression ones: // // 1. Network is created. Because we solve classification problem, we use // mlpcreatec1() function instead of mlpcreate1(). This function creates // classifier network with SOFTMAX-normalized outputs. This network returns // vector of class membership probabilities which are normalized to be // non-negative and sum to 1.0 // // 2. We use mlpcreatetrainercls() function instead of mlpcreatetrainer() to // create trainer object. Trainer object process dataset and neural network // slightly differently to account for specifics of the classification // problems. // // 3. Dataset is attached to trainer object. Note that dataset format is slightly // different from one used for regression. // mlpcreatetrainercls(1, 3, trn); mlpcreatec1(1, 5, 3, network); mlpsetdataset(trn, xy, 5); // // Network is trained with 5 restarts from random positions // mlptrainnetwork(trn, network, 5, rep); // // Test our neural network on strictly positive and strictly negative numbers. // // IMPORTANT! Classifier network returns class membership probabilities instead // of class indexes. Network returns three values (probabilities) instead of one // (class index). // // Thus, for +1 we expect to get [P0,P1,P2] = [1,0,0], // for -1 we expect to get [P0,P1,P2] = [0,1,0], // and for 0 we will get [P0,P1,P2] = [0,0,1]. // // Following properties are guaranteed by network architecture: // * P0>=0, P1>=0, P2>=0 non-negativity // * P0+P1+P2=1 normalization // x = "[1]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,0.000,0.000]", 0.05); x = "[-1]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,1.000,0.000]", 0.05); x = "[0]"; mlpprocess(network, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,0.000,1.000]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_cls3"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_trainerobject // Advanced example on trainer object // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // Trainer object is used to train network. It stores dataset, training settings, // and other information which is NOT part of neural network. You should use // trainer object as follows: // (1) you create trainer object and specify task type (classification/regression) // and number of inputs/outputs // (2) you add dataset to the trainer object // (3) you may change training settings (stopping criteria or weight decay) // (4) finally, you may train one or more networks // // You may interleave stages 2...4 and repeat them many times. Trainer object // remembers its internal state and can be used several times after its creation // and initialization. // mlptrainer trn; // // Stage 1: object creation. // // We have to specify number of inputs and outputs. Trainer object can be used // only for problems with same number of inputs/outputs as was specified during // its creation. // // In case you want to train SOFTMAX-normalized network which solves classification // problems, you must use another function to create trainer object: // mlpcreatetrainercls(). // // Below we create trainer object which can be used to train regression networks // with 2 inputs and 1 output. // mlpcreatetrainer(2, 1, trn); // // Stage 2: specification of the training set // // By default trainer object stores empty dataset. So to solve your non-empty problem // you have to set dataset by passing to trainer dense or sparse matrix. // // One row of the matrix corresponds to one record A*B=C in the multiplication table. // First two columns store A and B, last column stores C // // [1 * 1 = 1] [ 1 1 1 ] // [1 * 2 = 2] [ 1 2 2 ] // [2 * 1 = 2] = [ 2 1 2 ] // [2 * 2 = 4] [ 2 2 4 ] // real_2d_array xy = "[[1,1,1],[1,2,2],[2,1,2],[2,2,4]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); mlpsetdataset(trn, xy, 4); // // Stage 3: modification of the training parameters. // // You may modify parameters like weights decay or stopping criteria: // * we set moderate weight decay // * we choose iterations limit as stopping condition (another condition - step size - // is zero, which means than this condition is not active) // double wstep = 0.000; if( _spoil_scenario==3 ) wstep = fp_nan; if( _spoil_scenario==4 ) wstep = fp_posinf; if( _spoil_scenario==5 ) wstep = fp_neginf; ae_int_t maxits = 100; mlpsetdecay(trn, 0.01); mlpsetcond(trn, wstep, maxits); // // Stage 4: training. // // We will train several networks with different architecture using same trainer object. // We may change training parameters or even dataset, so different networks are trained // differently. But in this simple example we will train all networks with same settings. // // We create and train three networks: // * network 1 has 2x1 architecture (2 inputs, no hidden neurons, 1 output) // * network 2 has 2x5x1 architecture (2 inputs, 5 hidden neurons, 1 output) // * network 3 has 2x5x5x1 architecture (2 inputs, two hidden layers, 1 output) // // NOTE: these networks solve regression problems. For classification problems you // should use mlpcreatec0/c1/c2 to create neural networks which have SOFTMAX- // normalized outputs. // multilayerperceptron net1; multilayerperceptron net2; multilayerperceptron net3; mlpreport rep; mlpcreate0(2, 1, net1); mlpcreate1(2, 5, 1, net2); mlpcreate2(2, 5, 5, 1, net3); mlptrainnetwork(trn, net1, 5, rep); mlptrainnetwork(trn, net2, 5, rep); mlptrainnetwork(trn, net3, 5, rep); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_trainerobject"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_crossvalidation // Cross-validation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example shows how to perform cross-validation with ALGLIB // mlptrainer trn; multilayerperceptron network; mlpreport rep; // // Training set: f(x)=1/(x^2+1) // One row corresponds to one record [x,f(x)] // real_2d_array xy = "[[-2.0,0.2],[-1.6,0.3],[-1.3,0.4],[-1,0.5],[-0.6,0.7],[-0.3,0.9],[0,1],[2.0,0.2],[1.6,0.3],[1.3,0.4],[1,0.5],[0.6,0.7],[0.3,0.9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // Trainer object is created. // Dataset is attached to trainer object. // // NOTE: it is not good idea to perform cross-validation on sample // as small as ours (13 examples). It is done for demonstration // purposes only. Generalization error estimates won't be // precise enough for practical purposes. // mlpcreatetrainer(1, 1, trn); mlpsetdataset(trn, xy, 13); // // The key property of the cross-validation is that it estimates // generalization properties of neural ARCHITECTURE. It does NOT // estimates generalization error of some specific network which // is passed to the k-fold CV routine. // // In our example we create 1x4x1 neural network and pass it to // CV routine without training it. Original state of the network // is not used for cross-validation - each round is restarted from // random initial state. Only geometry of network matters. // // We perform 5 restarts from different random positions for each // of the 10 cross-validation rounds. // mlpcreate1(1, 4, 1, network); mlpkfoldcv(trn, network, 5, 10, rep); // // Cross-validation routine stores estimates of the generalization // error to MLP report structure. You may examine its fields and // see estimates of different errors (RMS, CE, Avg). // // Because cross-validation is non-deterministic, in our manual we // can not say what values will be stored to rep after call to // mlpkfoldcv(). Every CV round will return slightly different // estimates. // _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_crossvalidation"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_ensembles_es // Early stopping ensembles // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example shows how to train early stopping ensebles. // mlptrainer trn; mlpensemble ensemble; mlpreport rep; // // Training set: f(x)=1/(x^2+1) // One row corresponds to one record [x,f(x)] // real_2d_array xy = "[[-2.0,0.2],[-1.6,0.3],[-1.3,0.4],[-1,0.5],[-0.6,0.7],[-0.3,0.9],[0,1],[2.0,0.2],[1.6,0.3],[1.3,0.4],[1,0.5],[0.6,0.7],[0.3,0.9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); // // Trainer object is created. // Dataset is attached to trainer object. // // NOTE: it is not good idea to use early stopping ensemble on sample // as small as ours (13 examples). It is done for demonstration // purposes only. Ensemble training algorithm won't find good // solution on such small sample. // mlpcreatetrainer(1, 1, trn); mlpsetdataset(trn, xy, 13); // // Ensemble is created and trained. Each of 50 network is trained // with 5 restarts. // mlpecreate1(1, 4, 1, 50, ensemble); mlptrainensemblees(trn, ensemble, 5, rep); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_ensembles_es"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nn_parallel // Parallel training // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example shows how to use parallel functionality of ALGLIB. // We generate simple 1-dimensional regression problem and show how // to use parallel training, parallel cross-validation, parallel // training of neural ensembles. // // We assume that you already know how to use ALGLIB in serial mode // and concentrate on its parallel capabilities. // // NOTE: it is not good idea to use parallel features on sample as small // as ours (13 examples). It is done only for demonstration purposes. // mlptrainer trn; multilayerperceptron network; mlpensemble ensemble; mlpreport rep; real_2d_array xy = "[[-2.0,0.2],[-1.6,0.3],[-1.3,0.4],[-1,0.5],[-0.6,0.7],[-0.3,0.9],[0,1],[2.0,0.2],[1.6,0.3],[1.3,0.4],[1,0.5],[0.6,0.7],[0.3,0.9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); mlpcreatetrainer(1, 1, trn); mlpsetdataset(trn, xy, 13); mlpcreate1(1, 4, 1, network); mlpecreate1(1, 4, 1, 50, ensemble); // // Below we demonstrate how to perform: // * parallel training of individual networks // * parallel cross-validation // * parallel training of neural ensembles // // In order to use multithreading, you have to: // 1) Install SMP edition of ALGLIB. // 2) This step is specific for C++ users: you should activate OS-specific // capabilities of ALGLIB by defining AE_OS=AE_POSIX (for *nix systems) // or AE_OS=AE_WINDOWS (for Windows systems). // C# users do not have to perform this step because C# programs are // portable across different systems without OS-specific tuning. // 3) Tell ALGLIB that you want it to use multithreading by means of // setnworkers() call: // * alglib::setnworkers(0) = use all cores // * alglib::setnworkers(-1) = leave one core unused // * alglib::setnworkers(-2) = leave two cores unused // * alglib::setnworkers(+2) = use 2 cores (even if you have more) // During runtime ALGLIB will automatically determine whether it is // feasible to start worker threads and split your task between cores. // alglib::setnworkers(+2); // // First, we perform parallel training of individual network with 5 // restarts from random positions. These 5 rounds of training are // executed in parallel manner, with best network chosen after // training. // // ALGLIB can use additional way to speed up computations - divide // dataset into smaller subsets and process these subsets // simultaneously. It allows us to efficiently parallelize even // single training round. This operation is performed automatically // for large datasets, but our toy dataset is too small. // mlptrainnetwork(trn, network, 5, rep); // // Then, we perform parallel 10-fold cross-validation, with 5 random // restarts per each CV round. I.e., 5*10=50 networks are trained // in total. All these operations can be parallelized. // // NOTE: again, ALGLIB can parallelize calculation of gradient // over entire dataset - but our dataset is too small. // mlpkfoldcv(trn, network, 5, 10, rep); // // Finally, we train early stopping ensemble of 50 neural networks, // each of them is trained with 5 random restarts. I.e., 5*50=250 // networks aretrained in total. // mlptrainensemblees(trn, ensemble, 5, rep); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nn_parallel"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST clst_ahc // Simple hierarchical clusterization with Euclidean distance function // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple clusterization example // // We have a set of points in 2D space: // (P0,P1,P2,P3,P4) = ((1,1),(1,2),(4,1),(2,3),(4,1.5)) // // | // | P3 // | // | P1 // | P4 // | P0 P2 // |------------------------- // // We want to perform Agglomerative Hierarchic Clusterization (AHC), // using complete linkage (default algorithm) and Euclidean distance // (default metric). // // In order to do that, we: // * create clusterizer with clusterizercreate() // * set points XY and metric (2=Euclidean) with clusterizersetpoints() // * run AHC algorithm with clusterizerrunahc // // You may see that clusterization itself is a minor part of the example, // most of which is dominated by comments :) // clusterizerstate s; ahcreport rep; real_2d_array xy = "[[1,1],[1,2],[4,1],[2,3],[4,1.5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); clusterizercreate(s); clusterizersetpoints(s, xy, 2); clusterizerrunahc(s, rep); // // Now we've built our clusterization tree. Rep.z contains information which // is required to build dendrogram. I-th row of rep.z represents one merge // operation, with first cluster to merge having index rep.z[I,0] and second // one having index rep.z[I,1]. Merge result has index NPoints+I. // // Clusters with indexes less than NPoints are single-point initial clusters, // while ones with indexes from NPoints to 2*NPoints-2 are multi-point // clusters created during merges. // // In our example, Z=[[2,4], [0,1], [3,6], [5,7]] // // It means that: // * first, we merge C2=(P2) and C4=(P4), and create C5=(P2,P4) // * then, we merge C2=(P0) and C1=(P1), and create C6=(P0,P1) // * then, we merge C3=(P3) and C6=(P0,P1), and create C7=(P0,P1,P3) // * finally, we merge C5 and C7 and create C8=(P0,P1,P2,P3,P4) // // Thus, we have following dendrogram: // // ------8----- // | | // | ----7---- // | | | // ---5--- | ---6--- // | | | | | // P2 P4 P3 P0 P1 // _TestResult = _TestResult && doc_test_int_matrix(rep.z, "[[2,4],[0,1],[3,6],[5,7]]"); // // We've built dendrogram above by reordering our dataset. // // Without such reordering it would be impossible to build dendrogram without // intersections. Luckily, ahcreport structure contains two additional fields // which help to build dendrogram from your data: // * rep.p, which contains permutation applied to dataset // * rep.pm, which contains another representation of merges // // In our example we have: // * P=[3,4,0,2,1] // * PZ=[[0,0,1,1,0,0],[3,3,4,4,0,0],[2,2,3,4,0,1],[0,1,2,4,1,2]] // // Permutation array P tells us that P0 should be moved to position 3, // P1 moved to position 4, P2 moved to position 0 and so on: // // (P0 P1 P2 P3 P4) => (P2 P4 P3 P0 P1) // // Merges array PZ tells us how to perform merges on the sorted dataset. // One row of PZ corresponds to one merge operations, with first pair of // elements denoting first of the clusters to merge (start index, end // index) and next pair of elements denoting second of the clusters to // merge. Clusters being merged are always adjacent, with first one on // the left and second one on the right. // // For example, first row of PZ tells us that clusters [0,0] and [1,1] are // merged (single-point clusters, with first one containing P2 and second // one containing P4). Third row of PZ tells us that we merge one single- // point cluster [2,2] with one two-point cluster [3,4]. // // There are two more elements in each row of PZ. These are the helper // elements, which denote HEIGHT (not size) of left and right subdendrograms. // For example, according to PZ, first two merges are performed on clusterization // trees of height 0, while next two merges are performed on 0-1 and 1-2 // pairs of trees correspondingly. // _TestResult = _TestResult && doc_test_int_vector(rep.p, "[3,4,0,2,1]"); _TestResult = _TestResult && doc_test_int_matrix(rep.pm, "[[0,0,1,1,0,0],[3,3,4,4,0,0],[2,2,3,4,0,1],[0,1,2,4,1,2]]"); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "clst_ahc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST clst_kmeans // Simple k-means clusterization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple clusterization example // // We have a set of points in 2D space: // (P0,P1,P2,P3,P4) = ((1,1),(1,2),(4,1),(2,3),(4,1.5)) // // | // | P3 // | // | P1 // | P4 // | P0 P2 // |------------------------- // // We want to perform k-means++ clustering with K=2. // // In order to do that, we: // * create clusterizer with clusterizercreate() // * set points XY and metric (must be Euclidean, distype=2) with clusterizersetpoints() // * (optional) set number of restarts from random positions to 5 // * run k-means algorithm with clusterizerrunkmeans() // // You may see that clusterization itself is a minor part of the example, // most of which is dominated by comments :) // clusterizerstate s; kmeansreport rep; real_2d_array xy = "[[1,1],[1,2],[4,1],[2,3],[4,1.5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); clusterizercreate(s); clusterizersetpoints(s, xy, 2); clusterizersetkmeanslimits(s, 5, 0); clusterizerrunkmeans(s, 2, rep); // // We've performed clusterization, and it succeeded (completion code is +1). // // Now first center is stored in the first row of rep.c, second one is stored // in the second row. rep.cidx can be used to determine which center is // closest to some specific point of the dataset. // _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); // We called clusterizersetpoints() with disttype=2 because k-means++ // algorithm does NOT support metrics other than Euclidean. But what if we // try to use some other metric? // // We change metric type by calling clusterizersetpoints() one more time, // and try to run k-means algo again. It fails. // clusterizersetpoints(s, xy, 0); clusterizerrunkmeans(s, 2, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, -5); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "clst_kmeans"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST clst_linkage // Clusterization with different linkage types // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // We have a set of points in 1D space: // (P0,P1,P2,P3,P4) = (1, 3, 10, 16, 20) // // We want to perform Agglomerative Hierarchic Clusterization (AHC), // using either complete or single linkage and Euclidean distance // (default metric). // // First two steps merge P0/P1 and P3/P4 independently of the linkage type. // However, third step depends on linkage type being used: // * in case of complete linkage P2=10 is merged with [P0,P1] // * in case of single linkage P2=10 is merged with [P3,P4] // clusterizerstate s; ahcreport rep; real_2d_array xy = "[[1],[3],[10],[16],[20]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); integer_1d_array cidx; integer_1d_array cz; clusterizercreate(s); clusterizersetpoints(s, xy, 2); // use complete linkage, reduce set down to 2 clusters. // print clusterization with clusterizergetkclusters(2). // P2 must belong to [P0,P1] clusterizersetahcalgo(s, 0); clusterizerrunahc(s, rep); clusterizergetkclusters(rep, 2, cidx, cz); _TestResult = _TestResult && doc_test_int_vector(cidx, "[1,1,1,0,0]"); // use single linkage, reduce set down to 2 clusters. // print clusterization with clusterizergetkclusters(2). // P2 must belong to [P2,P3] clusterizersetahcalgo(s, 1); clusterizerrunahc(s, rep); clusterizergetkclusters(rep, 2, cidx, cz); _TestResult = _TestResult && doc_test_int_vector(cidx, "[0,0,1,1,1]"); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "clst_linkage"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST clst_distance // Clusterization with different metric types // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // We have three points in 4D space: // (P0,P1,P2) = ((1, 2, 1, 2), (6, 7, 6, 7), (7, 6, 7, 6)) // // We want to try clustering them with different distance functions. // Distance function is chosen when we add dataset to the clusterizer. // We can choose several distance types - Euclidean, city block, Chebyshev, // several correlation measures or user-supplied distance matrix. // // Here we'll try three distances: Euclidean, Pearson correlation, // user-supplied distance matrix. Different distance functions lead // to different choices being made by algorithm during clustering. // clusterizerstate s; ahcreport rep; ae_int_t disttype; real_2d_array xy = "[[1, 2, 1, 2], [6, 7, 6, 7], [7, 6, 7, 6]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); clusterizercreate(s); // With Euclidean distance function (disttype=2) two closest points // are P1 and P2, thus: // * first, we merge P1 and P2 to form C3=[P1,P2] // * second, we merge P0 and C3 to form C4=[P0,P1,P2] disttype = 2; clusterizersetpoints(s, xy, disttype); clusterizerrunahc(s, rep); _TestResult = _TestResult && doc_test_int_matrix(rep.z, "[[1,2],[0,3]]"); // With Pearson correlation distance function (disttype=10) situation // is different - distance between P0 and P1 is zero, thus: // * first, we merge P0 and P1 to form C3=[P0,P1] // * second, we merge P2 and C3 to form C4=[P0,P1,P2] disttype = 10; clusterizersetpoints(s, xy, disttype); clusterizerrunahc(s, rep); _TestResult = _TestResult && doc_test_int_matrix(rep.z, "[[0,1],[2,3]]"); // Finally, we try clustering with user-supplied distance matrix: // [ 0 3 1 ] // P = [ 3 0 3 ], where P[i,j] = dist(Pi,Pj) // [ 1 3 0 ] // // * first, we merge P0 and P2 to form C3=[P0,P2] // * second, we merge P1 and C3 to form C4=[P0,P1,P2] real_2d_array d = "[[0,3,1],[3,0,3],[1,3,0]]"; clusterizersetdistances(s, d, true); clusterizerrunahc(s, rep); _TestResult = _TestResult && doc_test_int_matrix(rep.z, "[[0,2],[1,3]]"); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "clst_distance"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST clst_kclusters // Obtaining K top clusters from clusterization tree // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // We have a set of points in 2D space: // (P0,P1,P2,P3,P4) = ((1,1),(1,2),(4,1),(2,3),(4,1.5)) // // | // | P3 // | // | P1 // | P4 // | P0 P2 // |------------------------- // // We perform Agglomerative Hierarchic Clusterization (AHC) and we want // to get top K clusters from clusterization tree for different K. // clusterizerstate s; ahcreport rep; real_2d_array xy = "[[1,1],[1,2],[4,1],[2,3],[4,1.5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); integer_1d_array cidx; integer_1d_array cz; clusterizercreate(s); clusterizersetpoints(s, xy, 2); clusterizerrunahc(s, rep); // with K=5, every points is assigned to its own cluster: // C0=P0, C1=P1 and so on... clusterizergetkclusters(rep, 5, cidx, cz); _TestResult = _TestResult && doc_test_int_vector(cidx, "[0,1,2,3,4]"); // with K=1 we have one large cluster C0=[P0,P1,P2,P3,P4,P5] clusterizergetkclusters(rep, 1, cidx, cz); _TestResult = _TestResult && doc_test_int_vector(cidx, "[0,0,0,0,0]"); // with K=3 we have three clusters C0=[P3], C1=[P2,P4], C2=[P0,P1] clusterizergetkclusters(rep, 3, cidx, cz); _TestResult = _TestResult && doc_test_int_vector(cidx, "[2,2,1,0,1]"); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "clst_kclusters"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST randomforest_cls // Simple classification with random forests // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple classification example: classify points (x,y) in 2D space // as ones with x>=0 and ones with x<0 (y is ignored, but our classifier // has to find out it). // // First, we have to create decision forest builder object, load dataset and // specify training settings. Our dataset is specified as matrix, which has // following format: // // x0 y0 class0 // x1 y1 class1 // x2 y2 class2 // .... // // Here xi and yi can be any values (and in fact you can have any number of // independent variables), and classi MUST be integer number in [0,NClasses) // range. In our example we denote points with x>=0 as class #0, and // ones with negative xi as class #1. // // NOTE: if you want to solve regression problem, specify NClasses=1. In // this case last column of xy can be any numeric value. // // For the sake of simplicity, our example includes only 4-point dataset. // However, random forests are able to cope with extremely large datasets // having millions of examples. // decisionforestbuilder builder; ae_int_t nvars = 2; ae_int_t nclasses = 2; ae_int_t npoints = 4; real_2d_array xy = "[[1,1,0],[1,-1,0],[-1,1,1],[-1,-1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); dfbuildercreate(builder); dfbuildersetdataset(builder, xy, npoints, nvars, nclasses); // in our example we train decision forest using full sample - it allows us // to get zero classification error. However, in practical applications smaller // values are used: 50%, 25%, 5% or even less. dfbuildersetsubsampleratio(builder, 1.0); // we train random forest with just one tree; again, in real life situations // you typically need from 50 to 500 trees. ae_int_t ntrees = 1; decisionforest forest; dfreport rep; dfbuilderbuildrandomforest(builder, ntrees, forest, rep); // with such settings (100% of the training set is used) you can expect // zero classification error. Beautiful results, but remember - in real life // you do not need zero TRAINING SET error, you need good generalization. _TestResult = _TestResult && doc_test_real(rep.relclserror, 0.0000, 0.00005); // now, let's perform some simple processing with dfprocess() real_1d_array x = "[+1,0]"; real_1d_array y = "[]"; dfprocess(forest, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[+1,0]", 0.0005); // another option is to use dfprocess0() which returns just first component // of the output vector y. ideal for regression problems and binary classifiers. double y0; y0 = dfprocess0(forest, x); _TestResult = _TestResult && doc_test_real(y0, 1.000, 0.0005); // finally, you can use dfclassify() which returns most probable class index (i.e. argmax y[i]). ae_int_t i; i = dfclassify(forest, x); _TestResult = _TestResult && doc_test_int(i, 0); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "randomforest_cls"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST randomforest_reg // Simple regression with decision forest // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple regression example: model f(x,y)=x+y // // First, we have to create DF builder object, load dataset and specify // training settings. Our dataset is specified as matrix, which has following // format: // // x0 y0 f0 // x1 y1 f1 // x2 y2 f2 // .... // // Here xi and yi can be any values, and fi is a dependent function value. // // NOTE: you can also solve classification problems with DF models, see // another example for this unit. // decisionforestbuilder builder; ae_int_t nvars = 2; ae_int_t nclasses = 1; ae_int_t npoints = 4; real_2d_array xy = "[[1,1,+2],[1,-1,0],[-1,1,0],[-1,-1,-2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); dfbuildercreate(builder); dfbuildersetdataset(builder, xy, npoints, nvars, nclasses); // in our example we train decision forest using full sample - it allows us // to get zero classification error. However, in practical applications smaller // values are used: 50%, 25%, 5% or even less. dfbuildersetsubsampleratio(builder, 1.0); // we train random forest with just one tree; again, in real life situations // you typically need from 50 to 500 trees. ae_int_t ntrees = 1; decisionforest model; dfreport rep; dfbuilderbuildrandomforest(builder, ntrees, model, rep); // with such settings (full sample is used) you can expect zero RMS error on the // training set. Beautiful results, but remember - in real life you do not // need zero TRAINING SET error, you need good generalization. _TestResult = _TestResult && doc_test_real(rep.rmserror, 0.0000, 0.00005); // now, let's perform some simple processing with dfprocess() real_1d_array x = "[+1,+1]"; real_1d_array y = "[]"; dfprocess(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[+2]", 0.0005); // another option is to use dfprocess0() which returns just first component // of the output vector y. ideal for regression problems and binary classifiers. double y0; y0 = dfprocess0(model, x); _TestResult = _TestResult && doc_test_real(y0, 2.000, 0.0005); // there also exist another convenience function, dfclassify(), // but it does not work for regression problems - it always returns -1. ae_int_t i; i = dfclassify(model, x); _TestResult = _TestResult && doc_test_int(i, -1); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "randomforest_reg"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST knn_cls // Simple classification with KNN model // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple classification example: classify points (x,y) in 2D space // as ones with x>=0 and ones with x<0 (y is ignored, but our classifier // has to find out it). // // First, we have to create KNN builder object, load dataset and specify // training settings. Our dataset is specified as matrix, which has following // format: // // x0 y0 class0 // x1 y1 class1 // x2 y2 class2 // .... // // Here xi and yi can be any values (and in fact you can have any number of // independent variables), and classi MUST be integer number in [0,NClasses) // range. In our example we denote points with x>=0 as class #0, and // ones with negative xi as class #1. // // NOTE: if you want to solve regression problem, specify dataset in similar // format, but with dependent variable(s) instead of class labels. You // can have dataset with multiple dependent variables, by the way! // // For the sake of simplicity, our example includes only 4-point dataset and // really simple K=1 nearest neighbor search. Industrial problems typically // need larger values of K. // knnbuilder builder; ae_int_t nvars = 2; ae_int_t nclasses = 2; ae_int_t npoints = 4; real_2d_array xy = "[[1,1,0],[1,-1,0],[-1,1,1],[-1,-1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); knnbuildercreate(builder); knnbuildersetdatasetcls(builder, xy, npoints, nvars, nclasses); // we build KNN model with k=1 and eps=0 (exact k-nn search is performed) ae_int_t k = 1; double eps = 0; knnmodel model; knnreport rep; knnbuilderbuildknnmodel(builder, k, eps, model, rep); // with such settings (k=1 is used) you can expect zero classification // error on training set. Beautiful results, but remember - in real life // you do not need zero TRAINING SET error, you need good generalization. _TestResult = _TestResult && doc_test_real(rep.relclserror, 0.0000, 0.00005); // now, let's perform some simple processing with knnprocess() real_1d_array x = "[+1,0]"; real_1d_array y = "[]"; knnprocess(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[+1,0]", 0.0005); // another option is to use knnprocess0() which returns just first component // of the output vector y. ideal for regression problems and binary classifiers. double y0; y0 = knnprocess0(model, x); _TestResult = _TestResult && doc_test_real(y0, 1.000, 0.0005); // finally, you can use knnclassify() which returns most probable class index (i.e. argmax y[i]). ae_int_t i; i = knnclassify(model, x); _TestResult = _TestResult && doc_test_int(i, 0); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "knn_cls"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST knn_reg // Simple classification with KNN model // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // The very simple regression example: model f(x,y)=x+y // // First, we have to create KNN builder object, load dataset and specify // training settings. Our dataset is specified as matrix, which has following // format: // // x0 y0 f0 // x1 y1 f1 // x2 y2 f2 // .... // // Here xi and yi can be any values, and fi is a dependent function value. // By the way, with KNN algorithm you can even model functions with multiple // dependent variables! // // NOTE: you can also solve classification problems with KNN models, see // another example for this unit. // // For the sake of simplicity, our example includes only 4-point dataset and // really simple K=1 nearest neighbor search. Industrial problems typically // need larger values of K. // knnbuilder builder; ae_int_t nvars = 2; ae_int_t nout = 1; ae_int_t npoints = 4; real_2d_array xy = "[[1,1,+2],[1,-1,0],[-1,1,0],[-1,-1,-2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); knnbuildercreate(builder); knnbuildersetdatasetreg(builder, xy, npoints, nvars, nout); // we build KNN model with k=1 and eps=0 (exact k-nn search is performed) ae_int_t k = 1; double eps = 0; knnmodel model; knnreport rep; knnbuilderbuildknnmodel(builder, k, eps, model, rep); // with such settings (k=1 is used) you can expect zero RMS error on the // training set. Beautiful results, but remember - in real life you do not // need zero TRAINING SET error, you need good generalization. _TestResult = _TestResult && doc_test_real(rep.rmserror, 0.0000, 0.00005); // now, let's perform some simple processing with knnprocess() real_1d_array x = "[+1,+1]"; real_1d_array y = "[]"; knnprocess(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[+2]", 0.0005); // another option is to use knnprocess0() which returns just first component // of the output vector y. ideal for regression problems and binary classifiers. double y0; y0 = knnprocess0(model, x); _TestResult = _TestResult && doc_test_real(y0, 2.000, 0.0005); // there also exist another convenience function, knnclassify(), // but it does not work for regression problems - it always returns -1. ae_int_t i; i = knnclassify(model, x); _TestResult = _TestResult && doc_test_int(i, -1); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "knn_reg"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST autogk_d1 // Integrating f=exp(x) by adaptive integrator // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // This example demonstrates integration of f=exp(x) on [0,1]: // * first, autogkstate is initialized // * then we call integration function // * and finally we obtain results with autogkresults() call // double a = 0; if( _spoil_scenario==0 ) a = fp_nan; if( _spoil_scenario==1 ) a = fp_posinf; if( _spoil_scenario==2 ) a = fp_neginf; double b = 1; if( _spoil_scenario==3 ) b = fp_nan; if( _spoil_scenario==4 ) b = fp_posinf; if( _spoil_scenario==5 ) b = fp_neginf; autogkstate s; double v; autogkreport rep; autogksmooth(a, b, s); alglib::autogkintegrate(s, int_function_1_func); autogkresults(s, v, rep); _TestResult = _TestResult && doc_test_real(v, 1.7182, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "autogk_d1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST fft_complex_d1 // Complex FFT: simple example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // first we demonstrate forward FFT: // [1i,1i,1i,1i] is converted to [4i, 0, 0, 0] // complex_1d_array z = "[1i,1i,1i,1i]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(z); if( _spoil_scenario==1 ) spoil_vector_by_posinf(z); if( _spoil_scenario==2 ) spoil_vector_by_neginf(z); fftc1d(z); _TestResult = _TestResult && doc_test_complex_vector(z, "[4i,0,0,0]", 0.0001); // // now we convert [4i, 0, 0, 0] back to [1i,1i,1i,1i] // with backward FFT // fftc1dinv(z); _TestResult = _TestResult && doc_test_complex_vector(z, "[1i,1i,1i,1i]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "fft_complex_d1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST fft_complex_d2 // Complex FFT: advanced example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // first we demonstrate forward FFT: // [0,1,0,1i] is converted to [1+1i, -1-1i, -1-1i, 1+1i] // complex_1d_array z = "[0,1,0,1i]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(z); if( _spoil_scenario==1 ) spoil_vector_by_posinf(z); if( _spoil_scenario==2 ) spoil_vector_by_neginf(z); fftc1d(z); _TestResult = _TestResult && doc_test_complex_vector(z, "[1+1i, -1-1i, -1-1i, 1+1i]", 0.0001); // // now we convert result back with backward FFT // fftc1dinv(z); _TestResult = _TestResult && doc_test_complex_vector(z, "[0,1,0,1i]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "fft_complex_d2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST fft_real_d1 // Real FFT: simple example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // first we demonstrate forward FFT: // [1,1,1,1] is converted to [4, 0, 0, 0] // real_1d_array x = "[1,1,1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); complex_1d_array f; real_1d_array x2; fftr1d(x, f); _TestResult = _TestResult && doc_test_complex_vector(f, "[4,0,0,0]", 0.0001); // // now we convert [4, 0, 0, 0] back to [1,1,1,1] // with backward FFT // fftr1dinv(f, x2); _TestResult = _TestResult && doc_test_real_vector(x2, "[1,1,1,1]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "fft_real_d1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST fft_real_d2 // Real FFT: advanced example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // first we demonstrate forward FFT: // [1,2,3,4] is converted to [10, -2+2i, -2, -2-2i] // // note that output array is self-adjoint: // * f[0] = conj(f[0]) // * f[1] = conj(f[3]) // * f[2] = conj(f[2]) // real_1d_array x = "[1,2,3,4]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); complex_1d_array f; real_1d_array x2; fftr1d(x, f); _TestResult = _TestResult && doc_test_complex_vector(f, "[10, -2+2i, -2, -2-2i]", 0.0001); // // now we convert [10, -2+2i, -2, -2-2i] back to [1,2,3,4] // fftr1dinv(f, x2); _TestResult = _TestResult && doc_test_real_vector(x2, "[1,2,3,4]", 0.0001); // // remember that F is self-adjoint? It means that we can pass just half // (slightly larger than half) of F to inverse real FFT and still get our result. // // I.e. instead [10, -2+2i, -2, -2-2i] we pass just [10, -2+2i, -2] and everything works! // // NOTE: in this case we should explicitly pass array length (which is 4) to ALGLIB; // if not, it will automatically use array length to determine FFT size and // will erroneously make half-length FFT. // f = "[10, -2+2i, -2]"; fftr1dinv(f, 4, x2); _TestResult = _TestResult && doc_test_real_vector(x2, "[1,2,3,4]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "fft_real_d2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST fft_complex_e1 // error detection in backward FFT // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { complex_1d_array z = "[0,2,0,-2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(z); if( _spoil_scenario==1 ) spoil_vector_by_posinf(z); if( _spoil_scenario==2 ) spoil_vector_by_neginf(z); fftc1dinv(z); _TestResult = _TestResult && doc_test_complex_vector(z, "[0,1i,0,-1i]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "fft_complex_e1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST idw_d_mstab // Simple model built with IDW-MSTAB algorithm // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example illustrates basic concepts of the IDW models: // creation and evaluation. // // Suppose that we have set of 2-dimensional points with associated // scalar function values, and we want to build an IDW model using // our data. // // NOTE: we can work with N-dimensional models and vector-valued functions too :) // // Typical sequence of steps is given below: // 1. we create IDW builder object // 2. we attach our dataset to the IDW builder and tune algorithm settings // 3. we generate IDW model // 4. we use IDW model instance (evaluate, serialize, etc.) // double v; // // Step 1: IDW builder creation. // // We have to specify dimensionality of the space (2 or 3) and // dimensionality of the function (scalar or vector). // // New builder object is empty - it has not dataset and uses // default model construction settings // idwbuilder builder; idwbuildercreate(2, 1, builder); // // Step 2: dataset addition // // XY contains two points - x0=(-1,0) and x1=(+1,0) - // and two function values f(x0)=2, f(x1)=3. // real_2d_array xy = "[[-1,0,2],[+1,0,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); idwbuildersetpoints(builder, xy); // // Step 3: choose IDW algorithm and generate model // // We use modified stabilized IDW algorithm with following parameters: // * SRad - set to 5.0 (search radius must be large enough) // // IDW-MSTAB algorithm is a state-of-the-art implementation of IDW which // is competitive with RBFs and bicubic splines. See comments on the // idwbuildersetalgomstab() function for more information. // idwmodel model; idwreport rep; idwbuildersetalgomstab(builder, 5.0); idwfit(builder, model, rep); // // Step 4: model was built, evaluate its value // v = idwcalc2(model, 1.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 3.000, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "idw_d_mstab"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST idw_d_serialize // IDW model serialization/unserialization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example shows how to serialize and unserialize IDW model. // // Suppose that we have set of 2-dimensional points with associated // scalar function values, and we have built an IDW model using // our data. // // This model can be serialized to string or stream. ALGLIB supports // flexible (un)serialization, i.e. you can move serialized model // representation between different machines (32-bit or 64-bit), // different CPU architectures (x86/64, ARM) or even different // programming languages supported by ALGLIB (C#, C++, ...). // // Our first step is to build model, evaluate it at point (1,0), // and serialize it to string. // std::string s; double v; real_2d_array xy = "[[-1,0,2],[+1,0,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); idwbuilder builder; idwmodel model; idwmodel model2; idwreport rep; idwbuildercreate(2, 1, builder); idwbuildersetpoints(builder, xy); idwbuildersetalgomstab(builder, 5.0); idwfit(builder, model, rep); v = idwcalc2(model, 1.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 3.000, 0.005); // // Serialization + unserialization to a different instance // of the model class. // alglib::idwserialize(model, s); alglib::idwunserialize(s, model2); // // Evaluate unserialized model at the same point // v = idwcalc2(model2, 1.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 3.000, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "idw_d_serialize"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline1d_d_linear // Piecewise linear spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // We use piecewise linear spline to interpolate f(x)=x^2 sampled // at 5 equidistant nodes on [-1,+1]. // real_1d_array x = "[-1.0,-0.5,0.0,+0.5,+1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[+1.0,0.25,0.0,0.25,+1.0]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); double t = 0.25; if( _spoil_scenario==10 ) t = fp_posinf; if( _spoil_scenario==11 ) t = fp_neginf; double v; spline1dinterpolant s; // build spline spline1dbuildlinear(x, y, s); // calculate S(0.25) - it is quite different from 0.25^2=0.0625 v = spline1dcalc(s, t); _TestResult = _TestResult && doc_test_real(v, 0.125, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline1d_d_linear"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline1d_d_cubic // Cubic spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { // // We use cubic spline to interpolate f(x)=x^2 sampled // at 5 equidistant nodes on [-1,+1]. // // First, we use default boundary conditions ("parabolically terminated // spline") because cubic spline built with such boundary conditions // will exactly reproduce any quadratic f(x). // // Then we try to use natural boundary conditions // d2S(-1)/dx^2 = 0.0 // d2S(+1)/dx^2 = 0.0 // and see that such spline interpolated f(x) with small error. // real_1d_array x = "[-1.0,-0.5,0.0,+0.5,+1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[+1.0,0.25,0.0,0.25,+1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); double t = 0.25; if( _spoil_scenario==8 ) t = fp_posinf; if( _spoil_scenario==9 ) t = fp_neginf; double v; spline1dinterpolant s; ae_int_t natural_bound_type = 2; // // Test exact boundary conditions: build S(x), calculare S(0.25) // (almost same as original function) // spline1dbuildcubic(x, y, s); v = spline1dcalc(s, t); _TestResult = _TestResult && doc_test_real(v, 0.0625, 0.00001); // // Test natural boundary conditions: build S(x), calculare S(0.25) // (small interpolation error) // spline1dbuildcubic(x, y, 5, natural_bound_type, 0.0, natural_bound_type, 0.0, s); v = spline1dcalc(s, t); _TestResult = _TestResult && doc_test_real(v, 0.0580, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline1d_d_cubic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline1d_d_monotone // Monotone interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { // // Spline built witn spline1dbuildcubic() can be non-monotone even when // Y-values form monotone sequence. Say, for x=[0,1,2] and y=[0,1,1] // cubic spline will monotonically grow until x=1.5 and then start // decreasing. // // That's why ALGLIB provides special spline construction function // which builds spline which preserves monotonicity of the original // dataset. // // NOTE: in case original dataset is non-monotonic, ALGLIB splits it // into monotone subsequences and builds piecewise monotonic spline. // real_1d_array x = "[0,1,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0,1,1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); spline1dinterpolant s; // build spline spline1dbuildmonotone(x, y, s); // calculate S at x = [-0.5, 0.0, 0.5, 1.0, 1.5, 2.0] // you may see that spline is really monotonic double v; v = spline1dcalc(s, -0.5); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.00005); v = spline1dcalc(s, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.00005); v = spline1dcalc(s, +0.5); _TestResult = _TestResult && doc_test_real(v, 0.5000, 0.00005); v = spline1dcalc(s, 1.0); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.00005); v = spline1dcalc(s, 1.5); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.00005); v = spline1dcalc(s, 2.0); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline1d_d_monotone"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline1d_d_griddiff // Differentiation on the grid using cubic splines // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { // // We use cubic spline to do grid differentiation, i.e. having // values of f(x)=x^2 sampled at 5 equidistant nodes on [-1,+1] // we calculate derivatives of cubic spline at nodes WITHOUT // CONSTRUCTION OF SPLINE OBJECT. // // There are efficient functions spline1dgriddiffcubic() and // spline1dgriddiff2cubic() for such calculations. // // We use default boundary conditions ("parabolically terminated // spline") because cubic spline built with such boundary conditions // will exactly reproduce any quadratic f(x). // // Actually, we could use natural conditions, but we feel that // spline which exactly reproduces f() will show us more // understandable results. // real_1d_array x = "[-1.0,-0.5,0.0,+0.5,+1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[+1.0,0.25,0.0,0.25,+1.0]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array d1; real_1d_array d2; // // We calculate first derivatives: they must be equal to 2*x // spline1dgriddiffcubic(x, y, d1); _TestResult = _TestResult && doc_test_real_vector(d1, "[-2.0, -1.0, 0.0, +1.0, +2.0]", 0.0001); // // Now test griddiff2, which returns first AND second derivatives. // First derivative is 2*x, second is equal to 2.0 // spline1dgriddiff2cubic(x, y, d1, d2); _TestResult = _TestResult && doc_test_real_vector(d1, "[-2.0, -1.0, 0.0, +1.0, +2.0]", 0.0001); _TestResult = _TestResult && doc_test_real_vector(d2, "[ 2.0, 2.0, 2.0, 2.0, 2.0]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline1d_d_griddiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline1d_d_convdiff // Resampling using cubic splines // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { // // We use cubic spline to do resampling, i.e. having // values of f(x)=x^2 sampled at 5 equidistant nodes on [-1,+1] // we calculate values/derivatives of cubic spline on // another grid (equidistant with 9 nodes on [-1,+1]) // WITHOUT CONSTRUCTION OF SPLINE OBJECT. // // There are efficient functions spline1dconvcubic(), // spline1dconvdiffcubic() and spline1dconvdiff2cubic() // for such calculations. // // We use default boundary conditions ("parabolically terminated // spline") because cubic spline built with such boundary conditions // will exactly reproduce any quadratic f(x). // // Actually, we could use natural conditions, but we feel that // spline which exactly reproduces f() will show us more // understandable results. // real_1d_array x_old = "[-1.0,-0.5,0.0,+0.5,+1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x_old); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x_old); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x_old); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x_old); real_1d_array y_old = "[+1.0,0.25,0.0,0.25,+1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y_old); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y_old); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y_old); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y_old); real_1d_array x_new = "[-1.00,-0.75,-0.50,-0.25,0.00,+0.25,+0.50,+0.75,+1.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(x_new); if( _spoil_scenario==9 ) spoil_vector_by_posinf(x_new); if( _spoil_scenario==10 ) spoil_vector_by_neginf(x_new); real_1d_array y_new; real_1d_array d1_new; real_1d_array d2_new; // // First, conversion without differentiation. // // spline1dconvcubic(x_old, y_old, x_new, y_new); _TestResult = _TestResult && doc_test_real_vector(y_new, "[1.0000, 0.5625, 0.2500, 0.0625, 0.0000, 0.0625, 0.2500, 0.5625, 1.0000]", 0.0001); // // Then, conversion with differentiation (first derivatives only) // // spline1dconvdiffcubic(x_old, y_old, x_new, y_new, d1_new); _TestResult = _TestResult && doc_test_real_vector(y_new, "[1.0000, 0.5625, 0.2500, 0.0625, 0.0000, 0.0625, 0.2500, 0.5625, 1.0000]", 0.0001); _TestResult = _TestResult && doc_test_real_vector(d1_new, "[-2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]", 0.0001); // // Finally, conversion with first and second derivatives // // spline1dconvdiff2cubic(x_old, y_old, x_new, y_new, d1_new, d2_new); _TestResult = _TestResult && doc_test_real_vector(y_new, "[1.0000, 0.5625, 0.2500, 0.0625, 0.0000, 0.0625, 0.2500, 0.5625, 1.0000]", 0.0001); _TestResult = _TestResult && doc_test_real_vector(d1_new, "[-2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]", 0.0001); _TestResult = _TestResult && doc_test_real_vector(d2_new, "[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]", 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline1d_d_convdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST parametric_rdp // Parametric Ramer-Douglas-Peucker approximation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { // // We use RDP algorithm to approximate parametric 2D curve given by // locations in t=0,1,2,3 (see below), which form piecewise linear // trajectory through D-dimensional space (2-dimensional in our example). // // | // | // - * * X2................X3 // | . // | . // - * * . * * * * // | . // | . // - * X1 * * * * // | ..... // | .... // X0----|-----|-----|-----|-----|-----|--- // ae_int_t npoints = 4; ae_int_t ndimensions = 2; real_2d_array x = "[[0,0],[2,1],[3,3],[6,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); // // Approximation of parametric curve is performed by another parametric curve // with lesser amount of points. It allows to work with "compressed" // representation, which needs smaller amount of memory. Say, in our example // (we allow points with error smaller than 0.8) approximation will have // just two sequential sections connecting X0 with X2, and X2 with X3. // // | // | // - * * X2................X3 // | . // | . // - * . * * * * // | . // | . // - . X1 * * * * // | . // | . // X0----|-----|-----|-----|-----|-----|--- // // real_2d_array y; integer_1d_array idxy; ae_int_t nsections; ae_int_t limitcnt = 0; double limiteps = 0.8; if( _spoil_scenario==5 ) limiteps = fp_posinf; if( _spoil_scenario==6 ) limiteps = fp_neginf; parametricrdpfixed(x, npoints, ndimensions, limitcnt, limiteps, y, idxy, nsections); _TestResult = _TestResult && doc_test_int(nsections, 2); _TestResult = _TestResult && doc_test_int_vector(idxy, "[0,2,3]"); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "parametric_rdp"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline3d_trilinear // Trilinear spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<22; _spoil_scenario++) { try { // // We use trilinear spline to interpolate f(x,y,z)=x+xy+z sampled // at (x,y,z) from [0.0, 1.0] X [0.0, 1.0] X [0.0, 1.0]. // // We store x, y and z-values at local arrays with same names. // Function values are stored in the array F as follows: // f[0] (x,y,z) = (0,0,0) // f[1] (x,y,z) = (1,0,0) // f[2] (x,y,z) = (0,1,0) // f[3] (x,y,z) = (1,1,0) // f[4] (x,y,z) = (0,0,1) // f[5] (x,y,z) = (1,0,1) // f[6] (x,y,z) = (0,1,1) // f[7] (x,y,z) = (1,1,1) // real_1d_array x = "[0.0, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array z = "[0.0, 1.0]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(z); if( _spoil_scenario==9 ) spoil_vector_by_posinf(z); if( _spoil_scenario==10 ) spoil_vector_by_neginf(z); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(z); real_1d_array f = "[0,1,0,2,1,2,1,3]"; if( _spoil_scenario==12 ) spoil_vector_by_nan(f); if( _spoil_scenario==13 ) spoil_vector_by_posinf(f); if( _spoil_scenario==14 ) spoil_vector_by_neginf(f); if( _spoil_scenario==15 ) spoil_vector_by_deleting_element(f); double vx = 0.50; if( _spoil_scenario==16 ) vx = fp_posinf; if( _spoil_scenario==17 ) vx = fp_neginf; double vy = 0.50; if( _spoil_scenario==18 ) vy = fp_posinf; if( _spoil_scenario==19 ) vy = fp_neginf; double vz = 0.50; if( _spoil_scenario==20 ) vz = fp_posinf; if( _spoil_scenario==21 ) vz = fp_neginf; double v; spline3dinterpolant s; // build spline spline3dbuildtrilinearv(x, 2, y, 2, z, 2, f, 1, s); // calculate S(0.5,0.5,0.5) v = spline3dcalc(s, vx, vy, vz); _TestResult = _TestResult && doc_test_real(v, 1.2500, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline3d_trilinear"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline3d_vector // Vector-valued trilinear spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<22; _spoil_scenario++) { try { // // We use trilinear vector-valued spline to interpolate {f0,f1}={x+xy+z,x+xy+yz+z} // sampled at (x,y,z) from [0.0, 1.0] X [0.0, 1.0] X [0.0, 1.0]. // // We store x, y and z-values at local arrays with same names. // Function values are stored in the array F as follows: // f[0] f0, (x,y,z) = (0,0,0) // f[1] f1, (x,y,z) = (0,0,0) // f[2] f0, (x,y,z) = (1,0,0) // f[3] f1, (x,y,z) = (1,0,0) // f[4] f0, (x,y,z) = (0,1,0) // f[5] f1, (x,y,z) = (0,1,0) // f[6] f0, (x,y,z) = (1,1,0) // f[7] f1, (x,y,z) = (1,1,0) // f[8] f0, (x,y,z) = (0,0,1) // f[9] f1, (x,y,z) = (0,0,1) // f[10] f0, (x,y,z) = (1,0,1) // f[11] f1, (x,y,z) = (1,0,1) // f[12] f0, (x,y,z) = (0,1,1) // f[13] f1, (x,y,z) = (0,1,1) // f[14] f0, (x,y,z) = (1,1,1) // f[15] f1, (x,y,z) = (1,1,1) // real_1d_array x = "[0.0, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array z = "[0.0, 1.0]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(z); if( _spoil_scenario==9 ) spoil_vector_by_posinf(z); if( _spoil_scenario==10 ) spoil_vector_by_neginf(z); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(z); real_1d_array f = "[0,0, 1,1, 0,0, 2,2, 1,1, 2,2, 1,2, 3,4]"; if( _spoil_scenario==12 ) spoil_vector_by_nan(f); if( _spoil_scenario==13 ) spoil_vector_by_posinf(f); if( _spoil_scenario==14 ) spoil_vector_by_neginf(f); if( _spoil_scenario==15 ) spoil_vector_by_deleting_element(f); double vx = 0.50; if( _spoil_scenario==16 ) vx = fp_posinf; if( _spoil_scenario==17 ) vx = fp_neginf; double vy = 0.50; if( _spoil_scenario==18 ) vy = fp_posinf; if( _spoil_scenario==19 ) vy = fp_neginf; double vz = 0.50; if( _spoil_scenario==20 ) vz = fp_posinf; if( _spoil_scenario==21 ) vz = fp_neginf; spline3dinterpolant s; // build spline spline3dbuildtrilinearv(x, 2, y, 2, z, 2, f, 2, s); // calculate S(0.5,0.5,0.5) - we have vector of values instead of single value real_1d_array v; spline3dcalcv(s, vx, vy, vz, v); _TestResult = _TestResult && doc_test_real_vector(v, "[1.2500,1.5000]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline3d_vector"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_d_calcdiff // Interpolation and differentiation using barycentric representation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // Here we demonstrate polynomial interpolation and differentiation // of y=x^2-x sampled at [0,1,2]. Barycentric representation of polynomial is used. // real_1d_array x = "[0,1,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0,0,2]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==10 ) t = fp_posinf; if( _spoil_scenario==11 ) t = fp_neginf; double v; double dv; double d2v; barycentricinterpolant p; // barycentric model is created polynomialbuild(x, y, p); // barycentric interpolation is demonstrated v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); // barycentric differentation is demonstrated barycentricdiff1(p, t, v, dv); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && doc_test_real(dv, -3.0, 0.00005); // second derivatives with barycentric representation barycentricdiff1(p, t, v, dv); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && doc_test_real(dv, -3.0, 0.00005); barycentricdiff2(p, t, v, dv, d2v); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && doc_test_real(dv, -3.0, 0.00005); _TestResult = _TestResult && doc_test_real(d2v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_d_calcdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_d_conv // Conversion between power basis and barycentric representation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { // // Here we demonstrate conversion of y=x^2-x // between power basis and barycentric representation. // real_1d_array a = "[0,-1,+1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(a); if( _spoil_scenario==1 ) spoil_vector_by_posinf(a); if( _spoil_scenario==2 ) spoil_vector_by_neginf(a); double t = 2; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; real_1d_array a2; double v; barycentricinterpolant p; // // a=[0,-1,+1] is decomposition of y=x^2-x in the power basis: // // y = 0 - 1*x + 1*x^2 // // We convert it to the barycentric form. // polynomialpow2bar(a, p); // now we have barycentric interpolation; we can use it for interpolation v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.005); // we can also convert back from barycentric representation to power basis polynomialbar2pow(p, a2); _TestResult = _TestResult && doc_test_real_vector(a2, "[0,-1,+1]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_d_conv"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_d_spec // Polynomial interpolation on special grids (equidistant, Chebyshev I/II) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { // // Temporaries: // * values of y=x^2-x sampled at three special grids: // * equdistant grid spanning [0,2], x[i] = 2*i/(N-1), i=0..N-1 // * Chebyshev-I grid spanning [-1,+1], x[i] = 1 + Cos(PI*(2*i+1)/(2*n)), i=0..N-1 // * Chebyshev-II grid spanning [-1,+1], x[i] = 1 + Cos(PI*i/(n-1)), i=0..N-1 // * barycentric interpolants for these three grids // * vectors to store coefficients of quadratic representation // real_1d_array y_eqdist = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y_eqdist); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y_eqdist); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y_eqdist); real_1d_array y_cheb1 = "[-0.116025,0.000000,1.616025]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(y_cheb1); if( _spoil_scenario==4 ) spoil_vector_by_posinf(y_cheb1); if( _spoil_scenario==5 ) spoil_vector_by_neginf(y_cheb1); real_1d_array y_cheb2 = "[0,0,2]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(y_cheb2); if( _spoil_scenario==7 ) spoil_vector_by_posinf(y_cheb2); if( _spoil_scenario==8 ) spoil_vector_by_neginf(y_cheb2); barycentricinterpolant p_eqdist; barycentricinterpolant p_cheb1; barycentricinterpolant p_cheb2; real_1d_array a_eqdist; real_1d_array a_cheb1; real_1d_array a_cheb2; // // First, we demonstrate construction of barycentric interpolants on // special grids. We unpack power representation to ensure that // interpolant was built correctly. // // In all three cases we should get same quadratic function. // polynomialbuildeqdist(0.0, 2.0, y_eqdist, p_eqdist); polynomialbar2pow(p_eqdist, a_eqdist); _TestResult = _TestResult && doc_test_real_vector(a_eqdist, "[0,-1,+1]", 0.00005); polynomialbuildcheb1(-1, +1, y_cheb1, p_cheb1); polynomialbar2pow(p_cheb1, a_cheb1); _TestResult = _TestResult && doc_test_real_vector(a_cheb1, "[0,-1,+1]", 0.00005); polynomialbuildcheb2(-1, +1, y_cheb2, p_cheb2); polynomialbar2pow(p_cheb2, a_cheb2); _TestResult = _TestResult && doc_test_real_vector(a_cheb2, "[0,-1,+1]", 0.00005); // // Now we demonstrate polynomial interpolation without construction // of the barycentricinterpolant structure. // // We calculate interpolant value at x=-2. // In all three cases we should get same f=6 // double t = -2; if( _spoil_scenario==9 ) t = fp_posinf; if( _spoil_scenario==10 ) t = fp_neginf; double v; v = polynomialcalceqdist(0.0, 2.0, y_eqdist, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); v = polynomialcalccheb1(-1, +1, y_cheb1, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); v = polynomialcalccheb2(-1, +1, y_cheb2, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_d_spec"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_1 // Polynomial interpolation, full list of parameters. // printf("100/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { real_1d_array x = "[0,1,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0,0,2]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==8 ) t = fp_posinf; if( _spoil_scenario==9 ) t = fp_neginf; barycentricinterpolant p; double v; polynomialbuild(x, y, 3, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_2 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; barycentricinterpolant p; double v; polynomialbuildeqdist(0.0, 2.0, y, 3, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_3 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array y = "[-0.116025,0.000000,1.616025]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; barycentricinterpolant p; double v; polynomialbuildcheb1(-1.0, +1.0, y, 3, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_3"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_4 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -2; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; double a = -1; if( _spoil_scenario==6 ) a = fp_nan; if( _spoil_scenario==7 ) a = fp_posinf; if( _spoil_scenario==8 ) a = fp_neginf; double b = +1; if( _spoil_scenario==9 ) b = fp_nan; if( _spoil_scenario==10 ) b = fp_posinf; if( _spoil_scenario==11 ) b = fp_neginf; barycentricinterpolant p; double v; polynomialbuildcheb2(a, b, y, 3, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_4"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_5 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; double v; v = polynomialcalceqdist(0.0, 2.0, y, 3, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_5"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_6 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { real_1d_array y = "[-0.116025,0.000000,1.616025]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -1; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; double a = -1; if( _spoil_scenario==6 ) a = fp_nan; if( _spoil_scenario==7 ) a = fp_posinf; if( _spoil_scenario==8 ) a = fp_neginf; double b = +1; if( _spoil_scenario==9 ) b = fp_nan; if( _spoil_scenario==10 ) b = fp_posinf; if( _spoil_scenario==11 ) b = fp_neginf; double v; v = polynomialcalccheb1(a, b, y, 3, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_6"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_7 // Polynomial interpolation, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); double t = -2; if( _spoil_scenario==4 ) t = fp_posinf; if( _spoil_scenario==5 ) t = fp_neginf; double a = -1; if( _spoil_scenario==6 ) a = fp_nan; if( _spoil_scenario==7 ) a = fp_posinf; if( _spoil_scenario==8 ) a = fp_neginf; double b = +1; if( _spoil_scenario==9 ) b = fp_nan; if( _spoil_scenario==10 ) b = fp_posinf; if( _spoil_scenario==11 ) b = fp_neginf; double v; v = polynomialcalccheb2(a, b, y, 3, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_7"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_8 // Polynomial interpolation: y=x^2-x, equidistant grid, barycentric form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -1; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; barycentricinterpolant p; double v; polynomialbuildeqdist(0.0, 2.0, y, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_8"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_9 // Polynomial interpolation: y=x^2-x, Chebyshev grid (first kind), barycentric form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { real_1d_array y = "[-0.116025,0.000000,1.616025]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -1; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; double a = -1; if( _spoil_scenario==5 ) a = fp_nan; if( _spoil_scenario==6 ) a = fp_posinf; if( _spoil_scenario==7 ) a = fp_neginf; double b = +1; if( _spoil_scenario==8 ) b = fp_nan; if( _spoil_scenario==9 ) b = fp_posinf; if( _spoil_scenario==10 ) b = fp_neginf; barycentricinterpolant p; double v; polynomialbuildcheb1(a, b, y, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_9"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_10 // Polynomial interpolation: y=x^2-x, Chebyshev grid (second kind), barycentric form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -2; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; double a = -1; if( _spoil_scenario==5 ) a = fp_nan; if( _spoil_scenario==6 ) a = fp_posinf; if( _spoil_scenario==7 ) a = fp_neginf; double b = +1; if( _spoil_scenario==8 ) b = fp_nan; if( _spoil_scenario==9 ) b = fp_posinf; if( _spoil_scenario==10 ) b = fp_neginf; barycentricinterpolant p; double v; polynomialbuildcheb2(a, b, y, p); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_10"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_11 // Polynomial interpolation: y=x^2-x, equidistant grid // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -1; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; double v; v = polynomialcalceqdist(0.0, 2.0, y, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_11"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_12 // Polynomial interpolation: y=x^2-x, Chebyshev grid (first kind) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { real_1d_array y = "[-0.116025,0.000000,1.616025]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -1; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; double a = -1; if( _spoil_scenario==5 ) a = fp_nan; if( _spoil_scenario==6 ) a = fp_posinf; if( _spoil_scenario==7 ) a = fp_neginf; double b = +1; if( _spoil_scenario==8 ) b = fp_nan; if( _spoil_scenario==9 ) b = fp_posinf; if( _spoil_scenario==10 ) b = fp_neginf; double v; v = polynomialcalccheb1(a, b, y, t); _TestResult = _TestResult && doc_test_real(v, 2.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_12"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST polint_t_13 // Polynomial interpolation: y=x^2-x, Chebyshev grid (second kind) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<11; _spoil_scenario++) { try { real_1d_array y = "[0,0,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); double t = -2; if( _spoil_scenario==3 ) t = fp_posinf; if( _spoil_scenario==4 ) t = fp_neginf; double a = -1; if( _spoil_scenario==5 ) a = fp_nan; if( _spoil_scenario==6 ) a = fp_posinf; if( _spoil_scenario==7 ) a = fp_neginf; double b = +1; if( _spoil_scenario==8 ) b = fp_nan; if( _spoil_scenario==9 ) b = fp_posinf; if( _spoil_scenario==10 ) b = fp_neginf; double v; v = polynomialcalccheb2(a, b, y, t); _TestResult = _TestResult && doc_test_real(v, 6.0, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "polint_t_13"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_nlf // Nonlinear fitting using function value only // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<24; _spoil_scenario++) { try { // // In this example we demonstrate exponential fitting // by f(x) = exp(-c*x^2) // using function value only. // // Gradient is estimated using combination of numerical differences // and secant updates. diffstep variable stores differentiation step // (we have to tell algorithm what step to use). // real_2d_array x = "[[-1],[-0.8],[-0.6],[-0.4],[-0.2],[0],[0.2],[0.4],[0.6],[0.8],[1.0]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); real_1d_array y = "[0.223130, 0.382893, 0.582748, 0.786628, 0.941765, 1.000000, 0.941765, 0.786628, 0.582748, 0.382893, 0.223130]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array c = "[0.3]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(c); if( _spoil_scenario==11 ) spoil_vector_by_posinf(c); if( _spoil_scenario==12 ) spoil_vector_by_neginf(c); double epsx = 0.000001; if( _spoil_scenario==13 ) epsx = fp_nan; if( _spoil_scenario==14 ) epsx = fp_posinf; if( _spoil_scenario==15 ) epsx = fp_neginf; ae_int_t maxits = 0; ae_int_t info; lsfitstate state; lsfitreport rep; double diffstep = 0.0001; if( _spoil_scenario==16 ) diffstep = fp_nan; if( _spoil_scenario==17 ) diffstep = fp_posinf; if( _spoil_scenario==18 ) diffstep = fp_neginf; // // Fitting without weights // lsfitcreatef(x, y, c, diffstep, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); // // Fitting with weights // (you can change weights and see how it changes result) // real_1d_array w = "[1,1,1,1,1,1,1,1,1,1,1]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(w); if( _spoil_scenario==20 ) spoil_vector_by_posinf(w); if( _spoil_scenario==21 ) spoil_vector_by_neginf(w); if( _spoil_scenario==22 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==23 ) spoil_vector_by_deleting_element(w); lsfitcreatewf(x, y, w, c, diffstep, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_nlf"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_nlfg // Nonlinear fitting using gradient // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // In this example we demonstrate exponential fitting // by f(x) = exp(-c*x^2) // using function value and gradient (with respect to c). // real_2d_array x = "[[-1],[-0.8],[-0.6],[-0.4],[-0.2],[0],[0.2],[0.4],[0.6],[0.8],[1.0]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); real_1d_array y = "[0.223130, 0.382893, 0.582748, 0.786628, 0.941765, 1.000000, 0.941765, 0.786628, 0.582748, 0.382893, 0.223130]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array c = "[0.3]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(c); if( _spoil_scenario==11 ) spoil_vector_by_posinf(c); if( _spoil_scenario==12 ) spoil_vector_by_neginf(c); double epsx = 0.000001; if( _spoil_scenario==13 ) epsx = fp_nan; if( _spoil_scenario==14 ) epsx = fp_posinf; if( _spoil_scenario==15 ) epsx = fp_neginf; ae_int_t maxits = 0; ae_int_t info; lsfitstate state; lsfitreport rep; // // Fitting without weights // lsfitcreatefg(x, y, c, true, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func, function_cx_1_grad); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); // // Fitting with weights // (you can change weights and see how it changes result) // real_1d_array w = "[1,1,1,1,1,1,1,1,1,1,1]"; if( _spoil_scenario==16 ) spoil_vector_by_nan(w); if( _spoil_scenario==17 ) spoil_vector_by_posinf(w); if( _spoil_scenario==18 ) spoil_vector_by_neginf(w); if( _spoil_scenario==19 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(w); lsfitcreatewfg(x, y, w, c, true, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func, function_cx_1_grad); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_nlfg"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_nlfgh // Nonlinear fitting using gradient and Hessian // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // In this example we demonstrate exponential fitting // by f(x) = exp(-c*x^2) // using function value, gradient and Hessian (with respect to c) // real_2d_array x = "[[-1],[-0.8],[-0.6],[-0.4],[-0.2],[0],[0.2],[0.4],[0.6],[0.8],[1.0]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); real_1d_array y = "[0.223130, 0.382893, 0.582748, 0.786628, 0.941765, 1.000000, 0.941765, 0.786628, 0.582748, 0.382893, 0.223130]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array c = "[0.3]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(c); if( _spoil_scenario==11 ) spoil_vector_by_posinf(c); if( _spoil_scenario==12 ) spoil_vector_by_neginf(c); double epsx = 0.000001; if( _spoil_scenario==13 ) epsx = fp_nan; if( _spoil_scenario==14 ) epsx = fp_posinf; if( _spoil_scenario==15 ) epsx = fp_neginf; ae_int_t maxits = 0; ae_int_t info; lsfitstate state; lsfitreport rep; // // Fitting without weights // lsfitcreatefgh(x, y, c, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func, function_cx_1_grad, function_cx_1_hess); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); // // Fitting with weights // (you can change weights and see how it changes result) // real_1d_array w = "[1,1,1,1,1,1,1,1,1,1,1]"; if( _spoil_scenario==16 ) spoil_vector_by_nan(w); if( _spoil_scenario==17 ) spoil_vector_by_posinf(w); if( _spoil_scenario==18 ) spoil_vector_by_neginf(w); if( _spoil_scenario==19 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(w); lsfitcreatewfgh(x, y, w, c, state); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func, function_cx_1_grad, function_cx_1_hess); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[1.5]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_nlfgh"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_nlfb // Bound contstrained nonlinear fitting using function value only // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { // // In this example we demonstrate exponential fitting by // f(x) = exp(-c*x^2) // subject to bound constraints // 0.0 <= c <= 1.0 // using function value only. // // Gradient is estimated using combination of numerical differences // and secant updates. diffstep variable stores differentiation step // (we have to tell algorithm what step to use). // // Unconstrained solution is c=1.5, but because of constraints we should // get c=1.0 (at the boundary). // real_2d_array x = "[[-1],[-0.8],[-0.6],[-0.4],[-0.2],[0],[0.2],[0.4],[0.6],[0.8],[1.0]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); real_1d_array y = "[0.223130, 0.382893, 0.582748, 0.786628, 0.941765, 1.000000, 0.941765, 0.786628, 0.582748, 0.382893, 0.223130]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array c = "[0.3]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(c); if( _spoil_scenario==11 ) spoil_vector_by_posinf(c); if( _spoil_scenario==12 ) spoil_vector_by_neginf(c); real_1d_array bndl = "[0.0]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[1.0]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(bndu); double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; ae_int_t info; lsfitstate state; lsfitreport rep; double diffstep = 0.0001; if( _spoil_scenario==20 ) diffstep = fp_nan; if( _spoil_scenario==21 ) diffstep = fp_posinf; if( _spoil_scenario==22 ) diffstep = fp_neginf; lsfitcreatef(x, y, c, diffstep, state); lsfitsetbc(state, bndl, bndu); lsfitsetcond(state, epsx, maxits); alglib::lsfitfit(state, function_cx_1_func); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_real_vector(c, "[1.0]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_nlfb"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_nlscale // Nonlinear fitting with custom scaling and bound constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<27; _spoil_scenario++) { try { // // In this example we demonstrate fitting by // f(x) = c[0]*(1+c[1]*((x-1999)^c[2]-1)) // subject to bound constraints // -INF < c[0] < +INF // -10 <= c[1] <= +10 // 0.1 <= c[2] <= 2.0 // Data we want to fit are time series of Japan national debt // collected from 2000 to 2008 measured in USD (dollars, not // millions of dollars). // // Our variables are: // c[0] - debt value at initial moment (2000), // c[1] - direction coefficient (growth or decrease), // c[2] - curvature coefficient. // You may see that our variables are badly scaled - first one // is order of 10^12, and next two are somewhere about 1 in // magnitude. Such problem is difficult to solve without some // kind of scaling. // That is exactly where lsfitsetscale() function can be used. // We set scale of our variables to [1.0E12, 1, 1], which allows // us to easily solve this problem. // // You can try commenting out lsfitsetscale() call - and you will // see that algorithm will fail to converge. // real_2d_array x = "[[2000],[2001],[2002],[2003],[2004],[2005],[2006],[2007],[2008]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(x); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(x); real_1d_array y = "[4323239600000.0, 4560913100000.0, 5564091500000.0, 6743189300000.0, 7284064600000.0, 7050129600000.0, 7092221500000.0, 8483907600000.0, 8625804400000.0]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array c = "[1.0e+13, 1, 1]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(c); if( _spoil_scenario==11 ) spoil_vector_by_posinf(c); if( _spoil_scenario==12 ) spoil_vector_by_neginf(c); double epsx = 1.0e-5; if( _spoil_scenario==13 ) epsx = fp_nan; if( _spoil_scenario==14 ) epsx = fp_posinf; if( _spoil_scenario==15 ) epsx = fp_neginf; real_1d_array bndl = "[-inf, -10, 0.1]"; if( _spoil_scenario==16 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==17 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+inf, +10, 2.0]"; if( _spoil_scenario==18 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(bndu); real_1d_array s = "[1.0e+12, 1, 1]"; if( _spoil_scenario==20 ) spoil_vector_by_nan(s); if( _spoil_scenario==21 ) spoil_vector_by_posinf(s); if( _spoil_scenario==22 ) spoil_vector_by_neginf(s); if( _spoil_scenario==23 ) spoil_vector_by_deleting_element(s); ae_int_t maxits = 0; ae_int_t info; lsfitstate state; lsfitreport rep; double diffstep = 1.0e-5; if( _spoil_scenario==24 ) diffstep = fp_nan; if( _spoil_scenario==25 ) diffstep = fp_posinf; if( _spoil_scenario==26 ) diffstep = fp_neginf; lsfitcreatef(x, y, c, diffstep, state); lsfitsetcond(state, epsx, maxits); lsfitsetbc(state, bndl, bndu); lsfitsetscale(state, s); alglib::lsfitfit(state, function_debt_func); lsfitresults(state, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 2); _TestResult = _TestResult && doc_test_real_vector(c, "[4.142560e+12, 0.434240, 0.565376]", -0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_nlscale"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_lin // Unconstrained (general) linear least squares fitting with and without weights // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<13; _spoil_scenario++) { try { // // In this example we demonstrate linear fitting by f(x|a) = a*exp(0.5*x). // // We have: // * y - vector of experimental data // * fmatrix - matrix of basis functions calculated at sample points // Actually, we have only one basis function F0 = exp(0.5*x). // real_2d_array fmatrix = "[[0.606531],[0.670320],[0.740818],[0.818731],[0.904837],[1.000000],[1.105171],[1.221403],[1.349859],[1.491825],[1.648721]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(fmatrix); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(fmatrix); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(fmatrix); real_1d_array y = "[1.133719, 1.306522, 1.504604, 1.554663, 1.884638, 2.072436, 2.257285, 2.534068, 2.622017, 2.897713, 3.219371]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(y); if( _spoil_scenario==4 ) spoil_vector_by_posinf(y); if( _spoil_scenario==5 ) spoil_vector_by_neginf(y); if( _spoil_scenario==6 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); ae_int_t info; real_1d_array c; lsfitreport rep; // // Linear fitting without weights // lsfitlinear(y, fmatrix, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_vector(c, "[1.98650]", 0.00005); // // Linear fitting with individual weights. // Slightly different result is returned. // real_1d_array w = "[1.414213, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(w); if( _spoil_scenario==9 ) spoil_vector_by_posinf(w); if( _spoil_scenario==10 ) spoil_vector_by_neginf(w); if( _spoil_scenario==11 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(w); lsfitlinearw(y, w, fmatrix, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_vector(c, "[1.983354]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_lin"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_linc // Constrained (general) linear least squares fitting with and without weights // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // In this example we demonstrate linear fitting by f(x|a,b) = a*x+b // with simple constraint f(0)=0. // // We have: // * y - vector of experimental data // * fmatrix - matrix of basis functions sampled at [0,1] with step 0.2: // [ 1.0 0.0 ] // [ 1.0 0.2 ] // [ 1.0 0.4 ] // [ 1.0 0.6 ] // [ 1.0 0.8 ] // [ 1.0 1.0 ] // first column contains value of first basis function (constant term) // second column contains second basis function (linear term) // * cmatrix - matrix of linear constraints: // [ 1.0 0.0 0.0 ] // first two columns contain coefficients before basis functions, // last column contains desired value of their sum. // So [1,0,0] means "1*constant_term + 0*linear_term = 0" // real_1d_array y = "[0.072436,0.246944,0.491263,0.522300,0.714064,0.921929]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(y); real_2d_array fmatrix = "[[1,0.0],[1,0.2],[1,0.4],[1,0.6],[1,0.8],[1,1.0]]"; if( _spoil_scenario==5 ) spoil_matrix_by_nan(fmatrix); if( _spoil_scenario==6 ) spoil_matrix_by_posinf(fmatrix); if( _spoil_scenario==7 ) spoil_matrix_by_neginf(fmatrix); if( _spoil_scenario==8 ) spoil_matrix_by_adding_row(fmatrix); if( _spoil_scenario==9 ) spoil_matrix_by_adding_col(fmatrix); if( _spoil_scenario==10 ) spoil_matrix_by_deleting_row(fmatrix); if( _spoil_scenario==11 ) spoil_matrix_by_deleting_col(fmatrix); real_2d_array cmatrix = "[[1,0,0]]"; if( _spoil_scenario==12 ) spoil_matrix_by_nan(cmatrix); if( _spoil_scenario==13 ) spoil_matrix_by_posinf(cmatrix); if( _spoil_scenario==14 ) spoil_matrix_by_neginf(cmatrix); ae_int_t info; real_1d_array c; lsfitreport rep; // // Constrained fitting without weights // lsfitlinearc(y, fmatrix, cmatrix, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_vector(c, "[0,0.932933]", 0.0005); // // Constrained fitting with individual weights // real_1d_array w = "[1, 1.414213, 1, 1, 1, 1]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(w); if( _spoil_scenario==16 ) spoil_vector_by_posinf(w); if( _spoil_scenario==17 ) spoil_vector_by_neginf(w); if( _spoil_scenario==18 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(w); lsfitlinearwc(y, w, fmatrix, cmatrix, info, c, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_vector(c, "[0,0.938322]", 0.0005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_linc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_pol // Unconstrained polynomial fitting // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // This example demonstrates polynomial fitting. // // Fitting is done by two (M=2) functions from polynomial basis: // f0 = 1 // f1 = x // Basically, it just a linear fit; more complex polynomials may be used // (e.g. parabolas with M=3, cubic with M=4), but even such simple fit allows // us to demonstrate polynomialfit() function in action. // // We have: // * x set of abscissas // * y experimental data // // Additionally we demonstrate weighted fitting, where second point has // more weight than other ones. // real_1d_array x = "[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.00,0.05,0.26,0.32,0.33,0.43,0.60,0.60,0.77,0.98,1.02]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); ae_int_t m = 2; double t = 2; if( _spoil_scenario==10 ) t = fp_posinf; if( _spoil_scenario==11 ) t = fp_neginf; ae_int_t info; barycentricinterpolant p; polynomialfitreport rep; double v; // // Fitting without individual weights // // NOTE: result is returned as barycentricinterpolant structure. // if you want to get representation in the power basis, // you can use barycentricbar2pow() function to convert // from barycentric to power representation (see docs for // POLINT subpackage for more info). // polynomialfit(x, y, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.011, 0.002); // // Fitting with individual weights // // NOTE: slightly different result is returned // real_1d_array w = "[1,1.414213562,1,1,1,1,1,1,1,1,1]"; if( _spoil_scenario==12 ) spoil_vector_by_nan(w); if( _spoil_scenario==13 ) spoil_vector_by_posinf(w); if( _spoil_scenario==14 ) spoil_vector_by_neginf(w); if( _spoil_scenario==15 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(w); real_1d_array xc = "[]"; if( _spoil_scenario==17 ) spoil_vector_by_adding_element(xc); real_1d_array yc = "[]"; if( _spoil_scenario==18 ) spoil_vector_by_adding_element(yc); integer_1d_array dc = "[]"; if( _spoil_scenario==19 ) spoil_vector_by_adding_element(dc); polynomialfitwc(x, y, w, xc, yc, dc, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.023, 0.002); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_pol"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_polc // Constrained polynomial fitting // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<29; _spoil_scenario++) { try { // // This example demonstrates polynomial fitting. // // Fitting is done by two (M=2) functions from polynomial basis: // f0 = 1 // f1 = x // with simple constraint on function value // f(0) = 0 // Basically, it just a linear fit; more complex polynomials may be used // (e.g. parabolas with M=3, cubic with M=4), but even such simple fit allows // us to demonstrate polynomialfit() function in action. // // We have: // * x set of abscissas // * y experimental data // * xc points where constraints are placed // * yc constraints on derivatives // * dc derivative indices // (0 means function itself, 1 means first derivative) // real_1d_array x = "[1.0,1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.9,1.1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); real_1d_array w = "[1,1]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(w); if( _spoil_scenario==11 ) spoil_vector_by_posinf(w); if( _spoil_scenario==12 ) spoil_vector_by_neginf(w); if( _spoil_scenario==13 ) spoil_vector_by_adding_element(w); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(w); real_1d_array xc = "[0]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(xc); if( _spoil_scenario==16 ) spoil_vector_by_posinf(xc); if( _spoil_scenario==17 ) spoil_vector_by_neginf(xc); if( _spoil_scenario==18 ) spoil_vector_by_adding_element(xc); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(xc); real_1d_array yc = "[0]"; if( _spoil_scenario==20 ) spoil_vector_by_nan(yc); if( _spoil_scenario==21 ) spoil_vector_by_posinf(yc); if( _spoil_scenario==22 ) spoil_vector_by_neginf(yc); if( _spoil_scenario==23 ) spoil_vector_by_adding_element(yc); if( _spoil_scenario==24 ) spoil_vector_by_deleting_element(yc); integer_1d_array dc = "[0]"; if( _spoil_scenario==25 ) spoil_vector_by_adding_element(dc); if( _spoil_scenario==26 ) spoil_vector_by_deleting_element(dc); double t = 2; if( _spoil_scenario==27 ) t = fp_posinf; if( _spoil_scenario==28 ) t = fp_neginf; ae_int_t m = 2; ae_int_t info; barycentricinterpolant p; polynomialfitreport rep; double v; polynomialfitwc(x, y, w, xc, yc, dc, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.000, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_polc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_d_spline // Unconstrained fitting by penalized regression spline // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<19; _spoil_scenario++) { try { // // In this example we demonstrate penalized spline fitting of noisy data // // We have: // * x - abscissas // * y - vector of experimental data, straight line with small noise // real_1d_array x = "[0.00,0.10,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.10,0.00,0.30,0.40,0.30,0.40,0.62,0.68,0.75,0.95]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); ae_int_t info; double v; spline1dinterpolant s; spline1dfitreport rep; double rho; // // Fit with VERY small amount of smoothing (rho = -5.0) // and large number of basis functions (M=50). // // With such small regularization penalized spline almost fully reproduces function values // rho = -5.0; if( _spoil_scenario==10 ) rho = fp_nan; if( _spoil_scenario==11 ) rho = fp_posinf; if( _spoil_scenario==12 ) rho = fp_neginf; spline1dfitpenalized(x, y, 50, rho, info, s, rep); _TestResult = _TestResult && doc_test_int(info, 1); v = spline1dcalc(s, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.10, 0.01); // // Fit with VERY large amount of smoothing (rho = 10.0) // and large number of basis functions (M=50). // // With such regularization our spline should become close to the straight line fit. // We will compare its value in x=1.0 with results obtained from such fit. // rho = +10.0; if( _spoil_scenario==13 ) rho = fp_nan; if( _spoil_scenario==14 ) rho = fp_posinf; if( _spoil_scenario==15 ) rho = fp_neginf; spline1dfitpenalized(x, y, 50, rho, info, s, rep); _TestResult = _TestResult && doc_test_int(info, 1); v = spline1dcalc(s, 1.0); _TestResult = _TestResult && doc_test_real(v, 0.969, 0.001); // // In real life applications you may need some moderate degree of fitting, // so we try to fit once more with rho=3.0. // rho = +3.0; if( _spoil_scenario==16 ) rho = fp_nan; if( _spoil_scenario==17 ) rho = fp_posinf; if( _spoil_scenario==18 ) rho = fp_neginf; spline1dfitpenalized(x, y, 50, rho, info, s, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_d_spline"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_t_polfit_1 // Polynomial fitting, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { real_1d_array x = "[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.00,0.05,0.26,0.32,0.33,0.43,0.60,0.60,0.77,0.98,1.02]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); ae_int_t m = 2; double t = 2; if( _spoil_scenario==8 ) t = fp_posinf; if( _spoil_scenario==9 ) t = fp_neginf; ae_int_t info; barycentricinterpolant p; polynomialfitreport rep; double v; polynomialfit(x, y, 11, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.011, 0.002); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_t_polfit_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_t_polfit_2 // Polynomial fitting, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<14; _spoil_scenario++) { try { real_1d_array x = "[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.00,0.05,0.26,0.32,0.33,0.43,0.60,0.60,0.77,0.98,1.02]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array w = "[1,1.414213562,1,1,1,1,1,1,1,1,1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(w); if( _spoil_scenario==9 ) spoil_vector_by_posinf(w); if( _spoil_scenario==10 ) spoil_vector_by_neginf(w); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(w); real_1d_array xc = "[]"; real_1d_array yc = "[]"; integer_1d_array dc = "[]"; ae_int_t m = 2; double t = 2; if( _spoil_scenario==12 ) t = fp_posinf; if( _spoil_scenario==13 ) t = fp_neginf; ae_int_t info; barycentricinterpolant p; polynomialfitreport rep; double v; polynomialfitwc(x, y, w, 11, xc, yc, dc, 0, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.023, 0.002); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_t_polfit_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_t_polfit_3 // Polynomial fitting, full list of parameters. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { real_1d_array x = "[1.0,1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.9,1.1]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array w = "[1,1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(w); if( _spoil_scenario==9 ) spoil_vector_by_posinf(w); if( _spoil_scenario==10 ) spoil_vector_by_neginf(w); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(w); real_1d_array xc = "[0]"; if( _spoil_scenario==12 ) spoil_vector_by_nan(xc); if( _spoil_scenario==13 ) spoil_vector_by_posinf(xc); if( _spoil_scenario==14 ) spoil_vector_by_neginf(xc); if( _spoil_scenario==15 ) spoil_vector_by_deleting_element(xc); real_1d_array yc = "[0]"; if( _spoil_scenario==16 ) spoil_vector_by_nan(yc); if( _spoil_scenario==17 ) spoil_vector_by_posinf(yc); if( _spoil_scenario==18 ) spoil_vector_by_neginf(yc); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(yc); integer_1d_array dc = "[0]"; if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(dc); ae_int_t m = 2; double t = 2; if( _spoil_scenario==21 ) t = fp_posinf; if( _spoil_scenario==22 ) t = fp_neginf; ae_int_t info; barycentricinterpolant p; polynomialfitreport rep; double v; polynomialfitwc(x, y, w, 2, xc, yc, dc, 1, m, info, p, rep); v = barycentriccalc(p, t); _TestResult = _TestResult && doc_test_real(v, 2.000, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_t_polfit_3"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_t_4pl // 4-parameter logistic fitting // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<8; _spoil_scenario++) { try { real_1d_array x = "[1,2,3,4,5,6,7,8]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.06313223,0.44552624,0.61838364,0.71385108,0.77345838,0.81383140,0.84280033,0.86449822]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); ae_int_t n = 8; double a; double b; double c; double d; lsfitreport rep; // // Test logisticfit4() on carefully designed data with a priori known answer. // logisticfit4(x, y, n, a, b, c, d, rep); _TestResult = _TestResult && doc_test_real(a, -1.000, 0.01); _TestResult = _TestResult && doc_test_real(b, 1.200, 0.01); _TestResult = _TestResult && doc_test_real(c, 0.900, 0.01); _TestResult = _TestResult && doc_test_real(d, 1.000, 0.01); // // Evaluate model at point x=0.5 // double v; v = logisticcalc4(0.5, a, b, c, d); _TestResult = _TestResult && doc_test_real(v, -0.33874308, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_t_4pl"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lsfit_t_5pl // 5-parameter logistic fitting // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<8; _spoil_scenario++) { try { real_1d_array x = "[1,2,3,4,5,6,7,8]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.1949776139,0.5710060208,0.726002637,0.8060434158,0.8534547965,0.8842071579,0.9054773317,0.9209088299]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); ae_int_t n = 8; double a; double b; double c; double d; double g; lsfitreport rep; // // Test logisticfit5() on carefully designed data with a priori known answer. // logisticfit5(x, y, n, a, b, c, d, g, rep); _TestResult = _TestResult && doc_test_real(a, -1.000, 0.01); _TestResult = _TestResult && doc_test_real(b, 1.200, 0.01); _TestResult = _TestResult && doc_test_real(c, 0.900, 0.01); _TestResult = _TestResult && doc_test_real(d, 1.000, 0.01); _TestResult = _TestResult && doc_test_real(g, 1.200, 0.01); // // Evaluate model at point x=0.5 // double v; v = logisticcalc5(0.5, a, b, c, d, g); _TestResult = _TestResult && doc_test_real(v, -0.2354656824, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lsfit_t_5pl"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_bilinear // Bilinear spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<16; _spoil_scenario++) { try { // // We use bilinear spline to interpolate f(x,y)=x^2+2*y^2 sampled // at (x,y) from [0.0, 0.5, 1.0] X [0.0, 1.0]. // real_1d_array x = "[0.0, 0.5, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array f = "[0.00,0.25,1.00,2.00,2.25,3.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(f); if( _spoil_scenario==9 ) spoil_vector_by_posinf(f); if( _spoil_scenario==10 ) spoil_vector_by_neginf(f); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(f); double vx = 0.25; if( _spoil_scenario==12 ) vx = fp_posinf; if( _spoil_scenario==13 ) vx = fp_neginf; double vy = 0.50; if( _spoil_scenario==14 ) vy = fp_posinf; if( _spoil_scenario==15 ) vy = fp_neginf; double v; spline2dinterpolant s; // build spline spline2dbuildbilinearv(x, 3, y, 2, f, 1, s); // calculate S(0.25,0.50) v = spline2dcalc(s, vx, vy); _TestResult = _TestResult && doc_test_real(v, 1.1250, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_bilinear"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_bicubic // Bilinear spline interpolation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<16; _spoil_scenario++) { try { // // We use bilinear spline to interpolate f(x,y)=x^2+2*y^2 sampled // at (x,y) from [0.0, 0.5, 1.0] X [0.0, 1.0]. // real_1d_array x = "[0.0, 0.5, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array f = "[0.00,0.25,1.00,2.00,2.25,3.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(f); if( _spoil_scenario==9 ) spoil_vector_by_posinf(f); if( _spoil_scenario==10 ) spoil_vector_by_neginf(f); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(f); double vx = 0.25; if( _spoil_scenario==12 ) vx = fp_posinf; if( _spoil_scenario==13 ) vx = fp_neginf; double vy = 0.50; if( _spoil_scenario==14 ) vy = fp_posinf; if( _spoil_scenario==15 ) vy = fp_neginf; double v; double dx; double dy; double dxy; spline2dinterpolant s; // build spline spline2dbuildbicubicv(x, 3, y, 2, f, 1, s); // calculate S(0.25,0.50) v = spline2dcalc(s, vx, vy); _TestResult = _TestResult && doc_test_real(v, 1.0625, 0.00005); // calculate derivatives spline2ddiff(s, vx, vy, v, dx, dy, dxy); _TestResult = _TestResult && doc_test_real(v, 1.0625, 0.00005); _TestResult = _TestResult && doc_test_real(dx, 0.5000, 0.00005); _TestResult = _TestResult && doc_test_real(dy, 2.0000, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_bicubic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_fit_blocklls // Fitting bicubic spline to irregular data // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { // // We use bicubic spline to reproduce f(x,y)=1/(1+x^2+2*y^2) sampled // at irregular points (x,y) from [-1,+1]*[-1,+1] // // We have 5 such points, located approximately at corners of the area // and its center - but not exactly at the grid. Thus, we have to FIT // the spline, i.e. to solve least squares problem // real_2d_array xy = "[[-0.987,-0.902,0.359],[0.948,-0.992,0.347],[-1.000,1.000,0.333],[1.000,0.973,0.339],[0.017,0.180,0.968]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(xy); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(xy); // // First step is to create spline2dbuilder object and set its properties: // * d=1 means that we create vector-valued spline with 1 component // * we specify dataset xy // * we rely on automatic selection of interpolation area // * we tell builder that we want to use 5x5 grid for an underlying spline // * we choose least squares solver named BlockLLS and configure it by // telling that we want to apply zero nonlinearity penalty. // // NOTE: you can specify non-zero lambdav if you want to make your spline // more "rigid", i.e. to penalize nonlinearity. // // NOTE: ALGLIB has two solvers which fit bicubic splines to irregular data, // one of them is BlockLLS and another one is FastDDM. Former is // intended for moderately sized grids (up to 512x512 nodes, although // it may take up to few minutes); it is the most easy to use and // control spline fitting function in the library. Latter, FastDDM, // is intended for efficient solution of large-scale problems // (up to 100.000.000 nodes). Both solvers can be parallelized, but // FastDDM is much more efficient. See comments for more information. // spline2dbuilder builder; ae_int_t d = 1; double lambdav = 0.000; spline2dbuildercreate(d, builder); spline2dbuildersetpoints(builder, xy, 5); spline2dbuildersetgrid(builder, 5, 5); spline2dbuildersetalgoblocklls(builder, lambdav); // // Now we are ready to fit and evaluate our results // spline2dinterpolant s; spline2dfitreport rep; spline2dfit(builder, s, rep); // evaluate results - function value at the grid is reproduced exactly double v; v = spline2dcalc(s, -1, 1); _TestResult = _TestResult && doc_test_real(v, 0.333000, 0.005); // check maximum error - it must be nearly zero _TestResult = _TestResult && doc_test_real(rep.maxerror, 0.000, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_fit_blocklls"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_unpack // Unpacking bilinear spline // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // We build bilinear spline for f(x,y)=x+2*y+3*xy for (x,y) in [0,1]. // Then we demonstrate how to unpack it. // real_1d_array x = "[0.0, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array f = "[0.00,1.00,2.00,6.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(f); if( _spoil_scenario==9 ) spoil_vector_by_posinf(f); if( _spoil_scenario==10 ) spoil_vector_by_neginf(f); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(f); real_2d_array c; ae_int_t m; ae_int_t n; ae_int_t d; spline2dinterpolant s; // build spline spline2dbuildbilinearv(x, 2, y, 2, f, 1, s); // unpack and test spline2dunpackv(s, m, n, d, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0, 1, 0, 1, 0,2,0,0, 1,3,0,0, 0,0,0,0, 0,0,0,0 ]]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_unpack"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_copytrans // Copy and transform // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<16; _spoil_scenario++) { try { // // We build bilinear spline for f(x,y)=x+2*y for (x,y) in [0,1]. // Then we apply several transformations to this spline. // real_1d_array x = "[0.0, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array f = "[0.00,1.00,2.00,3.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(f); if( _spoil_scenario==9 ) spoil_vector_by_posinf(f); if( _spoil_scenario==10 ) spoil_vector_by_neginf(f); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(f); spline2dinterpolant s; spline2dinterpolant snew; double v; spline2dbuildbilinearv(x, 2, y, 2, f, 1, s); // copy spline, apply transformation x:=2*xnew, y:=4*ynew // evaluate at (xnew,ynew) = (0.25,0.25) - should be same as (x,y)=(0.5,1.0) spline2dcopy(s, snew); spline2dlintransxy(snew, 2.0, 0.0, 4.0, 0.0); v = spline2dcalc(snew, 0.25, 0.25); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.00005); // copy spline, apply transformation SNew:=2*S+3 spline2dcopy(s, snew); spline2dlintransf(snew, 2.0, 3.0); v = spline2dcalc(snew, 0.5, 1.0); _TestResult = _TestResult && doc_test_real(v, 8.000, 0.00005); // // Same example, but for vector spline (f0,f1) = {x+2*y, 2*x+y} // real_1d_array f2 = "[0.00,0.00, 1.00,2.00, 2.00,1.00, 3.00,3.00]"; if( _spoil_scenario==12 ) spoil_vector_by_nan(f2); if( _spoil_scenario==13 ) spoil_vector_by_posinf(f2); if( _spoil_scenario==14 ) spoil_vector_by_neginf(f2); if( _spoil_scenario==15 ) spoil_vector_by_deleting_element(f2); real_1d_array vr; spline2dbuildbilinearv(x, 2, y, 2, f2, 2, s); // copy spline, apply transformation x:=2*xnew, y:=4*ynew spline2dcopy(s, snew); spline2dlintransxy(snew, 2.0, 0.0, 4.0, 0.0); spline2dcalcv(snew, 0.25, 0.25, vr); _TestResult = _TestResult && doc_test_real_vector(vr, "[2.500,2.000]", 0.00005); // copy spline, apply transformation SNew:=2*S+3 spline2dcopy(s, snew); spline2dlintransf(snew, 2.0, 3.0); spline2dcalcv(snew, 0.5, 1.0, vr); _TestResult = _TestResult && doc_test_real_vector(vr, "[8.000,7.000]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_copytrans"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST spline2d_vector // Copy and transform // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // We build bilinear vector-valued spline (f0,f1) = {x+2*y, 2*x+y} // Spline is built using function values at 2x2 grid: (x,y)=[0,1]*[0,1] // Then we perform evaluation at (x,y)=(0.1,0.3) // real_1d_array x = "[0.0, 1.0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0.0, 1.0]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(y); if( _spoil_scenario==5 ) spoil_vector_by_posinf(y); if( _spoil_scenario==6 ) spoil_vector_by_neginf(y); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(y); real_1d_array f = "[0.00,0.00, 1.00,2.00, 2.00,1.00, 3.00,3.00]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(f); if( _spoil_scenario==9 ) spoil_vector_by_posinf(f); if( _spoil_scenario==10 ) spoil_vector_by_neginf(f); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(f); spline2dinterpolant s; real_1d_array vr; spline2dbuildbilinearv(x, 2, y, 2, f, 2, s); spline2dcalcv(s, 0.1, 0.3, vr); _TestResult = _TestResult && doc_test_real_vector(vr, "[0.700,0.500]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "spline2d_vector"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST rbf_d_hrbf // Simple model built with HRBF algorithm // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example illustrates basic concepts of the RBF models: creation, modification, // evaluation. // // Suppose that we have set of 2-dimensional points with associated // scalar function values, and we want to build a RBF model using // our data. // // NOTE: we can work with 3D models too :) // // Typical sequence of steps is given below: // 1. we create RBF model object // 2. we attach our dataset to the RBF model and tune algorithm settings // 3. we rebuild RBF model using QNN algorithm on new data // 4. we use RBF model (evaluate, serialize, etc.) // double v; // // Step 1: RBF model creation. // // We have to specify dimensionality of the space (2 or 3) and // dimensionality of the function (scalar or vector). // // New model is empty - it can be evaluated, // but we just get zero value at any point. // rbfmodel model; rbfcreate(2, 1, model); v = rbfcalc2(model, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.000, 0.005); // // Step 2: we add dataset. // // XY contains two points - x0=(-1,0) and x1=(+1,0) - // and two function values f(x0)=2, f(x1)=3. // // We added points, but model was not rebuild yet. // If we call rbfcalc2(), we still will get 0.0 as result. // real_2d_array xy = "[[-1,0,2],[+1,0,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); rbfsetpoints(model, xy); v = rbfcalc2(model, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.000, 0.005); // // Step 3: rebuild model // // After we've configured model, we should rebuild it - // it will change coefficients stored internally in the // rbfmodel structure. // // We use hierarchical RBF algorithm with following parameters: // * RBase - set to 1.0 // * NLayers - three layers are used (although such simple problem // does not need more than 1 layer) // * LambdaReg - is set to zero value, no smoothing is required // rbfreport rep; rbfsetalgohierarchical(model, 1.0, 3, 0.0); rbfbuildmodel(model, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); // // Step 4: model was built // // After call of rbfbuildmodel(), rbfcalc2() will return // value of the new model. // v = rbfcalc2(model, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "rbf_d_hrbf"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST rbf_d_vector // Working with vector functions // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // Suppose that we have set of 2-dimensional points with associated VECTOR // function values, and we want to build a RBF model using our data. // // Typical sequence of steps is given below: // 1. we create RBF model object // 2. we attach our dataset to the RBF model and tune algorithm settings // 3. we rebuild RBF model using new data // 4. we use RBF model (evaluate, serialize, etc.) // real_1d_array x; real_1d_array y; // // Step 1: RBF model creation. // // We have to specify dimensionality of the space (equal to 2) and // dimensionality of the function (2-dimensional vector function). // // New model is empty - it can be evaluated, // but we just get zero value at any point. // rbfmodel model; rbfcreate(2, 2, model); x = "[+1,+1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); rbfcalc(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,0.000]", 0.005); // // Step 2: we add dataset. // // XY arrays containt four points: // * (x0,y0) = (+1,+1), f(x0,y0)=(0,-1) // * (x1,y1) = (+1,-1), f(x1,y1)=(-1,0) // * (x2,y2) = (-1,-1), f(x2,y2)=(0,+1) // * (x3,y3) = (-1,+1), f(x3,y3)=(+1,0) // real_2d_array xy = "[[+1,+1,0,-1],[+1,-1,-1,0],[-1,-1,0,+1],[-1,+1,+1,0]]"; if( _spoil_scenario==3 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==4 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==5 ) spoil_matrix_by_neginf(xy); rbfsetpoints(model, xy); // We added points, but model was not rebuild yet. // If we call rbfcalc(), we still will get 0.0 as result. rbfcalc(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,0.000]", 0.005); // // Step 3: rebuild model // // We use hierarchical RBF algorithm with following parameters: // * RBase - set to 1.0 // * NLayers - three layers are used (although such simple problem // does not need more than 1 layer) // * LambdaReg - is set to zero value, no smoothing is required // // After we've configured model, we should rebuild it - // it will change coefficients stored internally in the // rbfmodel structure. // rbfreport rep; rbfsetalgohierarchical(model, 1.0, 3, 0.0); rbfbuildmodel(model, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); // // Step 4: model was built // // After call of rbfbuildmodel(), rbfcalc() will return // value of the new model. // rbfcalc(model, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[0.000,-1.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "rbf_d_vector"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST rbf_d_polterm // RBF models - working with polynomial term // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example show how to work with polynomial term // // Suppose that we have set of 2-dimensional points with associated // scalar function values, and we want to build a RBF model using // our data. // // We use hierarchical RBF algorithm with following parameters: // * RBase - set to 1.0 // * NLayers - three layers are used (although such simple problem // does not need more than 1 layer) // * LambdaReg - is set to zero value, no smoothing is required // double v; rbfmodel model; real_2d_array xy = "[[-1,0,2],[+1,0,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); rbfreport rep; rbfcreate(2, 1, model); rbfsetpoints(model, xy); rbfsetalgohierarchical(model, 1.0, 3, 0.0); // // By default, RBF model uses linear term. It means that model // looks like // f(x,y) = SUM(RBF[i]) + a*x + b*y + c // where RBF[i] is I-th radial basis function and a*x+by+c is a // linear term. Having linear terms in a model gives us: // (1) improved extrapolation properties // (2) linearity of the model when data can be perfectly fitted // by the linear function // (3) linear asymptotic behavior // // Our simple dataset can be modelled by the linear function // f(x,y) = 0.5*x + 2.5 // and rbfbuildmodel() with default settings should preserve this // linearity. // ae_int_t nx; ae_int_t ny; ae_int_t nc; ae_int_t modelversion; real_2d_array xwr; real_2d_array c; rbfbuildmodel(model, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); rbfunpack(model, nx, ny, xwr, nc, c, modelversion); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.500,0.000,2.500]]", 0.005); // asymptotic behavior of our function is linear v = rbfcalc2(model, 1000.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 502.50, 0.05); // // Instead of linear term we can use constant term. In this case // we will get model which has form // f(x,y) = SUM(RBF[i]) + c // where RBF[i] is I-th radial basis function and c is a constant, // which is equal to the average function value on the dataset. // // Because we've already attached dataset to the model the only // thing we have to do is to call rbfsetconstterm() and then // rebuild model with rbfbuildmodel(). // rbfsetconstterm(model); rbfbuildmodel(model, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); rbfunpack(model, nx, ny, xwr, nc, c, modelversion); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.000,0.000,2.500]]", 0.005); // asymptotic behavior of our function is constant v = rbfcalc2(model, 1000.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.005); // // Finally, we can use zero term. Just plain RBF without polynomial // part: // f(x,y) = SUM(RBF[i]) // where RBF[i] is I-th radial basis function. // rbfsetzeroterm(model); rbfbuildmodel(model, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); rbfunpack(model, nx, ny, xwr, nc, c, modelversion); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.000,0.000,0.000]]", 0.005); // asymptotic behavior of our function is just zero constant v = rbfcalc2(model, 1000.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.000, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "rbf_d_polterm"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST rbf_d_serialize // Serialization/unserialization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // This example show how to serialize and unserialize RBF model // // Suppose that we have set of 2-dimensional points with associated // scalar function values, and we want to build a RBF model using // our data. Then we want to serialize it to string and to unserialize // from string, loading to another instance of RBF model. // // Here we assume that you already know how to create RBF models. // std::string s; double v; rbfmodel model0; rbfmodel model1; real_2d_array xy = "[[-1,0,2],[+1,0,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(xy); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(xy); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(xy); rbfreport rep; // model initialization rbfcreate(2, 1, model0); rbfsetpoints(model0, xy); rbfsetalgohierarchical(model0, 1.0, 3, 0.0); rbfbuildmodel(model0, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); // // Serialization - it looks easy, // but you should carefully read next section. // alglib::rbfserialize(model0, s); alglib::rbfunserialize(s, model1); // both models return same value v = rbfcalc2(model0, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.005); v = rbfcalc2(model1, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.005); // // Previous section shows that model state is saved/restored during // serialization. However, some properties are NOT serialized. // // Serialization saves/restores RBF model, but it does NOT saves/restores // settings which were used to build current model. In particular, dataset // which was used to build model, is not preserved. // // What does it mean in for us? // // Do you remember this sequence: rbfcreate-rbfsetpoints-rbfbuildmodel? // First step creates model, second step adds dataset and tunes model // settings, third step builds model using current dataset and model // construction settings. // // If you call rbfbuildmodel() without calling rbfsetpoints() first, you // will get empty (zero) RBF model. In our example, model0 contains // dataset which was added by rbfsetpoints() call. However, model1 does // NOT contain dataset - because dataset is NOT serialized. // // This, if we call rbfbuildmodel(model0,rep), we will get same model, // which returns 2.5 at (x,y)=(0,0). However, after same call model1 will // return zero - because it contains RBF model (coefficients), but does NOT // contain dataset which was used to build this model. // // Basically, it means that: // * serialization of the RBF model preserves anything related to the model // EVALUATION // * but it does NOT creates perfect copy of the original object. // rbfbuildmodel(model0, rep); v = rbfcalc2(model0, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 2.500, 0.005); rbfbuildmodel(model1, rep); v = rbfcalc2(model1, 0.0, 0.0); _TestResult = _TestResult && doc_test_real(v, 0.000, 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "rbf_d_serialize"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_d_1 // Determinant calculation, real matrix, short form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { real_2d_array b = "[[1,2],[2,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(b); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(b); double a; a = rmatrixdet(b); _TestResult = _TestResult && doc_test_real(a, -3, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_d_2 // Determinant calculation, real matrix, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { real_2d_array b = "[[5,4],[4,5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); double a; a = rmatrixdet(b, 2); _TestResult = _TestResult && doc_test_real(a, 9, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_d_3 // Determinant calculation, complex matrix, short form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { complex_2d_array b = "[[1+1i,2],[2,1-1i]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(b); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(b); alglib::complex a; a = cmatrixdet(b); _TestResult = _TestResult && doc_test_complex(a, -2, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_d_3"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_d_4 // Determinant calculation, complex matrix, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { alglib::complex a; complex_2d_array b = "[[5i,4],[4i,5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); a = cmatrixdet(b, 2); _TestResult = _TestResult && doc_test_complex(a, alglib::complex(0,9), 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_d_4"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_d_5 // Determinant calculation, complex matrix with zero imaginary part, short form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { alglib::complex a; complex_2d_array b = "[[9,1],[2,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(b); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(b); a = cmatrixdet(b); _TestResult = _TestResult && doc_test_complex(a, 7, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_d_5"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_0 // Determinant calculation, real matrix, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { double a; real_2d_array b = "[[3,4],[-4,3]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); a = rmatrixdet(b, 2); _TestResult = _TestResult && doc_test_real(a, 25, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_0"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_1 // Determinant calculation, real matrix, LU, short form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { double a; real_2d_array b = "[[1,2],[2,5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(b); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(b); integer_1d_array p = "[1,1]"; if( _spoil_scenario==7 ) spoil_vector_by_adding_element(p); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(p); a = rmatrixludet(b, p); _TestResult = _TestResult && doc_test_real(a, -5, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_2 // Determinant calculation, real matrix, LU, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { double a; real_2d_array b = "[[5,4],[4,5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); integer_1d_array p = "[0,1]"; if( _spoil_scenario==5 ) spoil_vector_by_deleting_element(p); a = rmatrixludet(b, p, 2); _TestResult = _TestResult && doc_test_real(a, 25, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_3 // Determinant calculation, complex matrix, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<5; _spoil_scenario++) { try { alglib::complex a; complex_2d_array b = "[[5i,4],[-4,5i]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); a = cmatrixdet(b, 2); _TestResult = _TestResult && doc_test_complex(a, -9, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_3"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_4 // Determinant calculation, complex matrix, LU, short form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { alglib::complex a; complex_2d_array b = "[[1,2],[2,5i]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(b); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(b); integer_1d_array p = "[1,1]"; if( _spoil_scenario==7 ) spoil_vector_by_adding_element(p); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(p); a = cmatrixludet(b, p); _TestResult = _TestResult && doc_test_complex(a, alglib::complex(0,-5), 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_4"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matdet_t_5 // Determinant calculation, complex matrix, LU, full form // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { alglib::complex a; complex_2d_array b = "[[5,4i],[4,5]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(b); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(b); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(b); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(b); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(b); integer_1d_array p = "[0,1]"; if( _spoil_scenario==5 ) spoil_vector_by_deleting_element(p); a = cmatrixludet(b, p, 2); _TestResult = _TestResult && doc_test_complex(a, 25, 0.0001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matdet_t_5"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST solvesks_d_1 // Solving positive definite sparse system using Skyline (SKS) solver // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<4; _spoil_scenario++) { try { // // This example demonstrates creation/initialization of the sparse matrix // in the SKS (Skyline) storage format and solution using SKS-based direct // solver. // // First, we have to create matrix and initialize it. Matrix is created // in the SKS format, using fixed bandwidth initialization function. // Several points should be noted: // // 1. SKS sparse storage format also allows variable bandwidth matrices; // we just do not want to overcomplicate this example. // // 2. SKS format requires you to specify matrix geometry prior to // initialization of its elements with sparseset(). If you specified // bandwidth=1, you can not change your mind afterwards and call // sparseset() for non-existent elements. // // 3. Because SKS solver need just one triangle of SPD matrix, we can // omit initialization of the lower triangle of our matrix. // ae_int_t n = 4; ae_int_t bandwidth = 1; sparsematrix s; sparsecreatesksband(n, n, bandwidth, s); sparseset(s, 0, 0, 2.0); sparseset(s, 0, 1, 1.0); sparseset(s, 1, 1, 3.0); sparseset(s, 1, 2, 1.0); sparseset(s, 2, 2, 3.0); sparseset(s, 2, 3, 1.0); sparseset(s, 3, 3, 2.0); // // Now we have symmetric positive definite 4x4 system width bandwidth=1: // // [ 2 1 ] [ x0]] [ 4 ] // [ 1 3 1 ] [ x1 ] [ 10 ] // [ 1 3 1 ] * [ x2 ] = [ 15 ] // [ 1 2 ] [ x3 ] [ 11 ] // // After successful creation we can call SKS solver. // real_1d_array b = "[4,10,15,11]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); sparsesolverreport rep; real_1d_array x; bool isuppertriangle = true; sparsespdsolvesks(s, isuppertriangle, b, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[1.0000, 2.0000, 3.0000, 4.0000]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "solvesks_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST lincg_d_1 // Solution of sparse linear systems with CG // printf("150/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<4; _spoil_scenario++) { try { // // This example illustrates solution of sparse linear systems with // conjugate gradient method. // // Suppose that we have linear system A*x=b with sparse symmetric // positive definite A (represented by sparsematrix object) // [ 5 1 ] // [ 1 7 2 ] // A = [ 2 8 1 ] // [ 1 4 1 ] // [ 1 4 ] // and right part b // [ 7 ] // [ 17 ] // b = [ 14 ] // [ 10 ] // [ 6 ] // and we want to solve this system using sparse linear CG. In order // to do so, we have to create left part (sparsematrix object) and // right part (dense array). // // Initially, sparse matrix is created in the Hash-Table format, // which allows easy initialization, but do not allow matrix to be // used in the linear solvers. So after construction you should convert // sparse matrix to CRS format (one suited for linear operations). // // It is important to note that in our example we initialize full // matrix A, both lower and upper triangles. However, it is symmetric // and sparse solver needs just one half of the matrix. So you may // save about half of the space by filling only one of the triangles. // sparsematrix a; sparsecreate(5, 5, a); sparseset(a, 0, 0, 5.0); sparseset(a, 0, 1, 1.0); sparseset(a, 1, 0, 1.0); sparseset(a, 1, 1, 7.0); sparseset(a, 1, 2, 2.0); sparseset(a, 2, 1, 2.0); sparseset(a, 2, 2, 8.0); sparseset(a, 2, 3, 1.0); sparseset(a, 3, 2, 1.0); sparseset(a, 3, 3, 4.0); sparseset(a, 3, 4, 1.0); sparseset(a, 4, 3, 1.0); sparseset(a, 4, 4, 4.0); // // Now our matrix is fully initialized, but we have to do one more // step - convert it from Hash-Table format to CRS format (see // documentation on sparse matrices for more information about these // formats). // // If you omit this call, ALGLIB will generate exception on the first // attempt to use A in linear operations. // sparseconverttocrs(a); // // Initialization of the right part // real_1d_array b = "[7,17,14,10,6]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); // // Now we have to create linear solver object and to use it for the // solution of the linear system. // // NOTE: lincgsolvesparse() accepts additional parameter which tells // what triangle of the symmetric matrix should be used - upper // or lower. Because we've filled both parts of the matrix, we // can use any part - upper or lower. // lincgstate s; lincgreport rep; real_1d_array x; lincgcreate(5, s); lincgsolvesparse(s, a, true, b); lincgresults(s, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 1); _TestResult = _TestResult && doc_test_real_vector(x, "[1.000,2.000,1.000,2.000,1.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "lincg_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; printf("151/151\n"); } catch(...) { printf("Unhandled exception was raised!\n"); return 1; } #ifdef AE_USE_ALLOC_COUNTER printf("Allocation counter checked... "); #ifdef _ALGLIB_HAS_WORKSTEALING alglib_impl::ae_free_disposed_items(); #endif if( alglib_impl::_alloc_counter!=0 ) { printf("FAILURE: alloc_counter is non-zero on end!\n"); return 1; } else printf("OK\n"); #endif return _TotalResult ? 0 : 1; }
42.755605
256
0.468692
[ "geometry", "object", "vector", "model", "transform", "3d" ]
dc89ba634fbb12160a10f7b0584d3fdf88eacb62
31,237
cpp
C++
test/code/scxcorelib/util/scxstringaid_test.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
37
2016-04-14T20:06:15.000Z
2019-05-06T17:30:17.000Z
test/code/scxcorelib/util/scxstringaid_test.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
37
2016-03-11T20:47:11.000Z
2019-04-01T22:53:04.000Z
test/code/scxcorelib/util/scxstringaid_test.cpp
snchennapragada/pal
9ee3e116dc2fadb44efa0938de7f0b737784fe16
[ "MIT" ]
20
2016-05-26T23:53:01.000Z
2019-05-06T08:54:08.000Z
/*-------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Created date 2007-05-24 08:10:00 String aid method test class. */ /*----------------------------------------------------------------------------*/ #include <scxcorelib/scxcmn.h> #include <scxcorelib/stringaid.h> #include <scxcorelib/scxexception.h> #include <scxcorelib/scxmath.h> #include <scxcorelib/scxdumpstring.h> #include <scxcorelib/scxlocale.h> #include <testutils/scxunit.h> #include <string> #include <vector> #include <exception> #include <stdexcept> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <langinfo.h> // To look up codepage (locale) using namespace SCXCoreLib; // A few test code points for the locale-independent upcase and downcase functions struct TestInfo { unsigned int Char; // a test character unsigned int Converted; // its upper or lowercase equivalent }; // Some test characters and their upper case equivalents static TestInfo UpcaseTestTable[] = { { '\f', '\f' }, // no case { '5', '5' }, // no case { 'C', 'C' }, // already upper case { 'q', 'Q' }, { 0x00A5, 0x00A5 }, { 0x00A3, 0x00A3 }, // already upper case { 0x00FF, 0x0178 }, { 0x0180, 0x0243 }, { 0x01A0, 0x01A0 }, // no case { 0x0217, 0x0216 }, { 0x023D, 0x023D }, // already upper case { 0x0280, 0x01A6 }, { 0x02FF, 0x02FF }, // no case { 0x0377, 0x0376 }, { 0x03CC, 0x038C }, { 0x03D8, 0x03D8 }, // already upper case { 0x04A7, 0x04A6 }, { 0x048A, 0x048A }, // already upper case { 0x04FF, 0x04FE }, { 0x052D, 0x052D }, // no case { 0x0575, 0x0545 }, { 0x0660, 0x0660 }, // no case { 0x1F97, 0x1F9F }, { 0x1D7D, 0x2C63 }, { 0x3089, 0x3089 }, // no case { 0x8080, 0x8080 }, // no case { 0xA78C, 0xA78B }, { 0xFF41, 0xFF21 }, { 0xFFD0, 0xFFD0 }, // no case { 0x00013478, 0x00013478 } // no case }; // Some test characters and their lower case equivalents static TestInfo DowncaseTestTable[] = { { 0x11, 0x11 }, // no case { '%', '%' }, // no case { 'C', 'c' }, { 'z', 'z' }, // already lower case { 0x00A6, 0x00A6 }, // no case { 0x00C3, 0x00E3 }, { 0x0133, 0x0133 }, // no case { 0x0216, 0x0217 }, { 0x0289, 0x0289 }, // already lower case { 0x02DE, 0x02DE }, // no case { 0x0376, 0x0377 }, { 0x03B1, 0x03B1 }, // already lower case { 0x04C3, 0x04C4 }, { 0x0512, 0x0513 }, { 0x052D, 0x052D }, // no case { 0x0660, 0x0660 }, // no case { 0x1F9F, 0x1F97 }, { 0x2C63, 0x1D7D }, { 0x8088, 0x8088 }, // no case { 0xA78B, 0xA78C }, { 0xC173, 0xC173 }, // no case { 0xFF25, 0xFF45 }, { 0xFFE0, 0xFFE0 }, // no case { 0x000E43F5, 0x000E43F5 } // no case }; class SCXStringAid_Test : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( SCXStringAid_Test ); CPPUNIT_TEST( testTrim ); CPPUNIT_TEST( testStrip ); CPPUNIT_TEST( testToUpper ); CPPUNIT_TEST( testCompare ); CPPUNIT_TEST( testIsPrefix ); CPPUNIT_TEST( testAppend ); CPPUNIT_TEST( testTokenize ); CPPUNIT_TEST( testTokenizeStr ); CPPUNIT_TEST( testToIntETC ); CPPUNIT_TEST( testFrom ); CPPUNIT_TEST( testUTF8Conversion ); CPPUNIT_TEST( testUTF8ConversionFails ); CPPUNIT_TEST( testMergeTokens ); CPPUNIT_TEST( testTokenizeWithDelimiters ); CPPUNIT_TEST( testFromMultibyte ); CPPUNIT_TEST( testFromMultibyteNoThrow ); CPPUNIT_TEST( testDumpStringException ); CPPUNIT_TEST( testUtfUpDownCase ); // This test should not be run on HPUX 11iv2 since we know that vsnprintf does not behave well on that platform #if (!defined(hpux) || !((PF_MAJOR==11) && (PF_MINOR < 31))) && (!defined(sun) || !((PF_MAJOR==5) && (PF_MINOR <= 9))) CPPUNIT_TEST( testUNIX03 ); #endif CPPUNIT_TEST( test_Empty_String ); CPPUNIT_TEST( test_Nonquoted_String_OnlySpaces ); CPPUNIT_TEST( test_Nonquoted_String_EmptyTokensOnly ); CPPUNIT_TEST( test_Nonquoted_String ); CPPUNIT_TEST( test_Nonquoted_String_ReturnEmptyTokens ); CPPUNIT_TEST( test_QuotedQuotes_Ignored ); CPPUNIT_TEST( test_Quoted_String ); CPPUNIT_TEST( test_Quoted_String_Double ); CPPUNIT_TEST( test_Quoted_SingleQuote ); CPPUNIT_TEST( test_Quoted_SingleQuote_ReturnEmptyTokens ); CPPUNIT_TEST( test_Quoted_SingleQuote_QuotedSpaces ); CPPUNIT_TEST( test_Quoted_String_QuotedQuotes ); CPPUNIT_TEST( test_Quoted_SingleQuotedElement ); CPPUNIT_TEST( test_Quoted_UnterminatedQuote ); CPPUNIT_TEST_SUITE_END(); protected: void testTrim() { std::wstring w_tst(L"\t Test String \t"); std::wstring w_tst1(L"Test String \t"); std::wstring w_tst2(L"\t Test String"); std::wstring w_tst3(L"Test String"); std::wstring w_empty(L""); std::wstring w_blank(L" \t "); // Check that TrimL removes whitespace to the left of the string CPPUNIT_ASSERT(w_tst1 == SCXCoreLib::StrTrimL(w_tst)); // Check that TrimR removes whitespace to the right of the string CPPUNIT_ASSERT(w_tst2 == SCXCoreLib::StrTrimR(w_tst)); // Check that Trim removes whitespace at both sides of the string CPPUNIT_ASSERT(w_tst3 == SCXCoreLib::StrTrim(w_tst)); // Check that Trim works on empty string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrTrim(w_empty)); // Check that TrimL works on blank string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrTrimL(w_blank)); // Check that TrimR works on blank string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrTrimR(w_blank)); } void testStrip() { std::wstring w_tst(L"\n. Test String. \n"); std::wstring w_tst1(L"Test String. \n"); std::wstring w_tst2(L"\n. Test String"); std::wstring w_tst3(L"Test String"); std::wstring w_empty(L""); std::wstring w_blank(L".\n ."); std::wstring w_what(L". \n"); // Check that TrimL removes whitespace to the left of the string CPPUNIT_ASSERT(w_tst1 == SCXCoreLib::StrStripL(w_tst, w_what)); // Check that TrimR removes whitespace to the right of the string CPPUNIT_ASSERT(w_tst2 == SCXCoreLib::StrStripR(w_tst, w_what)); // Check that Trim removes whitespace at both sides of the string CPPUNIT_ASSERT(w_tst3 == SCXCoreLib::StrStrip(w_tst, w_what)); // Check non-trimmable strings are not trimmed. CPPUNIT_ASSERT(w_tst3 == SCXCoreLib::StrStrip(w_tst3, w_what)); // Check that Trim works on empty string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrStrip(w_empty, w_what)); // Check that TrimL works on blank string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrStripL(w_blank, w_what)); // Check that TrimR works on blank string CPPUNIT_ASSERT(w_empty == SCXCoreLib::StrStripR(w_blank, w_what)); } void testToUpper() { std::wstring w_tst(L"A Small Test String"); std::wstring w_tst1(L"A SMALL TEST STRING"); // Test that ToUpper returns a string with all charachters converted to uppercase CPPUNIT_ASSERT(w_tst1 == SCXCoreLib::StrToUpper(w_tst)); } void testCompare() { std::wstring w_tst(L"a small test string"); std::wstring w_tst1(L"A SMALL TEST STRING"); std::wstring w_tst2(L"A SMALL TEST STRING"); // Test that a string is equal when compared with it self CPPUNIT_ASSERT(SCXCoreLib::StrCompare(w_tst, w_tst, true) == 0); // Test that two strings with different casing is case insensitive equal CPPUNIT_ASSERT(SCXCoreLib::StrCompare(w_tst, w_tst1, true) == 0); // Compare that two different strings with same content are equal CPPUNIT_ASSERT(SCXCoreLib::StrCompare(w_tst1, w_tst2, false) == 0); } void testIsPrefix() { std::wstring w_tst(L"a small test string"); std::wstring w_tst1(L"a small"); std::wstring w_tst2(L"A SMALL"); // Test that an equally cased substring is prefix CPPUNIT_ASSERT(SCXCoreLib::StrIsPrefix(w_tst, w_tst1)); // Test that an differently cased substring is not prefix CPPUNIT_ASSERT( ! SCXCoreLib::StrIsPrefix(w_tst, w_tst2)); // Test that an equally cased substring is case insensitve prefix CPPUNIT_ASSERT(SCXCoreLib::StrIsPrefix(w_tst, w_tst1, true)); // Test that an differently cased substring is case insensitve prefix CPPUNIT_ASSERT(SCXCoreLib::StrIsPrefix(w_tst, w_tst2, true)); } void testAppend() { std::wstring w_tst(L"a small "); scxulong i = 4711; std::wstring w_tst3(L"a small 4711"); // Test that appending an integer to a string results in the two being concatenated CPPUNIT_ASSERT(w_tst3 == SCXCoreLib::StrAppend(w_tst, i)); } void testTokenize() { std::vector<std::wstring> tokens; // Test trimming and no empty tokens SCXCoreLib::StrTokenize(L"a small test\nstring", tokens); CPPUNIT_ASSERT(tokens.size() == 4); CPPUNIT_ASSERT(tokens[0] == L"a"); CPPUNIT_ASSERT(tokens[1] == L"small"); CPPUNIT_ASSERT(tokens[2] == L"test"); CPPUNIT_ASSERT(tokens[3] == L"string"); // Test trimming and empty tokens SCXCoreLib::StrTokenize(L"a x smally x test zstring", tokens, L"xyz", true, true); CPPUNIT_ASSERT(tokens.size() == 5); CPPUNIT_ASSERT(tokens[0] == L"a"); CPPUNIT_ASSERT(tokens[1] == L"small"); CPPUNIT_ASSERT(tokens[2] == L""); CPPUNIT_ASSERT(tokens[3] == L"test"); CPPUNIT_ASSERT(tokens[4] == L"string"); // Test no trimming and no empty tokens SCXCoreLib::StrTokenize(L"a x smallyx test zstring", tokens, L"xyz", false, false); CPPUNIT_ASSERT(tokens.size() == 4); CPPUNIT_ASSERT(tokens[0] == L"a "); CPPUNIT_ASSERT(tokens[1] == L" small"); CPPUNIT_ASSERT(tokens[2] == L" test "); CPPUNIT_ASSERT(tokens[3] == L"string"); // Test no trimming and empty tokens SCXCoreLib::StrTokenize(L"a x smallyx test zstring", tokens, L"xyz", false, true); CPPUNIT_ASSERT(tokens.size() == 5); CPPUNIT_ASSERT(tokens[0] == L"a "); CPPUNIT_ASSERT(tokens[1] == L" small"); CPPUNIT_ASSERT(tokens[2] == L""); CPPUNIT_ASSERT(tokens[3] == L" test "); CPPUNIT_ASSERT(tokens[4] == L"string"); // Test that a string without separators are returned as a single token SCXCoreLib::StrTokenize(L"abc", tokens, L" "); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"abc"); // Test that an empty string results in a single empty token or no token at all (depending on parameters) SCXCoreLib::StrTokenize(L"", tokens, L" ", true, true); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L""); SCXCoreLib::StrTokenize(L"", tokens, L" ", true, false); CPPUNIT_ASSERT(tokens.size() == 0); // Test that an empty separator results in a single token (as if no separator found) SCXCoreLib::StrTokenize(L"a b c", tokens, L""); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"a b c"); // Test separators beginning/end of string SCXCoreLib::StrTokenize(L" abc ", tokens, L" ", false, true); CPPUNIT_ASSERT(tokens.size() == 3); CPPUNIT_ASSERT(tokens[0] == L""); CPPUNIT_ASSERT(tokens[1] == L"abc"); CPPUNIT_ASSERT(tokens[2] == L""); SCXCoreLib::StrTokenize(L" abc ", tokens, L" ", true, false); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"abc"); SCXCoreLib::StrTokenize(L" abc ", tokens, L" ", false, false); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"abc"); // test only separators result in (no) tokens depending on parameter SCXCoreLib::StrTokenize(L";;", tokens, L";"); CPPUNIT_ASSERT(tokens.size() == 0); SCXCoreLib::StrTokenize(L";;", tokens, L";", true, true); CPPUNIT_ASSERT(tokens.size() == 3); CPPUNIT_ASSERT(tokens[0] == L""); CPPUNIT_ASSERT(tokens[1] == L""); CPPUNIT_ASSERT(tokens[2] == L""); } void testTokenizeStr() { std::vector<std::wstring> tokens; // Test trimming and no empty tokens SCXCoreLib::StrTokenizeStr(L"a small small testsmallstring", tokens, L"small"); CPPUNIT_ASSERT(tokens.size() == 3); CPPUNIT_ASSERT(tokens[0] == L"a"); CPPUNIT_ASSERT(tokens[1] == L"test"); CPPUNIT_ASSERT(tokens[2] == L"string"); // Test trimming and empty tokens SCXCoreLib::StrTokenizeStr(L"a small small testsmallstring", tokens, L"small", true, true); CPPUNIT_ASSERT(tokens.size() == 4); CPPUNIT_ASSERT(tokens[0] == L"a"); CPPUNIT_ASSERT(tokens[1] == L""); CPPUNIT_ASSERT(tokens[2] == L"test"); CPPUNIT_ASSERT(tokens[3] == L"string"); // Test no trimming and no empty tokens SCXCoreLib::StrTokenizeStr(L"a small small testsmallsmallstring", tokens, L"small", false, false); CPPUNIT_ASSERT(tokens.size() == 4); CPPUNIT_ASSERT(tokens[0] == L"a "); CPPUNIT_ASSERT(tokens[1] == L" "); CPPUNIT_ASSERT(tokens[2] == L" test"); CPPUNIT_ASSERT(tokens[3] == L"string"); // Test no trimming and empty tokens SCXCoreLib::StrTokenizeStr(L"a small small testsmallsmallstring", tokens, L"small", false, true); CPPUNIT_ASSERT(tokens.size() == 5); CPPUNIT_ASSERT(tokens[0] == L"a "); CPPUNIT_ASSERT(tokens[1] == L" "); CPPUNIT_ASSERT(tokens[2] == L" test"); CPPUNIT_ASSERT(tokens[3] == L""); CPPUNIT_ASSERT(tokens[4] == L"string"); // Test that a string without separators are returned as a single token SCXCoreLib::StrTokenizeStr(L"abc", tokens, L"cab"); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"abc"); // Test that an empty string results in a single empty token or no token at all (depending on parameters) SCXCoreLib::StrTokenizeStr(L"", tokens, L"abc", true, true); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L""); SCXCoreLib::StrTokenizeStr(L"", tokens, L"abc", true, false); CPPUNIT_ASSERT(tokens.size() == 0); // Test that an empty separator results in a single token (as if no separator found) SCXCoreLib::StrTokenizeStr(L"a b c", tokens, L""); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"a b c"); // Test separators beginning/end of string SCXCoreLib::StrTokenizeStr(L"cababccab", tokens, L"cab", false, true); CPPUNIT_ASSERT(tokens.size() == 3); CPPUNIT_ASSERT(tokens[0] == L""); CPPUNIT_ASSERT(tokens[1] == L"abc"); CPPUNIT_ASSERT(tokens[2] == L""); SCXCoreLib::StrTokenizeStr(L"cababccab", tokens, L"cab", false, false); CPPUNIT_ASSERT(tokens.size() == 1); CPPUNIT_ASSERT(tokens[0] == L"abc"); // test only separators result in (no) tokens depending on parameter SCXCoreLib::StrTokenizeStr(L"cabcab", tokens, L"cab"); CPPUNIT_ASSERT(tokens.size() == 0); SCXCoreLib::StrTokenizeStr(L"cabcab", tokens, L"cab", true, true); CPPUNIT_ASSERT(tokens.size() == 3); CPPUNIT_ASSERT(tokens[0] == L""); CPPUNIT_ASSERT(tokens[1] == L""); CPPUNIT_ASSERT(tokens[2] == L""); } void testToIntETC() { try { std::wstring w_tst(L"4711"); std::wstring w_tst2(L" 4711 "); std::wstring w_tst3(L"-42"); std::wstring w_tst4(L" -42 "); // StrToUInt CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToUInt(w_tst)); CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToUInt(w_tst2)); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToUInt(L"Not a number"), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToUInt(w_tst3), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToUInt(w_tst4), SCXCoreLib::SCXNotSupportedException); // Note: We can't detect overflow. The following will succeed. //CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToUInt(L"999999999999999999999999999999"), // SCXCoreLib::SCXNotSupportedException); // StrToDouble CPPUNIT_ASSERT(SCXCoreLib::Equal(4711, SCXCoreLib::StrToDouble(w_tst), 0)); CPPUNIT_ASSERT(SCXCoreLib::Equal(4711, SCXCoreLib::StrToDouble(w_tst2), 0)); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToDouble(L"Not a number"), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT(SCXCoreLib::Equal(-42, SCXCoreLib::StrToDouble(w_tst3), 0)); CPPUNIT_ASSERT(SCXCoreLib::Equal(-42, SCXCoreLib::StrToDouble(w_tst4), 0)); // StrToLong CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToLong(w_tst)); CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToLong(w_tst2)); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToLong(L"Not a number"), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT(-42 == SCXCoreLib::StrToLong(w_tst3)); CPPUNIT_ASSERT(-42 == SCXCoreLib::StrToLong(w_tst4)); // StrToULong CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToULong(w_tst)); CPPUNIT_ASSERT(4711 == SCXCoreLib::StrToULong(w_tst2)); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToULong(L"Not a number"), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToULong(w_tst3), SCXCoreLib::SCXNotSupportedException); CPPUNIT_ASSERT_THROW(SCXCoreLib::StrToULong(w_tst4), SCXCoreLib::SCXNotSupportedException); } catch (SCXException& e) { std::wcout << L"\nException in testToIntETC: " << e.What() << L" @ " << e.Where() << std::endl; CPPUNIT_ASSERT(!"Exception"); } } void testFrom() { CPPUNIT_ASSERT(L"42" == SCXCoreLib::StrFrom(static_cast<unsigned int>(42))); CPPUNIT_ASSERT(L"42" == SCXCoreLib::StrFrom(static_cast<scxulong>(42))); CPPUNIT_ASSERT(L"-4711" == SCXCoreLib::StrFrom(static_cast<scxlong>(-4711))); CPPUNIT_ASSERT(L"-47.11" == SCXCoreLib::StrFrom(static_cast<double>(-47.11))); CPPUNIT_ASSERT(L"42" == SCXCoreLib::StrFrom(static_cast<double>(42))); } void testUTF8Conversion() { bool solarisAndClocale = false; #if defined(sun) solarisAndClocale = (SCXLocaleContext::GetCtypeName() == L"C"); #endif CPPUNIT_ASSERT( SCXCoreLib::StrFromUTF8( SCXCoreLib::StrToUTF8(L"")) == L""); CPPUNIT_ASSERT( SCXCoreLib::StrFromUTF8( SCXCoreLib::StrToUTF8(L"Test string 1 - Simple")) == L"Test string 1 - Simple"); if (!solarisAndClocale) { CPPUNIT_ASSERT( SCXCoreLib::StrFromUTF8( SCXCoreLib::StrToUTF8(L"Test string 2 - With åäöÅÄÖ")) == L"Test string 2 - With åäöÅÄÖ"); CPPUNIT_ASSERT( SCXCoreLib::StrFromUTF8( SCXCoreLib::StrToUTF8(L"Hello world, Καλημ%Gα½³%@ρα κ%Gα½Ή%@σμε, コンニチハ")) == L"Hello world, Καλημ%Gα½³%@ρα κ%Gα½Ή%@σμε, コンニチハ"); } } void testUTF8ConversionFails() { std::string utf8("AB"); // Create an invalid UTF8 sequence: utf8[0] = (char)0xC3; utf8[1] = (char)0x00; SCXUNIT_ASSERT_THROWN_EXCEPTION(SCXCoreLib::StrFromUTF8(utf8), SCXCoreLib::SCXStringConversionException, L"Multibyte"); } void testMergeTokens() { std::wstring s = L"this 'is' \"a string\" with (lot's (sic!) of) ' variants ' 'for you'"; std::vector<std::wstring> tokens; std::map<std::wstring,std::wstring> m; // Set up the merge identifier pairs m[L"\""] = L"\""; m[L"'"] = L"'"; m[L"("] = L")"; SCXCoreLib::StrTokenize(s, tokens); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(13), tokens.size()); CPPUNIT_ASSERT(SCXCoreLib::StrMergeTokens(tokens, m, L" ")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(8), tokens.size()); CPPUNIT_ASSERT(L"this" == tokens[0]); CPPUNIT_ASSERT(L"is" == tokens[1]); CPPUNIT_ASSERT(L"a string" == tokens[2]); CPPUNIT_ASSERT(L"with" == tokens[3]); CPPUNIT_ASSERT(L"lot's (sic!" == tokens[4]); CPPUNIT_ASSERT(L"of)" == tokens[5]); CPPUNIT_ASSERT(L"variants" == tokens[6]); CPPUNIT_ASSERT(L"for you" == tokens[7]); // test mismatch tokens.clear(); SCXCoreLib::StrTokenize(L"a (b c", tokens); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), tokens.size()); CPPUNIT_ASSERT( ! SCXCoreLib::StrMergeTokens(tokens, m, L" ")); } void testTokenizeWithDelimiters() { std::vector<std::wstring> tokens; SCXCoreLib::StrTokenize(L"a=b c", tokens, L" =", false, false, true); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(6), tokens.size()); CPPUNIT_ASSERT(L"a" == tokens[0]); CPPUNIT_ASSERT(L"=" == tokens[1]); CPPUNIT_ASSERT(L"b" == tokens[2]); CPPUNIT_ASSERT(L" " == tokens[3]); CPPUNIT_ASSERT(L" " == tokens[4]); CPPUNIT_ASSERT(L"c" == tokens[5]); } void testFromMultibyte() { CPPUNIT_ASSERT(SCXCoreLib::StrFromUTF8("abc") == L"abc"); } void testFromMultibyteNoThrow() { CPPUNIT_ASSERT(SCXCoreLib::StrFromMultibyteNoThrow("abc") == L"abc"); // This test is sensitive to locale (don't run unless it's UTF-8) // // If the codepage isn't UTF-8, then method mbsrtowcs() doesn't throw, // but doesn't appear to generate something that std::wcout is able to // print, it seems. This is impossible for us to detect, though, since // no error is returned and no exception is thrown. const char *localeStr = nl_langinfo(CODESET); if ( NULL != localeStr && strcasecmp(localeStr, "UTF8") != 0 && strcasecmp(localeStr, "UTF-8") != 0 ) { SCXUNIT_WARNING( StrAppend(L"Test SCXStringAid_Test::testFromMultibyteNoThrow requires UTF-8 codepage to run properly, existing codpage: ", localeStr) ); return; } // It's difficult to get this string in place via C++, so use a hammer // We have to replace the 'X' (at end of string) with hex C0, octal 300 char badString[16]; strncpy( badString, "alxapfs34X", sizeof(badString) ); CPPUNIT_ASSERT( 'X' == badString[9] ); badString[9] = static_cast<char> (0xC0); CPPUNIT_ASSERT(SCXCoreLib::StrFromMultibyteNoThrow(std::string(badString)) == L"alxapfs34?"); } void testToUTF8() { CPPUNIT_ASSERT(SCXCoreLib::StrToUTF8(L"abc") == "abc"); } class MyException : public std::exception { public: virtual const char *what() const throw() { return "problem"; } }; void testDumpStringException() { MyException e; std::wstring text(SCXCoreLib::DumpString(e)); CPPUNIT_ASSERT(text.find(L"MyException") != std::wstring::npos && text.find(L"problem") != std::wstring::npos); } void testUtfUpDownCase() { unsigned int c; unsigned int uc1; unsigned int uc2; unsigned int Errors = 0; // upper case test for (size_t i = 0; i < sizeof UpcaseTestTable / sizeof (TestInfo); i++) { c = UpcaseTestTable[i].Char; uc1 = SCXCoreLib::UtfToUpper(c); if (uc1 != c) { uc2 = SCXCoreLib::UtfToLower(uc1); } else { uc2 = c; } if (uc2 != c || uc1 != UpcaseTestTable[i].Converted) { Errors++; } } CPPUNIT_ASSERT(Errors == 0); // lower case test Errors = 0; for (size_t i = 0; i < sizeof DowncaseTestTable / sizeof (TestInfo); i++) { c = DowncaseTestTable[i].Char; uc1 = SCXCoreLib::UtfToLower(c); if (uc1 != c) { uc2 = SCXCoreLib::UtfToUpper(uc1); } else { uc2 = c; } if (uc2 != c || uc1 != DowncaseTestTable[i].Converted) { Errors++; } } CPPUNIT_ASSERT(Errors == 0); return; } /** Here we test that vsnprintf() conforms to the UNIX03 specifiction as opposed to the conflicting definition from UNIX95. The core lib does not depend on this, but OpenWSMan does. OpenWSMan has no unit tests, so this seems like a resonable place to put the test. See also WI5724. */ void testUNIX03() { CPPUNIT_ASSERT_MESSAGE("vsnprintf() does not conform to UNIX03. ", u03helper("123%s", "456") == 6); } int u03helper(const char *fmt, ...) { va_list ap2; int size = 0; va_start(ap2, fmt); /* Should compute the size requirement under UNIX03, but returns 0 to indicate failure under UNIX95 */ size = vsnprintf(NULL, 0, fmt, ap2); va_end(ap2); return size; } // Debugging routine void DumpVector(const std::vector<std::wstring>& vector) { std::wcout << std::endl; std::wcout << L" Vector size: " << vector.size() << std::endl; for (size_t i = 0; i < vector.size(); ++i) { std::wcout << L" Element " << i << L": \"" << vector[i] << L"\"" << std::endl; } } void test_Empty_String() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L"", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(0), tokens.size() ); } void test_Nonquoted_String_OnlySpaces() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(0), tokens.size() ); } void test_Nonquoted_String_EmptyTokensOnly() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" , , , ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(0), tokens.size() ); } void test_Nonquoted_String() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" A, B , , C ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A"), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"B"), tokens[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[2] ); } void test_Nonquoted_String_ReturnEmptyTokens() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" A, B , , C ", tokens, L",", true); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(4), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A"), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"B"), tokens[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L""), tokens[2] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[3] ); } void test_QuotedQuotes_Ignored() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" A, B \\\" , , C ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A"), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"B \\\""), tokens[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[2] ); } void test_Quoted_String() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" \"A, B \", , C ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[1] ); } void test_Quoted_String_Double() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" \"A, B ', C, D' \", , E ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B ', C, D' "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"E"), tokens[1] ); } void test_Quoted_SingleQuote() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" 'A, B ', , C ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[1] ); } void test_Quoted_SingleQuote_ReturnEmptyTokens() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" 'A, B ', , C ", tokens, L",", true); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L""), tokens[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"C"), tokens[2] ); } void test_Quoted_SingleQuote_QuotedSpaces() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" ' ', , A ", tokens, L",", true); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L" "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L""), tokens[1] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A"), tokens[2] ); } void test_Quoted_String_QuotedQuotes() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" \"A, B \\\" CD \\\" \" , E ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B \\\" CD \\\" "), tokens[0] ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"E"), tokens[1] ); } void test_Quoted_SingleQuotedElement() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" \"A, B \" ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"A, B "), tokens[0] ); } void test_Quoted_UnterminatedQuote() { std::vector<std::wstring> tokens; StrTokenizeQuoted(L" \"A, B ", tokens, L","); CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), tokens.size() ); CPPUNIT_ASSERT_EQUAL( std::wstring(L"\"A, B"), tokens[0] ); } }; CPPUNIT_TEST_SUITE_REGISTRATION( SCXStringAid_Test );
38.280637
165
0.598169
[ "vector" ]
dc96e22570035fb13e7a836f9bd863660c4a2f2f
10,141
cpp
C++
pack.cpp
google/elfling
35164742157c2ab04c8fea693256e8a154c02133
[ "Apache-2.0" ]
26
2015-01-28T08:28:22.000Z
2021-06-29T23:08:29.000Z
pack.cpp
google/elfling
35164742157c2ab04c8fea693256e8a154c02133
[ "Apache-2.0" ]
null
null
null
pack.cpp
google/elfling
35164742157c2ab04c8fea693256e8a154c02133
[ "Apache-2.0" ]
11
2015-01-25T18:38:56.000Z
2021-07-12T12:25:06.000Z
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // elfling - a linking compressor for ELF files by Minas ^ Calodox #include "pack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int cmax = 0; #define CONTEXT_COUNT 8 #define GENOME_SIZE 48 #define GENOME_ITERATIONS 100 #define MAX_WEIGHT 60 int FromHexDigit(char d) { if (d >= '0' && d <= '9') return d - '0'; if (d >= 'A' && d <= 'F') return d - 'A' + 10; if (d >= 'a' && d <= 'f') return d - 'a' + 10; return -1; } int FromHex2(const char* str) { int d0 = FromHexDigit(str[0]); int d1 = FromHexDigit(str[1]); if (d0 < 0 || d1 < 0) return -1; return d0 * 16 + d1; } void ToHex2(int v, char* dst) { const char* hd = "0123456789abcdef"; dst[0] = hd[(v >> 4) & 0x0f]; dst[1] = hd[v & 0x0f]; } bool CompressionParameters::FromString(const char* str) { int l = strlen(str); if (l < 10) return false; // Expect at least two contexts. contextCount = FromHex2(str); if (contextCount < 2 || contextCount > MAX_CONTEXT_COUNT) return false; if (l != 2 + 4 * contextCount) return false; for (int i = 0; i < contextCount; ++i) { weights[i] = FromHex2(str + 2 + 4 * i); contexts[i] = FromHex2(str + 4 + 4 * i); } return true; } void CompressionParameters::ToString(char* str) { ToHex2(contextCount, str); for (int i = 0; i < contextCount; ++i) { ToHex2(weights[i], str + 2 + 4 * i); ToHex2(contexts[i], str + 4 + 4 * i); } str[2 + 4 * contextCount] = 0; } struct Context { u8 ctx; int bs; int bw; }; static int CompareContext(const Context* a, const Context* b) { return a->bs - b->bs; } struct Genome { CompressionParameters params; int fitness; }; static int CompareGenome(const Genome* a, const Genome* b) { if (a->fitness != b->fitness) { return a->fitness - b->fitness; } for (int i = 0; i < CONTEXT_COUNT; ++i) { if (a->params.weights[i] != b->params.weights[i]) return a->params.weights[i] - b->params.weights[i]; if (a->params.contexts[i] != b->params.contexts[i]) return a->params.contexts[i] - b->params.contexts[i]; } return 0; } bool Compressor::Compress(CompressionParameters* params, void* in, int inLen, void* out, int* outLen) { // Test all context patterns individually to figure out which ones are most // likely to produce good results for seeding our initial set. Context pats[128]; u32 pc = 0; int orgOutLen = *outLen; for (u32 i = 3; i < 256; i += 2) { u32 bc = 0; for (u8 b = 0; b < 8; ++b) { if (i & (1 << b)) ++bc; } if (bc > 4) continue; // Only keep patterns with 4 bytes at most. pats[pc].ctx = i; pats[pc].bs = *outLen; pats[pc].bw = 0; CompressionParameters c; c.contextCount = 2; c.weights[0] = 8; c.weights[1] = 1; c.contexts[0] = pats[pc].ctx; c.contexts[1] = 1; CompressSingle(&c, in, inLen, out, &pats[pc].bs); ++pc; } qsort(pats, pc, sizeof(Context), (__compar_fn_t)CompareContext); if (verbose_) { for (int i = 0; i < pc; ++i) { printf("Pattern %2d [%2.2x] = %d bytes @ %d\n", i, pats[i].ctx, pats[i].bs, pats[i].bw); } } Genome* g = new Genome[GENOME_SIZE]; for (int i = 0; i < GENOME_SIZE; ++i) { g[i].params.contextCount = CONTEXT_COUNT; g[i].params.contexts[0] = 1; g[i].params.weights[0] = 1; for (int j = 1; j < CONTEXT_COUNT; ++j) { if (i == 0) { g[i].params.contexts[j] = pats[j - 1].ctx; g[i].params.weights[j] = 20; } else { g[i].params.contexts[j] = pats[rand() % (pc / 4)].ctx; g[i].params.weights[j] = rand() % MAX_WEIGHT + 1; } } } if (params->contextCount) { g[1].params = *params; } for (int i = 0; i < GENOME_ITERATIONS; ++i) { for (int j = 0; j < GENOME_SIZE; ++j) { g[j].fitness = *outLen; CompressSingle(&g[j].params, in, inLen, out, &g[j].fitness); } qsort(g, GENOME_SIZE, sizeof(Genome), (__compar_fn_t)CompareGenome); for (int j = 0; j < GENOME_SIZE; ++j) { if (j >= 3) break; printf("I[%3d,%d]: %d", i, j, g[j].fitness); for (int i = 0; i < g[j].params.contextCount; ++i) { printf(" %2d*%2.2x", g[j].params.weights[i], g[j].params.contexts[i]); } printf("\n"); } *params = g[0].params; srand(time(nullptr)); int keep = GENOME_SIZE / 4; for (int j = 0; j < GENOME_SIZE; ++j) { g[j].fitness = 0; } for (int j = keep; j < GENOME_SIZE / 2; j += 2) { int m1 = rand() % keep; int m2 = rand() % keep; while (m2 == m1) { m2 = rand() % keep; } int cb = rand() % (CONTEXT_COUNT * 2); bool equals = true; for (int k = 0; k < 2 * CONTEXT_COUNT; ++k) { u8* trg1 = (k & 1) ? g[j].params.contexts : g[j].params.weights; u8* trg2 = (k & 1) ? g[j + 1].params.contexts : g[j + 1].params.weights; u8* src1 = (k & 1) ? g[m1].params.contexts : g[m1].params.weights; u8* src2 = (k & 1) ? g[m2].params.contexts : g[m2].params.weights; if (k >= cb) { u8* tmp = src1; src1 = src2; src2 = tmp; } trg1[k >> 1] = src1[k >> 1]; trg2[k >> 1] = src2[k >> 1]; } } qsort(g, GENOME_SIZE / 2, sizeof(Genome), (__compar_fn_t)CompareGenome); for (int j = 1; j < GENOME_SIZE / 2; ++j) { if (!memcmp(g[j].params.weights, g[j - 1].params.weights, CONTEXT_COUNT) && !memcmp(g[j].params.contexts, g[j - 1].params.contexts, CONTEXT_COUNT)) { int byte = rand() % (2 * CONTEXT_COUNT); if (byte < CONTEXT_COUNT) { g[j - 1].params.contexts[byte] = pats[rand() % pc].ctx; } else { g[j - 1].params.weights[byte - CONTEXT_COUNT] = rand() % MAX_WEIGHT + 1; } } } for (int j = GENOME_SIZE / 2; j < GENOME_SIZE; ++j) { memcpy(&g[j], &g[j % keep], sizeof(Genome)); int limit = 1; if (j > 3 * GENOME_SIZE / 4) limit = 3; for (int k = 0; k < 3; ++k) { // Mutation. int byte = rand() % (2 * CONTEXT_COUNT); if (byte < CONTEXT_COUNT) { g[j].params.contexts[byte] = pats[rand() % pc].ctx; } else { g[j].params.weights[byte - CONTEXT_COUNT] = rand() % MAX_WEIGHT + 1; } } } } delete[] g; if (CompressSingle(params, in, inLen, out, outLen)) { printf("Final: %d", *outLen); for (int i = 0; i < params->contextCount; ++i) { printf(" %2d*%2.2x", params->weights[i], params->contexts[i]); } printf("\n"); printf("cmax: %d\n", cmax); char buf[128]; params->ToString(buf); printf("Params: %s\n", buf); return true; } printf("Failed, for some reason could not recompress with optimal settings\n"); return false; } bool Compressor::CompressSingle(CompressionParameters* comp, void* in, int inLen, void* out, int* outLen) { u8* archive = (u8*)in; u8* output; u8* counters[MAX_CONTEXT_COUNT]; // Counter base offsets u8* cp[MAX_CONTEXT_COUNT]; // Current counters u8 tbuf[8] = {1, 0, 0, 0, 0, 0, 0, 0}; memset(modelCounters_, 0, MAX_CONTEXT_SIZE * comp->contextCount); u8* base = modelCounters_; for (int m = 0; m < comp->contextCount; ++m) { counters[m] = base; cp[m] = base; base += MAX_CONTEXT_SIZE; } u8* cout = (u8*)out; u32 x1 = 0, x2 = 0xffffffff; for (int j = 0; j < inLen; ++j) { u32 byte = *archive++; for (u32 i = 0; i < 8; ++i) { u32 n0 = 1, n1 = 1; for (int m = 0; m < comp->contextCount; ++m) { n0 += cp[m][0] * comp->weights[m]; n1 += cp[m][1] * comp->weights[m]; } u32 xmid = x1 + n0 * (u64)(x2 - x1) / (n0 + n1); int y; if (byte & 0x80) { x1 = xmid + 1; y = 1; } else { x2 = xmid; y = 0; } // Store bit y tbuf[0] += tbuf[0] + y; if (i == 7) { // Start new byte tbuf[7] = tbuf[6]; tbuf[6] = tbuf[5]; tbuf[5] = tbuf[4]; tbuf[4] = tbuf[3]; tbuf[3] = tbuf[2]; tbuf[2] = tbuf[1]; tbuf[1] = tbuf[0]; tbuf[0] = 1; } // Count y by context for (int m = comp->contextCount - 1; m >= 0; --m) { if (cp[m][y] < 255) ++cp[m][y]; if (cp[m][1-y] > 2) cp[m][1-y] = cp[m][1-y] / 2 + 1; u32 off = 0, cnt = 0; for (char i = 0; i < 8; ++i) { if (comp->contexts[m] & (1 << i)) { off = (off << 8) + tbuf[i]; } } // Use a sort of hashtable here. Decompressor just uses c = 0. u32 c = 24 * ((off & 0xffff) ^ (off >> 16)); while (*(u32*)&counters[m][c] != 0 && *(u32*)&counters[m][c] != off) c += 6; if (c > cmax) cmax = c; *(u32*)&counters[m][c] = off; cp[m] = &counters[m][c + 4]; } while (((x1 ^ x2) & 0xff000000) == 0) { *cout++ = x2 >> 24; x1 <<= 8; x2 = (x2 << 8) + 255; if (cout - (u8*)out >= *outLen) return false; } byte <<= 1; } } while (((x1 ^ x2) & 0xff000000)==0) { *cout++ = x2 >> 24; x1 <<= 8; x2 = (x2 << 8) + 255; if (cout - (u8*)out >= *outLen) return false; } *cout++ = x2 >> 24; // First unequal byte // Now for some weirdness: if the next byte happens to be less than 0xc3 (the // ret opcode), we need to output something that's less than that. Zero is a // good candidate. if (((x2 >> 16) & 0xff) < 0xc3) { if (cout - (u8*)out >= *outLen) return false; *cout++ = 0; } *outLen = cout - (u8*)out; return true; }
30.271642
155
0.534267
[ "3d" ]
dc9975d21a6d029472961ff8f1d555ab82e6430c
11,351
cpp
C++
Base/Src/Base/Value.cpp
lxq00/public
5834fac5ba982ff45ea810c5e4de9fe08833cf53
[ "MIT" ]
null
null
null
Base/Src/Base/Value.cpp
lxq00/public
5834fac5ba982ff45ea810c5e4de9fe08833cf53
[ "MIT" ]
null
null
null
Base/Src/Base/Value.cpp
lxq00/public
5834fac5ba982ff45ea810c5e4de9fe08833cf53
[ "MIT" ]
null
null
null
#include "Base/IntTypes.h" #include "Base/Value.h" #include "Base/String.h" #include "Base/BaseTemplate.h" #include <sstream> namespace Public { namespace Base { struct ValueInfo { Value::Type type; union { uint64_t _int; double _float; bool _bool; char *_str; } val; void *ptr; size_t len; ValueInfo() : type(Value::Type_Empty), ptr(NULL),len(0) { val._int = 0; } ~ValueInfo() { clear(); } void clear() { if (type == Value::Type_String) delete[] val._str; type = Value::Type_Empty; val._int = 0; } }; struct Value::ValueInternal { shared_ptr<ValueInfo> val; ValueInternal() { val = make_shared<ValueInfo>(); } void reset() { val = make_shared<ValueInfo>(); } }; Value::Value() { internal = new ValueInternal(); } Value::Value(const std::string &val, Value::Type type) { internal = new ValueInternal(); internal->val->type = type; switch (type) { case Type_Char: sscanf(val.c_str(), "%c", (char *)&internal->val->val._int); break; case Type_Int32: sscanf(val.c_str(), "%d", (int *)&internal->val->val._int); break; case Type_Uint32: sscanf(val.c_str(), "%u", (unsigned int *)&internal->val->val._int); break; case Type_Int64: sscanf(val.c_str(), "%lld", (long long int *)&internal->val->val._int); break; case Type_Uint64: sscanf(val.c_str(), "%llu", (long long unsigned int *)&internal->val->val._int); break; case Type_String: internal->val->len = val.length(); internal->val->val._str = new char[val.length() + 1]; memcpy(internal->val->val._str, val.c_str(), internal->val->len); internal->val->val._str[internal->val->len] = 0; break; case Type_Double: sscanf(val.c_str(), "%lf", &internal->val->val._float); break; case Type_Bool: internal->val->val._bool = String::iequals(val, "true"); break; case Type_Pointer: sscanf(val.c_str(), "%p", &internal->val->ptr); break; default: break; } } Value::Value(const char *val) { internal = new ValueInternal(); if (val != NULL && strlen(val) > 0) { internal->val->len = strlen(val); internal->val->val._str = new char[internal->val->len + 1]; memcpy(internal->val->val._str, val, internal->val->len); internal->val->val._str[internal->val->len] = 0; internal->val->type = Type_String; internal->val->ptr = (void *)val; } } Value::Value(const std::string &val) { internal = new ValueInternal(); if (val.length() > 0) { internal->val->len = val.length(); internal->val->val._str = new char[internal->val->len + 1]; memcpy(internal->val->val._str, val.c_str(), internal->val->len); internal->val->val._str[internal->val->len] = 0; internal->val->type = Type_String; } } Value::Value(const String &val) { internal = new ValueInternal(); if (val.length() > 0) { internal->val->len = val.length(); internal->val->val._str = new char[internal->val->len + 1]; memcpy(internal->val->val._str, val.c_str(), internal->val->len); internal->val->val._str[internal->val->len] = 0; internal->val->type = Type_String; } } Value::Value(const std::vector<char> &val) { internal = new ValueInternal(); if (val.size() > 0) { internal->val->len = val.size(); internal->val->val._str = new char[val.size() + 1]; for (size_t i = 0; i < val.size(); i++) internal->val->val._str[i] = val[i]; internal->val->val._str[val.size()] = 0; internal->val->type = Type_String; } } Value::Value(const unsigned char *val) { internal = new ValueInternal(); if (val != NULL && strlen((const char *)val) > 0) { internal->val->len = strlen((const char *)val); internal->val->val._str = new char[internal->val->len + 1]; memcpy(internal->val->val._str, val, internal->val->len); internal->val->val._str[internal->val->len] = 0; internal->val->type = Type_String; internal->val->ptr = (void *)val; } } Value::Value(char val) { internal = new ValueInternal(); internal->val->type = Type_Char; internal->val->val._int = (uint64_t)val; } Value::Value(int val) { internal = new ValueInternal(); internal->val->type = Type_Int32; internal->val->val._int = (uint64_t)val; } #ifndef __linux__ Value::Value(long val) { internal = new ValueInternal(); internal->val->type = Type_Int64; internal->val->val._int = (uint64_t)val; } Value::Value(unsigned long val) { internal = new ValueInternal(); internal->val->type = Type_Uint64; internal->val->val._int = (uint64_t)val; } #endif Value::Value(double val) { internal = new ValueInternal(); internal->val->type = Type_Double; internal->val->val._float = (double)val; } Value::Value(uint32_t val) { internal = new ValueInternal(); internal->val->type = Type_Uint32; internal->val->val._int = (uint64_t)val; } Value::Value(uint64_t val) { internal = new ValueInternal(); internal->val->type = Type_Uint64; internal->val->val._int = (uint64_t)val; } Value::Value(int64_t val) { internal = new ValueInternal(); internal->val->type = Type_Int64; internal->val->val._int = (uint64_t)val; } Value::Value(bool val) { internal = new ValueInternal(); internal->val->type = Type_Bool; internal->val->val._bool = val; } Value::Value(const Value &val) { internal = new ValueInternal(); internal->val = val.internal->val; } Value::Value(const void *val) { _alloc(val); } Value::~Value() { SAFE_DELETE(internal); } Value &Value::operator=(const Value &val) { internal->reset(); internal->val = val.internal->val; return *this; } bool Value::operator==(const Value &val) const { if (internal->val == val.internal->val) return true; else if (type() == val.type() && readString() == val.readString()) return true; return false; } Value::Type Value::type() const { return internal->val->type; } Value::operator std::string() const { return readString(); } Value::operator uint64_t() const { return readUint64(); } Value::operator uint32_t() const { return readUint32(); } Value::operator int64_t() const { return readInt64(); } Value::operator int32_t() const { return readInt(); } Value::operator bool() const { return readBool(); } Value::operator double() const { return readFloat(); } Value::operator float() const { return readFloat(); } std::string Value::readString(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%c" : fmt.c_str(), (char)internal->val->val._int); return buffer; } case Type_Int32: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%d" : fmt.c_str(), (int)internal->val->val._int); return buffer; } case Type_Uint32: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%u" : fmt.c_str(), (int)internal->val->val._int); return buffer; } case Type_Int64: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%lld" : fmt.c_str(), (long long int)internal->val->val._int); return buffer; } case Type_Uint64: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%llu" : fmt.c_str(), (long long int)internal->val->val._int); return buffer; } case Type_String: return std::string(internal->val->val._str, internal->val->len); case Type_Double: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%lf" : fmt.c_str(), internal->val->val._float); return buffer; } case Type_Bool: return internal->val->val._bool ? "true" : "false"; case Type_Pointer: { char buffer[32] = {0}; snprintf(buffer, 31, fmt == "" ? "%p" : fmt.c_str(), internal->val->ptr); return buffer; } default: break; } return ""; } int Value::readInt(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return (int)internal->val->val._int; case Type_String: { int val = 0; sscanf(internal->val->val._str, fmt == "" ? "%d" : fmt.c_str(), &val); return val; } case Type_Double: return (int)internal->val->val._float; case Type_Bool: return internal->val->val._bool ? 1 : 0; case Type_Pointer: { return (int)(long)internal->val->ptr; } default: break; } return 0; } float Value::readFloat(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return (float)internal->val->val._int; case Type_String: { float val = 0; sscanf(internal->val->val._str, fmt == "" ? "%f" : fmt.c_str(), &val); return val; } case Type_Double: return (float)internal->val->val._float; case Type_Bool: return internal->val->val._bool ? (float)1.0 : (float)0.0; case Type_Pointer: { return (float)(long long)internal->val->ptr; } default: break; } return (float)0.0; } long long Value::readInt64(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return (long long)internal->val->val._int; case Type_String: { long long val = 0; sscanf(internal->val->val._str, fmt == "" ? "%lld" : fmt.c_str(), &val); return val; } case Type_Double: return (long long)internal->val->val._float; case Type_Bool: return internal->val->val._bool ? 1 : 0; case Type_Pointer: { return (long long)internal->val->ptr; } default: break; } return 0; } uint32_t Value::readUint32(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return (uint32_t)internal->val->val._int; case Type_String: { uint32_t val = 0; sscanf(internal->val->val._str, fmt == "" ? "%u" : fmt.c_str(), &val); return val; } case Type_Double: return (uint32_t)internal->val->val._float; case Type_Bool: return internal->val->val._bool ? 1 : 0; case Type_Pointer: { return (uint32_t)(long)internal->val->ptr; } default: break; } return 0; } uint64_t Value::readUint64(const std::string &fmt) const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return (uint64_t)internal->val->val._int; case Type_String: { uint64_t val = 0; sscanf(internal->val->val._str, fmt == "" ? "%llu" : fmt.c_str(), (long long unsigned int *)&val); return val; } case Type_Double: return (uint64_t)internal->val->val._float; case Type_Bool: return internal->val->val._bool ? 1 : 0; case Type_Pointer: { return (uint64_t)internal->val->ptr; } default: break; } return 0; } bool Value::readBool() const { switch (internal->val->type) { case Type_Char: case Type_Int32: case Type_Uint32: case Type_Int64: case Type_Uint64: return internal->val->val._int != 0; case Type_String: return String::iequals(internal->val->val._str, "true") || atoi(internal->val->val._str) != 0; case Type_Double: return (int)internal->val->val._float != 0; case Type_Bool: return internal->val->val._bool; case Type_Pointer: { return internal->val->ptr != NULL; } default: break; } return false; } const void *Value::readPointer() const { return internal->val->ptr; } bool Value::empty() const { return internal->val->type == Type_Empty; } void Value::_alloc(const void *val) { internal = new ValueInternal(); internal->reset(); internal->val->type = Type_Pointer; internal->val->val._int = 0; internal->val->ptr = (void *)val; } } // namespace Base } // namespace Public
22.040777
100
0.657916
[ "vector" ]
dc9a4591b35830489b70c0b132c64d28861eeaa8
25,417
cpp
C++
routing_common/bicycle_model.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
routing_common/bicycle_model.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
routing_common/bicycle_model.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
#include "routing_common/bicycle_model.hpp" #include "base/assert.hpp" #include "base/macros.hpp" #include "base/logging.hpp" #include "indexer/classificator.hpp" #include "indexer/feature.hpp" using namespace routing; namespace { // See model specifics in different countries here: // http://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Access-Restrictions // Document contains proposals for some countries, but we assume that some kinds of roads are ready for bicycle routing, // but not listed in tables in the document. For example, steps are not listed, paths, roads and services features also // can be treated as ready for bicycle routing. These road types were added to lists below. // See road types here: // http://wiki.openstreetmap.org/wiki/Key:highway // Heuristics: // For less bicycle roads we add fine by setting smaller value of speed, and for more bicycle roads we // set greater values of speed. Algorithm picks roads with greater speed first, preferencing a more bicycle roads over // less bicycle. As result of such heuristic road is not totally the shortest, but it avoids non bicycle roads, which were // not marked as "hwtag=nobicycle" in OSM. double constexpr kSpeedTrunkKMpH = 3.0; double constexpr kSpeedTrunkLinkKMpH = 3.0; double constexpr kSpeedPrimaryKMpH = 5.0; double constexpr kSpeedPrimaryLinkKMpH = 5.0; double constexpr kSpeedSecondaryKMpH = 15.0; double constexpr kSpeedSecondaryLinkKMpH = 15.0; double constexpr kSpeedTertiaryKMpH = 15.0; double constexpr kSpeedTertiaryLinkKMpH = 15.0; double constexpr kSpeedServiceKMpH = 12.0; double constexpr kSpeedUnclassifiedKMpH = 12.0; double constexpr kSpeedRoadKMpH = 10.0; double constexpr kSpeedTrackKMpH = 8.0; double constexpr kSpeedPathKMpH = 6.0; double constexpr kSpeedBridlewayKMpH = 4.0; double constexpr kSpeedCyclewayKMpH = 15.0; double constexpr kSpeedResidentialKMpH = 8.0; double constexpr kSpeedLivingStreetKMpH = 7.0; double constexpr kSpeedStepsKMpH = 1.0; double constexpr kSpeedPedestrianKMpH = 5.0; double constexpr kSpeedFootwayKMpH = 7.0; double constexpr kSpeedPlatformKMpH = 3.0; double constexpr kSpeedPierKMpH = 7.0; // Default VehicleModel::InitListT const g_bicycleLimitsDefault = { { {"highway", "trunk"}, kSpeedTrunkKMpH, true /* transitAllowed */ }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // All options available. VehicleModel::InitListT const g_bicycleLimitsAll = { { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "bridleway"}, kSpeedBridlewayKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "footway"}, kSpeedFootwayKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Same as defaults except trunk and trunk_link are not allowed VehicleModel::InitListT const g_bicycleLimitsNoTrunk = { { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Same as defaults except pedestrian is allowed VehicleModel::InitListT const g_bicycleLimitsPedestrianAllowed = { { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Same as defaults except bridleway is allowed VehicleModel::InitListT const g_bicycleLimitsBridlewayAllowed = { { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "bridleway"}, kSpeedBridlewayKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Australia VehicleModel::InitListT const g_bicycleLimitsAustralia = g_bicycleLimitsAll; // Austria VehicleModel::InitListT const g_bicycleLimitsAustria = { // No trunk, trunk_link, path { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Belarus VehicleModel::InitListT const g_bicycleLimitsBelarus = { // Footway and pedestrian are allowed { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "footway"}, kSpeedFootwayKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Belgium VehicleModel::InitListT const g_bicycleLimitsBelgium = { // No trunk, trunk_link // Pedestrian is allowed { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Brazil VehicleModel::InitListT const g_bicycleLimitsBrazil = { // Bridleway and fotway are allowed { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "bridleway"}, kSpeedBridlewayKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "footway"}, kSpeedFootwayKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Denmark VehicleModel::InitListT const g_bicycleLimitsDenmark = g_bicycleLimitsNoTrunk; // France VehicleModel::InitListT const g_bicycleLimitsFrance = { // No trunk, trunk_link // Pedestrian is allowed { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Finland VehicleModel::InitListT const g_bicycleLimitsFinland = g_bicycleLimitsPedestrianAllowed; // Germany VehicleModel::InitListT const g_bicycleLimitsGermany = g_bicycleLimitsDefault; // Hungary VehicleModel::InitListT const g_bicycleLimitsHungary = g_bicycleLimitsNoTrunk; // Iceland VehicleModel::InitListT const g_bicycleLimitsIceland = g_bicycleLimitsAll; // Netherlands VehicleModel::InitListT const g_bicycleLimitsNetherlands = g_bicycleLimitsNoTrunk; // Norway VehicleModel::InitListT const g_bicycleLimitsNorway = g_bicycleLimitsAll; // Oman VehicleModel::InitListT const g_bicycleLimitsOman = g_bicycleLimitsBridlewayAllowed; // Poland VehicleModel::InitListT const g_bicycleLimitsPoland = g_bicycleLimitsNoTrunk; // Romania VehicleModel::InitListT const g_bicycleLimitsRomania = g_bicycleLimitsNoTrunk; // Russian Federation VehicleModel::InitListT const g_bicycleLimitsRussia = { // Footway and pedestrian are allowed // No transit for service and living_street { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, false }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, false }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "footway"}, kSpeedPedestrianKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // Slovakia VehicleModel::InitListT const g_bicycleLimitsSlovakia = g_bicycleLimitsNoTrunk; // Spain VehicleModel::InitListT const g_bicycleLimitsSpain = g_bicycleLimitsPedestrianAllowed; // Switzerland VehicleModel::InitListT const g_bicycleLimitsSwitzerland = g_bicycleLimitsNoTrunk; // Turkey VehicleModel::InitListT const g_bicycleLimitsTurkey = g_bicycleLimitsDefault; // Ukraine VehicleModel::InitListT const g_bicycleLimitsUkraine = { // No trunk // Footway and perestrian are allowed // No transit for living_street and service { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, false }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, false }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "footway"}, kSpeedFootwayKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; // United Kingdom VehicleModel::InitListT const g_bicycleLimitsUK = g_bicycleLimitsBridlewayAllowed; // United States of America VehicleModel::InitListT const g_bicycleLimitsUS = { // Bridleway and pedesprian are allowed { {"highway", "trunk"}, kSpeedTrunkKMpH, true }, { {"highway", "trunk_link"}, kSpeedTrunkLinkKMpH, true }, { {"highway", "primary"}, kSpeedPrimaryKMpH, true }, { {"highway", "primary_link"}, kSpeedPrimaryLinkKMpH, true }, { {"highway", "secondary"}, kSpeedSecondaryKMpH, true }, { {"highway", "secondary_link"}, kSpeedSecondaryLinkKMpH, true }, { {"highway", "tertiary"}, kSpeedTertiaryKMpH, true }, { {"highway", "tertiary_link"}, kSpeedTertiaryLinkKMpH, true }, { {"highway", "service"}, kSpeedServiceKMpH, true }, { {"highway", "unclassified"}, kSpeedUnclassifiedKMpH, true }, { {"highway", "road"}, kSpeedRoadKMpH, true }, { {"highway", "track"}, kSpeedTrackKMpH, true }, { {"highway", "path"}, kSpeedPathKMpH, true }, { {"highway", "bridleway"}, kSpeedBridlewayKMpH, true }, { {"highway", "cycleway"}, kSpeedCyclewayKMpH, true }, { {"highway", "residential"}, kSpeedResidentialKMpH, true }, { {"highway", "living_street"}, kSpeedLivingStreetKMpH, true }, { {"highway", "steps"}, kSpeedStepsKMpH, true }, { {"highway", "pedestrian"}, kSpeedPedestrianKMpH, true }, { {"highway", "platform"}, kSpeedPlatformKMpH, true }, }; } // namespace namespace routing { BicycleModel::BicycleModel() : VehicleModel(classif(), g_bicycleLimitsDefault) { Init(); } BicycleModel::BicycleModel(VehicleModel::InitListT const & speedLimits) : VehicleModel(classif(), speedLimits) { Init(); } void BicycleModel::Init() { initializer_list<char const *> hwtagYesBicycle = {"hwtag", "yesbicycle"}; m_yesBicycleType = classif().GetTypeByPath(hwtagYesBicycle); m_noBicycleType = classif().GetTypeByPath({"hwtag", "nobicycle"}); m_bidirBicycleType = classif().GetTypeByPath({"hwtag", "bidir_bicycle"}); vector<AdditionalRoadTags> const additionalTags = { {hwtagYesBicycle, m_maxSpeedKMpH}, {{"route", "ferry"}, m_maxSpeedKMpH}, {{"man_made", "pier"}, kSpeedPierKMpH}, }; SetAdditionalRoadTypes(classif(), additionalTags); } VehicleModelInterface::RoadAvailability BicycleModel::GetRoadAvailability(feature::TypesHolder const & types) const { if (types.Has(m_yesBicycleType)) return RoadAvailability::Available; if (types.Has(m_noBicycleType)) return RoadAvailability::NotAvailable; return RoadAvailability::Unknown; } bool BicycleModel::IsBicycleBidir(feature::TypesHolder const & types) const { return types.Has(m_bidirBicycleType); } bool BicycleModel::IsOneWay(FeatureType const & f) const { feature::TypesHolder const types(f); if (IsBicycleBidir(types)) return false; return VehicleModel::IsOneWay(f); } // If one of feature types will be disabled for bicycles, features of this type will be simplyfied // in generator. Look FeatureBuilder1::IsRoad() for more details. // static BicycleModel const & BicycleModel::AllLimitsInstance() { static BicycleModel const instance(g_bicycleLimitsAll); return instance; } BicycleModelFactory::BicycleModelFactory( CountryParentNameGetterFn const & countryParentNameGetterFn) : VehicleModelFactory(countryParentNameGetterFn) { // Names must be the same with country names from countries.txt m_models[""] = make_shared<BicycleModel>(g_bicycleLimitsDefault); m_models["Australia"] = make_shared<BicycleModel>(g_bicycleLimitsAustralia); m_models["Austria"] = make_shared<BicycleModel>(g_bicycleLimitsAustria); m_models["Belarus"] = make_shared<BicycleModel>(g_bicycleLimitsBelarus); m_models["Belgium"] = make_shared<BicycleModel>(g_bicycleLimitsBelgium); m_models["Brazil"] = make_shared<BicycleModel>(g_bicycleLimitsBrazil); m_models["Denmark"] = make_shared<BicycleModel>(g_bicycleLimitsDenmark); m_models["France"] = make_shared<BicycleModel>(g_bicycleLimitsFrance); m_models["Finland"] = make_shared<BicycleModel>(g_bicycleLimitsFinland); m_models["Germany"] = make_shared<BicycleModel>(g_bicycleLimitsGermany); m_models["Hungary"] = make_shared<BicycleModel>(g_bicycleLimitsHungary); m_models["Iceland"] = make_shared<BicycleModel>(g_bicycleLimitsIceland); m_models["Netherlands"] = make_shared<BicycleModel>(g_bicycleLimitsNetherlands); m_models["Norway"] = make_shared<BicycleModel>(g_bicycleLimitsNorway); m_models["Oman"] = make_shared<BicycleModel>(g_bicycleLimitsOman); m_models["Poland"] = make_shared<BicycleModel>(g_bicycleLimitsPoland); m_models["Romania"] = make_shared<BicycleModel>(g_bicycleLimitsRomania); m_models["Russian Federation"] = make_shared<BicycleModel>(g_bicycleLimitsRussia); m_models["Slovakia"] = make_shared<BicycleModel>(g_bicycleLimitsSlovakia); m_models["Spain"] = make_shared<BicycleModel>(g_bicycleLimitsSpain); m_models["Switzerland"] = make_shared<BicycleModel>(g_bicycleLimitsSwitzerland); m_models["Turkey"] = make_shared<BicycleModel>(g_bicycleLimitsTurkey); m_models["Ukraine"] = make_shared<BicycleModel>(g_bicycleLimitsUkraine); m_models["United Kingdom"] = make_shared<BicycleModel>(g_bicycleLimitsUK); m_models["United States of America"] = make_shared<BicycleModel>(g_bicycleLimitsUS); } } // routing
49.449416
122
0.642562
[ "vector", "model" ]
dc9d248bf3dddfdc0493c6efebbd9d37fe8b45c3
16,823
hpp
C++
third_party/rapidyaml/rapidyaml/ext/c4core/src/c4/memory_resource.hpp
rbauduin/jsonnet
da1490f6130062f5f4690dfcfeed6ce0c293fd2f
[ "Apache-2.0" ]
1
2019-07-21T12:53:12.000Z
2019-07-21T12:53:12.000Z
third_party/rapidyaml/rapidyaml/ext/c4core/src/c4/memory_resource.hpp
rbauduin/jsonnet
da1490f6130062f5f4690dfcfeed6ce0c293fd2f
[ "Apache-2.0" ]
null
null
null
third_party/rapidyaml/rapidyaml/ext/c4core/src/c4/memory_resource.hpp
rbauduin/jsonnet
da1490f6130062f5f4690dfcfeed6ce0c293fd2f
[ "Apache-2.0" ]
1
2022-03-13T14:04:37.000Z
2022-03-13T14:04:37.000Z
#ifndef _C4_MEMORY_RESOURCE_HPP_ #define _C4_MEMORY_RESOURCE_HPP_ /** @file memory_resource.hpp Provides facilities to allocate typeless * memory, via the memory resource model consecrated with C++17. */ /** @defgroup memory memory utilities */ /** @defgroup raw_memory_alloc Raw memory allocation * @ingroup memory */ /** @defgroup memory_resources Memory resources * @ingroup memory */ #include "c4/config.hpp" #include "c4/error.hpp" namespace c4 { // need these forward decls here struct MemoryResource; struct MemoryResourceMalloc; struct MemoryResourceStack; MemoryResourceMalloc* get_memory_resource_malloc(); MemoryResourceStack* get_memory_resource_stack(); namespace detail { MemoryResource*& get_memory_resource(); } // c-style allocation --------------------------------------------------------- // this API provides aligned allocation functions. // These functions forward the call to a user-modifiable function. // aligned allocation. /** Aligned allocation. Merely calls the current get_aalloc() function. * @see get_aalloc() * @ingroup raw_memory_alloc */ void* aalloc(size_t sz, size_t alignment); /** Aligned free. Merely calls the current get_afree() function. * @see get_afree() * @ingroup raw_memory_alloc */ void afree(void* ptr); /** Aligned reallocation. Merely calls the current get_arealloc() function. * @see get_arealloc() * @ingroup raw_memory_alloc */ void* arealloc(void* ptr, size_t oldsz, size_t newsz, size_t alignment); // allocation setup facilities. /** Function pointer type for aligned allocation * @see set_aalloc() * @ingroup raw_memory_alloc */ using aalloc_pfn = void* (*)(size_t size, size_t alignment); /** Function pointer type for aligned deallocation * @see set_afree() * @ingroup raw_memory_alloc */ using afree_pfn = void (*)(void *ptr); /** Function pointer type for aligned reallocation * @see set_arealloc() * @ingroup raw_memory_alloc */ using arealloc_pfn = void* (*)(void *ptr, size_t oldsz, size_t newsz, size_t alignment); // allocation function pointer setters/getters /** Set the global aligned allocation function. * @see aalloc() * @see get_aalloc() * @ingroup raw_memory_alloc */ void set_aalloc (aalloc_pfn fn); /** Set the global aligned deallocation function. * @see afree() * @see get_afree() * @ingroup raw_memory_alloc */ void set_afree (afree_pfn fn); /** Set the global aligned reallocation function. * @see arealloc() * @see get_arealloc() * @ingroup raw_memory_alloc */ void set_arealloc(arealloc_pfn fn); /** Get the global aligned reallocation function. * @see arealloc() * @ingroup raw_memory_alloc */ aalloc_pfn get_aalloc(); /** Get the global aligned deallocation function. * @see afree() * @ingroup raw_memory_alloc */ afree_pfn get_afree(); /** Get the global aligned reallocation function. * @see arealloc() * @ingroup raw_memory_alloc */ arealloc_pfn get_arealloc(); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // c++-style allocation ------------------------------------------------------- /** C++17-style memory_resource base class. See http://en.cppreference.com/w/cpp/experimental/memory_resource * @ingroup memory_resources */ struct MemoryResource { const char *name = nullptr; virtual ~MemoryResource() {} void* allocate(size_t sz, size_t alignment=alignof(max_align_t), void *hint=nullptr) { void *mem = this->do_allocate(sz, alignment, hint); C4_CHECK_MSG(mem != nullptr, "could not allocate %lu bytes", sz); return mem; } void* reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment=alignof(max_align_t)) { void *mem = this->do_reallocate(ptr, oldsz, newsz, alignment); C4_CHECK_MSG(mem != nullptr, "could not reallocate from %lu to %lu bytes", oldsz, newsz); return mem; } void deallocate(void* ptr, size_t sz, size_t alignment = alignof(max_align_t)) { this->do_deallocate(ptr, sz, alignment); } protected: virtual void* do_allocate(size_t sz, size_t alignment, void* hint) = 0; virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) = 0; virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) = 0; }; /** get the current global memory resource. To avoid static initialization * order problems, this is implemented using a function call to ensure * that it is available when first used. * @ingroup memory_resources */ C4_ALWAYS_INLINE MemoryResource* get_memory_resource() { return detail::get_memory_resource(); } /** set the global memory resource * @ingroup memory_resources */ C4_ALWAYS_INLINE void set_memory_resource(MemoryResource* mr) { C4_ASSERT(mr != nullptr); detail::get_memory_resource() = mr; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** A c4::aalloc-based memory resource. Thread-safe if the implementation * called by c4::aalloc() is safe. * @ingroup memory_resources */ struct MemoryResourceMalloc : public MemoryResource { MemoryResourceMalloc() { name = "malloc"; } virtual ~MemoryResourceMalloc() override {} protected: virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override { C4_UNUSED(hint); return c4::aalloc(sz, alignment); } virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override { C4_UNUSED(sz); C4_UNUSED(alignment); c4::afree(ptr); } virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override { return c4::arealloc(ptr, oldsz, newsz, alignment); } }; /** returns a malloc-based memory resource * @ingroup memory_resources */ C4_ALWAYS_INLINE MemoryResourceMalloc* get_memory_resource_malloc() { static MemoryResourceMalloc mr; return &mr; } namespace detail { C4_ALWAYS_INLINE MemoryResource* & get_memory_resource() { thread_local static MemoryResource* mr = get_memory_resource_malloc(); return mr; } } // namespace detail //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- namespace detail { /** Allows a memory resource to obtain its memory from another memory resource. * @ingroup memory_resources */ struct DerivedMemoryResource : public MemoryResource { public: DerivedMemoryResource(MemoryResource *mr_=nullptr) : m_local(mr_ ? mr_ : get_memory_resource()) {} private: MemoryResource *m_local; protected: virtual void* do_allocate(size_t sz, size_t alignment, void* hint) override { return m_local->allocate(sz, alignment, hint); } virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override { return m_local->reallocate(ptr, oldsz, newsz, alignment); } virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override { return m_local->deallocate(ptr, sz, alignment); } }; /** Provides common facilities for memory resource consisting of a single memory block * @ingroup memory_resources */ struct _MemoryResourceSingleChunk : public DerivedMemoryResource { C4_NO_COPY_OR_MOVE(_MemoryResourceSingleChunk); using impl_type = DerivedMemoryResource; public: _MemoryResourceSingleChunk(MemoryResource *impl=nullptr) : DerivedMemoryResource(impl) { name = "linear_malloc"; } /** initialize with owned memory, allocated from the given (or the global) memory resource */ _MemoryResourceSingleChunk(size_t sz, MemoryResource *impl=nullptr) : _MemoryResourceSingleChunk(impl) { acquire(sz); } /** initialize with borrowed memory */ _MemoryResourceSingleChunk(void *mem, size_t sz) : _MemoryResourceSingleChunk() { acquire(mem, sz); } virtual ~_MemoryResourceSingleChunk() override { release(); } public: void const* mem() const { return m_mem; } size_t capacity() const { return m_size; } size_t size() const { return m_pos; } size_t slack() const { C4_ASSERT(m_size >= m_pos); return m_size - m_pos; } public: char *m_mem{nullptr}; size_t m_size{0}; size_t m_pos{0}; bool m_owner; public: /** set the internal pointer to the beginning of the linear buffer */ void clear() { m_pos = 0; } /** initialize with owned memory, allocated from the global memory resource */ void acquire(size_t sz); /** initialize with borrowed memory */ void acquire(void *mem, size_t sz); /** release the memory */ void release(); }; } // namespace detail //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** provides a linear memory resource. Allocates incrementally from a linear * buffer, without ever deallocating. Deallocations are a no-op, and the * memory is freed only when the resource is release()d. The memory used by * this object can be either owned or borrowed. When borrowed, no calls to * malloc/free take place. * * @ingroup memory_resources */ struct MemoryResourceLinear : public detail::_MemoryResourceSingleChunk { C4_NO_COPY_OR_MOVE(MemoryResourceLinear); public: using detail::_MemoryResourceSingleChunk::_MemoryResourceSingleChunk; protected: virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override; virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override; virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** provides a stack-type malloc-based memory resource. * @ingroup memory_resources */ struct MemoryResourceStack : public detail::_MemoryResourceSingleChunk { C4_NO_COPY_OR_MOVE(MemoryResourceStack); public: using detail::_MemoryResourceSingleChunk::_MemoryResourceSingleChunk; protected: virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override; virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override; virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** provides a linear array-based memory resource. * @see MemoryResourceLinear * @ingroup memory_resources */ template<size_t N> struct MemoryResourceLinearArr : public MemoryResourceLinear { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4324) // structure was padded due to alignment specifier #endif alignas(alignof(max_align_t)) char m_arr[N]; #ifdef _MSC_VER #pragma warning(pop) #endif MemoryResourceLinearArr() : MemoryResourceLinear(m_arr, N) { name = "linear_arr"; } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- struct AllocationCounts { struct Item { ssize_t allocs; ssize_t size; void add(size_t sz) { ++allocs; size += static_cast<ssize_t>(sz); } void rem(size_t sz) { --allocs; size -= static_cast<ssize_t>(sz); } Item max(Item const& that) const { Item r(*this); r.allocs = r.allocs > that.allocs ? r.allocs : that.allocs; r.size = r.size > that.size ? r.size : that.size; return r; } }; Item curr = {0, 0}; Item total = {0, 0}; Item max = {0, 0}; void clear_counts() { curr = {0, 0}; total = {0, 0}; max = {0, 0}; } void update(AllocationCounts const& that) { curr.allocs += that.curr.allocs; curr.size += that.curr.size; total.allocs += that.total.allocs; total.size += that.total.size; max.allocs += that.max.allocs; max.size += that.max.size; } void add_counts(void* ptr, size_t sz) { if(ptr == nullptr) return; curr.add(sz); total.add(sz); max = max.max(curr); } void rem_counts(void *ptr, size_t sz) { if(ptr == nullptr) return; curr.rem(sz); } AllocationCounts operator- (AllocationCounts const& that) const { AllocationCounts r(*this); r.curr.allocs -= that.curr.allocs; r.curr.size -= that.curr.size; r.total.allocs -= that.total.allocs; r.total.size -= that.total.size; r.max.allocs -= that.max.allocs; r.max.size -= that.max.size; return r; } AllocationCounts operator+ (AllocationCounts const& that) const { AllocationCounts r(*this); r.curr.allocs += that.curr.allocs; r.curr.size += that.curr.size; r.total.allocs += that.total.allocs; r.total.size += that.total.size; r.max.allocs += that.max.allocs; r.max.size += that.max.size; return r; } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** a MemoryResource which latches onto another MemoryResource * and counts allocations and sizes. * @ingroup memory_resources */ class MemoryResourceCounts : public MemoryResource { public: MemoryResourceCounts() : m_resource(get_memory_resource()) { C4_ASSERT(m_resource != this); name = "MemoryResourceCounts"; } MemoryResourceCounts(MemoryResource *res) : m_resource(res) { C4_ASSERT(m_resource != this); name = "MemoryResourceCounts"; } MemoryResource *resource() { return m_resource; } AllocationCounts const& counts() const { return m_counts; } protected: MemoryResource *m_resource; AllocationCounts m_counts; protected: virtual void* do_allocate(size_t sz, size_t alignment, void * /*hint*/) override { void *ptr = m_resource->allocate(sz, alignment); m_counts.add_counts(ptr, sz); return ptr; } virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override { m_counts.rem_counts(ptr, sz); m_resource->deallocate(ptr, sz, alignment); } virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override { m_counts.rem_counts(ptr, oldsz); void* nptr = m_resource->reallocate(ptr, oldsz, newsz, alignment); m_counts.add_counts(nptr, newsz); return nptr; } }; //----------------------------------------------------------------------------- /** RAII class which binds a memory resource with a scope duration. * @ingroup memory_resources */ struct ScopedMemoryResource { MemoryResource *m_original; ScopedMemoryResource(MemoryResource *r) : m_original(get_memory_resource()) { set_memory_resource(r); } ~ScopedMemoryResource() { set_memory_resource(m_original); } }; //----------------------------------------------------------------------------- /** RAII class which counts allocations and frees inside a scope. Can * optionally set also the memory resource to be used. * @ingroup memory_resources */ struct ScopedMemoryResourceCounts { MemoryResourceCounts mr; ScopedMemoryResourceCounts() : mr() { set_memory_resource(&mr); } ScopedMemoryResourceCounts(MemoryResource *m) : mr(m) { set_memory_resource(&mr); } ~ScopedMemoryResourceCounts() { set_memory_resource(mr.resource()); } }; } // namespace c4 #endif /* _C4_MEMORY_RESOURCE_HPP_ */
29.775221
123
0.594424
[ "object", "model" ]
dc9eea460cef72865de63b2ea049aff69ba69e19
19,156
cpp
C++
src/chrono/fea/ChElementBeamTaperedTimoshenkoFPM.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
1,383
2015-02-04T14:17:40.000Z
2022-03-30T04:58:16.000Z
src/chrono/fea/ChElementBeamTaperedTimoshenkoFPM.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
245
2015-01-11T15:30:51.000Z
2022-03-30T21:28:54.000Z
src/chrono/fea/ChElementBeamTaperedTimoshenkoFPM.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
351
2015-02-04T14:17:47.000Z
2022-03-30T04:42:52.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= //#define BEAM_VERBOSE #include "chrono/core/ChQuadrature.h" #include "chrono/fea/ChElementBeamTaperedTimoshenkoFPM.h" namespace chrono { namespace fea { ChElementBeamTaperedTimoshenkoFPM::ChElementBeamTaperedTimoshenkoFPM() : guass_order(4) { q_refrotA = QUNIT; q_refrotB = QUNIT; q_element_abs_rot = QUNIT; q_element_ref_rot = QUNIT; force_symmetric_stiffness = false; disable_corotate = false; use_geometric_stiffness = true; use_Rc = true; use_Rs = true; nodes.resize(2); Km.setZero(this->GetNdofs(), this->GetNdofs()); Kg.setZero(this->GetNdofs(), this->GetNdofs()); M.setZero(this->GetNdofs(), this->GetNdofs()); Rm.setZero(this->GetNdofs(), this->GetNdofs()); Ri.setZero(this->GetNdofs(), this->GetNdofs()); Ki.setZero(this->GetNdofs(), this->GetNdofs()); T.setZero(this->GetNdofs(), this->GetNdofs()); Rs.setIdentity(6, 6); Rc.setIdentity(6, 6); } void ChElementBeamTaperedTimoshenkoFPM::ShapeFunctionsTimoshenkoFPM(ShapeFunctionGroupFPM& NB, double eta) { // The shape functions have referenced two papers below, especially the first one: // Alexander R.Stäblein,and Morten H.Hansen. // "Timoshenko beam element with anisotropic cross-sectional properties." // ECCOMAS Congress 2016, VII European Congress on Computational Methods in Applied Sciences and Engineering. // Crete Island, Greece, 5 - 10 June 2016 // // Taeseong Kim, Anders M.Hansen,and Kim Branner. // "Development of an anisotropic beam finite element for composite wind turbine blades in multibody system." // Renewable Energy 59(2013) : 172 - 183. // eta = 2 * x/L; // x = (-L/2, L/2), hence eta = (-1, 1) double L = this->length; double LL = L * L; double LLL = LL * L; double eta1 = (eta + 1) / 2.0; double eta2 = eta1 * eta1; double eta3 = eta2 * eta1; ChMatrixNM<double, 6, 14> Ax; Ax.setZero(); ChMatrixNM<double, 6, 14> dAx; dAx.setZero(); ChMatrixNM<double, 14, 14> Ex; Ex.setZero(); ChMatrixNM<double, 14, 14> Ex_inv; Ex_inv.setZero(); ChMatrixNM<double, 6, 12> Nx; Nx.setZero(); ChMatrixNM<double, 6, 12> dNx; dNx.setZero(); // The coefficient matrix of the displacements and rotations with respect to the shape function coefficient vector // c_v note: the shape function coefficient vector is as below: c_v = [c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c13 c14 c11 // c12].'; // notice the order of c11 c12 c13 c14 Ax.row(0) << L * eta1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; Ax.row(1) << 0, 0, LLL * eta3, LL * eta2, L * eta1, 1, 0, 0, 0, 0, 0, 0, 0, 0; Ax.row(2) << 0, 0, 0, 0, 0, 0, LLL * eta3, LL * eta2, L * eta1, 1, 0, 0, 0, 0; Ax.row(3) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L * eta1, 1; Ax.row(4) << 0, 0, 0, 0, 0, 0, -3 * LL * eta2, -2 * L * eta1, -1, 0, 1, 0, 0, 0; Ax.row(5) << 0, 0, 3 * LL * eta2, 2 * L * eta1, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0; // The derivative of Ax dAx.row(0) << 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; dAx.row(1) << 0, 0, 3 * LL * eta2, 2 * L * eta1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0; dAx.row(2) << 0, 0, 0, 0, 0, 0, 3 * LL * eta2, 2 * L * eta1, 1, 0, 0, 0, 0, 0; dAx.row(3) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0; dAx.row(4) << 0, 0, 0, 0, 0, 0, -6 * L * eta1, -2, 0, 0, 0, 0, 0, 0; dAx.row(5) << 0, 0, 6 * L * eta1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; // A temporary transformation matrix ChMatrixNM<double, 14, 12> Ttemp; Ttemp.setZero(); Ttemp.block<12, 12>(2, 0).setIdentity(); // the cross-sectional material stiffness matrix Klaw along beam element may be variant // due to different Klaw at two ends of tapered-sectional beam ChMatrixNM<double, 6, 6> Klaw_point = this->tapered_section_fpm->GetKlawAtPoint(eta); // double k11 = Klaw_point(0, 0); double k12 = Klaw_point(0, 1); double k13 = Klaw_point(0, 2); // double k14 = Klaw_point(0, 3); // double k15 = Klaw_point(0, 4); // double k16 = Klaw_point(0, 5); double k22 = Klaw_point(1, 1); double k23 = Klaw_point(1, 2); double k24 = Klaw_point(1, 3); double k25 = Klaw_point(1, 4); double k26 = Klaw_point(1, 5); double k33 = Klaw_point(2, 2); double k34 = Klaw_point(2, 3); double k35 = Klaw_point(2, 4); double k36 = Klaw_point(2, 5); // double k44 = Klaw_point(3, 3); // double k45 = Klaw_point(3, 4); // double k46 = Klaw_point(3, 5); double k55 = Klaw_point(4, 4); double k56 = Klaw_point(4, 5); double k66 = Klaw_point(5, 5); // The coefficient matrix of the equilibrium and compatibility equations // with respect to the shape function coefficient vector c_v Ex.row(0) << -k13, 0, 6 * k56 - 3 * L * k36 - 3 * L * eta * k36, -2 * k36, 0, 0, 3 * L * k35 - 6 * k55 + 3 * L * eta * k35, 2 * k35, 0, 0, -k33, -k23, -k34, 0; Ex.row(1) << k12, 0, 6 * k66 + 3 * L * k26 + 3 * L * eta * k26, 2 * k26, 0, 0, -6 * k56 - 3 * L * k25 - 3 * L * eta * k25, -2 * k25, 0, 0, k23, k22, k24, 0; Ex.row(2) << 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; Ex.row(3) << 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0; Ex.row(4) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0; Ex.row(5) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1; Ex.row(6) << 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0; Ex.row(7) << 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0; Ex.row(8) << L, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; Ex.row(9) << 0, 0, LLL, LL, L, 1, 0, 0, 0, 0, 0, 0, 0, 0; Ex.row(10) << 0, 0, 0, 0, 0, 0, LLL, LL, L, 1, 0, 0, 0, 0; Ex.row(11) << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L, 1; Ex.row(12) << 0, 0, 0, 0, 0, 0, -3 * LL, -2 * L, -1, 0, 1, 0, 0, 0; Ex.row(13) << 0, 0, 3 * LL, 2 * L, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0; // The inverse of Ex Ex_inv = Ex.inverse(); // The shape function matrix at dimensionless position eta Nx = Ax * Ex_inv * Ttemp; // and its derivative dNx = dAx * Ex_inv * Ttemp; // DO NOT add Ax * dEx_inv * Ttemp, see the first paper please. // A temporary matrix ChMatrixNM<double, 6, 6> TNtemp; TNtemp.setZero(); TNtemp(1, 5) = -1.0; TNtemp(2, 4) = 1.0; // The strain displacement matrix at dimensionless position eta ChMatrixNM<double, 6, 12> Bx = dNx + TNtemp * Nx; // return result NB = std::make_tuple(Nx, Bx); } /// This class defines the calculations for the Guass integrand of /// the cross-sectional stiffness/damping/mass matrices class BeamTaperedTimoshenkoFPM : public ChIntegrable1D<ChMatrixNM<double, 12, 12>> { public: BeamTaperedTimoshenkoFPM(ChElementBeamTaperedTimoshenkoFPM* element, const int option) : m_element(element), m_choice_KiRiMi(option) {} ~BeamTaperedTimoshenkoFPM() {} // Which one matrix is evaluated? stiffness/damping/mass matrices // - 0: stiffness matrix // - 1: damping matrix // - 2: mass matix void SetChoiceKiRiMi(int mv) { m_choice_KiRiMi = mv; } int GetChoiceKiRiMi() { return m_choice_KiRiMi; } private: ChElementBeamTaperedTimoshenkoFPM* m_element; // 0: stiffness matrix // 1: damping matrix // 2: mass matix int m_choice_KiRiMi = 0; virtual void Evaluate(ChMatrixNM<double, 12, 12>& result, const double x) override; }; void BeamTaperedTimoshenkoFPM::Evaluate(ChMatrixNM<double, 12, 12>& result, const double x) { double eta = x; ChElementBeamTaperedTimoshenkoFPM::ShapeFunctionGroupFPM NxBx; m_element->ShapeFunctionsTimoshenkoFPM(NxBx, eta); // shape function matrix ChMatrixNM<double, 6, 12> Nx = std::get<0>(NxBx); // strain-displacement relation matrix ChMatrixNM<double, 6, 12> Bx = std::get<1>(NxBx); auto tapered_section_fpm = m_element->GetTaperedSection(); ChMatrixNM<double, 6, 6> Klaw_point; ChMatrixNM<double, 6, 6> Rlaw_point; ChMatrixNM<double, 6, 6> Mlaw_point; switch (m_choice_KiRiMi) { case 0: Klaw_point = tapered_section_fpm->GetKlawAtPoint(eta); result = Bx.transpose() * Klaw_point * Bx; break; case 1: Rlaw_point = tapered_section_fpm->GetRlawAtPoint(eta); result = Bx.transpose() * Rlaw_point * Bx; // modified Rayleigh damping model break; case 2: Mlaw_point = tapered_section_fpm->GetMlawAtPoint(eta); result = Nx.transpose() * Mlaw_point * Nx; break; default: std::cout << "Please input the correct option: 0,1,2" << std::endl; return; } }; void ChElementBeamTaperedTimoshenkoFPM::ComputeStiffnessMatrix() { // Calculate the local element stiffness matrix via Guass integration this->Km.setZero(); BeamTaperedTimoshenkoFPM myformula(this, 0); // 0: stiffness matrix ChMatrixNM<double, 12, 12> TempStiffnessMatrix; TempStiffnessMatrix.setZero(); ChQuadrature::Integrate1D<ChMatrixNM<double, 12, 12>>(TempStiffnessMatrix, // result of integration will go there myformula, // formula to integrate -1, 1, // x limits guass_order // order of integration ); // eta = 2*x/L; // ---> Deta/dx = 2./L; // ---> detJ = dx/Deta = L/2.; TempStiffnessMatrix *= this->length / 2.0; // need to multiple detJ this->Km = this->T.transpose() * TempStiffnessMatrix * this->T; } void ChElementBeamTaperedTimoshenkoFPM::ComputeDampingMatrix() { // Calculate the local element damping matrix via Guass integration this->Rm.setZero(); BeamTaperedTimoshenkoFPM myformula(this, 1); // 1: damping matrix ChMatrixNM<double, 12, 12> TempDampingMatrix; TempDampingMatrix.setZero(); ChQuadrature::Integrate1D<ChMatrixNM<double, 12, 12>>(TempDampingMatrix, // result of integration will go there myformula, // formula to integrate -1, 1, // x limits guass_order // order of integration ); // eta = 2*x/L; // ---> Deta/dx = 2./L; // ---> detJ = dx/Deta = L/2.; TempDampingMatrix *= this->length / 2.0; // need to multiple detJ this->Rm = this->T.transpose() * TempDampingMatrix * this->T; // The mass-proportional term double rdamping_alpha = this->tapered_section->GetAverageSectionParameters()->rdamping_coeff.alpha; if (this->tapered_section->GetLumpedMassMatrixType()) { double node_multiplier_fact = 0.5 * this->length; Rm += rdamping_alpha * this->M * node_multiplier_fact; } else { Rm += rdamping_alpha * this->M; } } void ChElementBeamTaperedTimoshenkoFPM::ComputeConsistentMassMatrix() { // Calculate the local element mass matrix via Guass integration this->M.setZero(); BeamTaperedTimoshenkoFPM myformula(this, 2); // 2: mass matrix ChMatrixNM<double, 12, 12> TempMassMatrix; TempMassMatrix.setZero(); ChQuadrature::Integrate1D<ChMatrixNM<double, 12, 12>>(TempMassMatrix, // result of integration will go there myformula, // formula to integrate -1, 1, // x limits guass_order // order of integration ); // eta = 2*x/L; // ---> Deta/dx = 2./L; // ---> detJ = dx/Deta = L/2.; TempMassMatrix *= this->length / 2.0; // need to multiple detJ this->M = TempMassMatrix; // If the cross-sectional mass properties are given at the mass center, // then it should be transformed to the centerline firstly, // this is handled in the Class ChBeamSectionTimoshenkoAdvancedGenericFPM. NOT HERE. } void ChElementBeamTaperedTimoshenkoFPM::ComputeMassMatrix() { // Compute local mass matrix of element // It could be lumped or consistent mass matrix, depends on SetLumpedMassMatrix(true/false) if (this->tapered_section_fpm->GetLumpedMassMatrixType()) { // If it is lumped mass matrix, you need to multiple 0.5 * length to obtain the final mass matrix // For consistent mass matrix, don't need to multiple anything. this->tapered_section_fpm->ComputeInertiaMatrix(this->M); } else { // If the consistent mass matrix is used, you need to compute the ave_sec_par firstly. this->tapered_section_fpm->ComputeAverageSectionParameters(); ComputeConsistentMassMatrix(); } } void ChElementBeamTaperedTimoshenkoFPM::SetupInitial(ChSystem* system) { assert(tapered_section_fpm); // Compute rest length, mass: this->length = (nodes[1]->GetX0().GetPos() - nodes[0]->GetX0().GetPos()).Length(); this->mass = 0.5 * this->length * this->tapered_section_fpm->GetSectionA()->GetMassPerUnitLength() + 0.5 * this->length * this->tapered_section_fpm->GetSectionB()->GetMassPerUnitLength(); // Compute initial rotation ChMatrix33<> A0; ChVector<> mXele = nodes[1]->GetX0().GetPos() - nodes[0]->GetX0().GetPos(); ChVector<> myele = nodes[0]->GetX0().GetA().Get_A_Yaxis(); A0.Set_A_Xdir(mXele, myele); q_element_ref_rot = A0.Get_A_quaternion(); // Compute transformation matrix ComputeTransformMatrix(); // Compute local mass matrix: ComputeMassMatrix(); // Compute local stiffness matrix: ComputeStiffnessMatrix(); // Compute local geometric stiffness matrix normalized by pull force P: Kg/P ComputeGeometricStiffnessMatrix(); // Compute local damping matrix: ComputeDampingMatrix(); } void ChElementBeamTaperedTimoshenkoFPM::EvaluateSectionDisplacement(const double eta, ChVector<>& u_displ, ChVector<>& u_rotaz) { ChVectorDynamic<> displ(this->GetNdofs()); this->GetStateBlock(displ); // No transformation for the displacement of two nodes, // so the section displacement is evaluated at the centerline of beam ShapeFunctionGroupFPM NxBx; ShapeFunctionsTimoshenkoFPM(NxBx, eta); // the shape function matrix ChMatrixNM<double, 6, 12> Nx = std::get<0>(NxBx); // the displacements and rotations, as a vector ChVectorDynamic<> u_vector = Nx * displ; u_displ.x() = u_vector(0); u_displ.y() = u_vector(1); u_displ.z() = u_vector(2); u_rotaz.x() = u_vector(3); u_rotaz.y() = u_vector(4); u_rotaz.z() = u_vector(5); } void ChElementBeamTaperedTimoshenkoFPM::EvaluateSectionForceTorque(const double eta, ChVector<>& Fforce, ChVector<>& Mtorque) { assert(tapered_section_fpm); ChVectorDynamic<> displ(this->GetNdofs()); this->GetStateBlock(displ); // transform the displacement of two nodes to elastic axis ChVectorDynamic<> displ_ec = this->T * displ; ShapeFunctionGroupFPM NxBx; ShapeFunctionsTimoshenkoFPM(NxBx, eta); // the strain displacement matrix B: ChMatrixNM<double, 6, 12> Bx = std::get<1>(NxBx); // generalized strains/curvatures; ChVectorN<double, 6> sect_ek = Bx * displ_ec; // 6*6 fully populated constitutive matrix of the beam: ChMatrixNM<double, 6, 6> Klaw_d = this->tapered_section_fpm->GetKlawAtPoint(eta); ChMatrixDynamic<> Teta; ComputeTransformMatrixAtPoint(Teta, eta); // ..unrolled rotated constitutive matrix.. ChMatrixNM<double, 6, 6> Klaw_r; Klaw_r.setZero(); Klaw_r = Teta.transpose() * Klaw_d; // .. compute wrench = Klaw_r * sect_ek ChVectorN<double, 6> wrench = Klaw_r * sect_ek; Fforce = wrench.segment(0, 3); Mtorque = wrench.segment(3, 3); } void ChElementBeamTaperedTimoshenkoFPM::EvaluateSectionStrain(const double eta, ChVector<>& StrainV_trans, ChVector<>& StrainV_rot) { assert(tapered_section_fpm); ChVectorDynamic<> displ(this->GetNdofs()); this->GetStateBlock(displ); // transform the displacement of two nodes to elastic axis ChVectorDynamic<> displ_ec = this->T * displ; ShapeFunctionGroupFPM NxBx; ShapeFunctionsTimoshenkoFPM(NxBx, eta); // the strain displacement matrix B: ChMatrixNM<double, 6, 12> Bx = std::get<1>(NxBx); // generalized strains/curvatures; ChVectorN<double, 6> sect_ek = Bx * displ_ec; StrainV_trans = sect_ek.segment(0, 3); StrainV_rot = sect_ek.segment(3, 3); } void ChElementBeamTaperedTimoshenkoFPM::ComputeNF(const double U, ChVectorDynamic<>& Qi, double& detJ, const ChVectorDynamic<>& F, ChVectorDynamic<>* state_x, ChVectorDynamic<>* state_w) { ShapeFunctionGroupFPM NxBx; // the shape function matrix ChMatrixNM<double, 6, 12> Nx; double eta = -1; ShapeFunctionsTimoshenkoFPM(NxBx, eta); Nx = std::get<0>(NxBx); Qi.head(6) = Nx.transpose() * F; eta = 1; ShapeFunctionsTimoshenkoFPM(NxBx, eta); Nx = std::get<0>(NxBx); Qi.tail(6) = Nx.transpose() * F; // eta = 2*x/L; // ---> Deta/dx = 2./L; // ---> detJ = dx/Deta = L/2.; detJ = this->GetRestLength() / 2.0; } void ChElementBeamTaperedTimoshenkoFPM::ComputeNF(const double U, const double V, const double W, ChVectorDynamic<>& Qi, double& detJ, const ChVectorDynamic<>& F, ChVectorDynamic<>* state_x, ChVectorDynamic<>* state_w) { this->ComputeNF(U, Qi, detJ, F, state_x, state_w); detJ /= 4.0; // because volume } } // end namespace fea } // end namespace chrono
41.643478
118
0.578618
[ "shape", "vector", "model", "transform" ]
dca0233e82cc2116a4ee0f1408e1bebe330e009f
715
cpp
C++
libs/resource_partitioner/tests/regressions/help_exit_4317_1.cpp
jokteur/hpx
689ce9b586322c90f966ef84aa6eba190f037dd7
[ "BSL-1.0" ]
2
2016-11-11T13:20:25.000Z
2017-02-21T09:39:52.000Z
libs/resource_partitioner/tests/regressions/help_exit_4317_1.cpp
jokteur/hpx
689ce9b586322c90f966ef84aa6eba190f037dd7
[ "BSL-1.0" ]
null
null
null
libs/resource_partitioner/tests/regressions/help_exit_4317_1.cpp
jokteur/hpx
689ce9b586322c90f966ef84aa6eba190f037dd7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2020 albestro // // SPDX-License-Identifier: BSL-1.0 // 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 <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/modules/testing.hpp> #include <atomic> #include <string> #include <vector> std::atomic<bool> main_executed(false); int hpx_main() { main_executed = true; return hpx::finalize(); } int main(int argc, char** argv) { hpx::init_params init_args; init_args.cfg = {"--hpx:help"}; HPX_TEST_EQ(hpx::init(argc, argv, init_args), 0); HPX_TEST(!main_executed); return hpx::util::report_errors(); }
21.029412
80
0.688112
[ "vector" ]
dca18d4431b630d41fd51907850b73dc291e150f
1,932
hh
C++
include/libbio/sdsl_boost_serialization.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
2
2021-05-21T08:44:53.000Z
2021-12-24T16:22:56.000Z
include/libbio/sdsl_boost_serialization.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
include/libbio/sdsl_boost_serialization.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef LIBBIO_SDSL_BOOST_SERIALIZATION_HH # define LIBBIO_SDSL_BOOST_SERIALIZATION_HH # ifdef LIBBIO_HAVE_SDSL # include <boost/serialization/binary_object.hpp> # include <climits> # include <sdsl/int_vector.hpp> // Boost.Serialize requirements for sdsl::int_vector. namespace boost { namespace serialization { template <typename t_archive, std::uint8_t t_width> void save(t_archive &ar, sdsl::int_vector <t_width> const &vector, unsigned int const version) { std::uint64_t capacity(vector.capacity()); std::uint64_t const bit_size(vector.bit_size()); auto const *data(vector.data()); ar & capacity; ar & bit_size; ar & make_binary_object(data, vector.bit_capacity() / CHAR_BIT); // binary_object stores a sequence of bytes. } template <typename t_archive, std::uint8_t t_width> void load(t_archive &ar, sdsl::int_vector <t_width> &vector, unsigned int const version) { std::uint64_t capacity(0); std::uint64_t bit_size(0); binary_object obj(nullptr, 0); // No default constructor. ar & capacity; ar & bit_size; ar & obj; libbio_always_assert(vector.bit_capacity() / CHAR_BIT == obj.m_size); vector.reserve(capacity); vector.bit_resize(bit_size); // binary_object stores the data in a void *. Play safe and assume that // the data is byte-aligned. auto *dst(vector.data()); auto *src(obj.m_t); std::copy_n(reinterpret_cast <char const *>(src), obj.m_size, reinterpret_cast <char *>(dst)); } template <typename t_archive, std::uint8_t t_width> void serialize(t_archive &ar, sdsl::int_vector <t_width> &vector, unsigned int version) { // See <boost/serialization/split_free.hpp>; the definition of BOOST_SERIALIZATION_SPLIT_FREE // is essentially the same as this function. split_free(ar, vector, version); } }} # endif #endif
28
111
0.726708
[ "vector" ]
dca2e94e0696b57184602fc741f715d40514f9ee
3,018
cpp
C++
Finding_shortest_path_from_source.cpp
priyanshu1044/cpp
fc7be7f38edfddfcb0477e1d732d84e448e7d009
[ "MIT" ]
1
2021-12-17T06:12:51.000Z
2021-12-17T06:12:51.000Z
Finding_shortest_path_from_source.cpp
AneriSonani09/cpp
898fd0719c6ca501837661869070c939d07b595a
[ "MIT" ]
null
null
null
Finding_shortest_path_from_source.cpp
AneriSonani09/cpp
898fd0719c6ca501837661869070c939d07b595a
[ "MIT" ]
5
2020-10-01T04:12:34.000Z
2021-10-22T04:49:45.000Z
/* PRIYANSHU IS A PEACEFULL SOUL */ #include <bits/stdc++.h> #define vi vector<int> #define vvi vector<vi> #define pii pair<int,int> #define vii vector<pii> #define rep(i,a,b) for(int i=a;i<b;i++) #define ff first #define ll long long #define ss second using namespace std; int findMinVertex(int dist[],bool visited[],int n) { int minVertex = -1; for(int i=1;i<=n;i++) { if(!visited[i] && (minVertex == -1 || dist[i] < dist[minVertex] )) { minVertex = i; } } return minVertex; } void shortest_path(int numOfNode,int *arr,int s) { int g[numOfNode+1][numOfNode+1]; for(int i=0;i<numOfNode;i++) { for(int j=0;j<numOfNode;j++) { g[i+1][j+1] = *((arr+i*numOfNode) + j); } } int dist[numOfNode+1]; bool visited[numOfNode+1]; list <int> *path = new list<int>[numOfNode+1]; for(int i=1;i<=numOfNode;i++) { dist[i] = INT_MAX; visited[i] = false; } dist[s] = 0; path[s].push_back(s); for(int i=1;i<=numOfNode;i++) { int minVertex = findMinVertex(dist,visited,numOfNode); visited[minVertex] = true; for(int j=1;j<=numOfNode;j++) { if(g[minVertex][j] > 0 && !visited[j]) { int distance = dist[minVertex] + g[minVertex][j]; if(distance < dist[j]) { path[j].clear(); list <int>l = path[minVertex]; while(!l.empty()) { int temp = l.front(); path[j].push_back(temp); l.pop_front(); } path[j].push_back(j); dist[j] = distance; } } } } for(int i=1;i<=numOfNode;i++) { cout << i << "\t" << dist[i] << "\t" << s; path[i].pop_front(); while(!path[i].empty()) { cout << "->"; cout << path[i].front(); path[i].pop_front(); } cout << endl; } } int main() { int numOfNode,source; cin >> numOfNode; int g[numOfNode][numOfNode]; for(int i=0;i<numOfNode;i++) { for(int j=0;j<numOfNode;j++) { cin >> g[i][j]; if(i == j && g[i][j] != 0) { cout << "Weight of the edge " << i+1 << " <-> " << j+1 << " must be 0"; exit(0); } if(i != j && g[i][j] == 0) { cout << "Weight of the edge " << i+1 << " <-> " << j+1 << " can not be 0"; exit(0); } if(g[i][j] < -1) { cout << "Weight of the edge " << i+1 << " <-> " << j+1 << " can not be negative"; exit(0); } } } cin >> source; shortest_path(numOfNode,(int *)g,source); return 0; }
24.737705
97
0.414182
[ "vector" ]
dca655291db83eb0b50234bba72a3912d3137891
40,073
hpp
C++
library/include/ux/Drawing.hpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
library/include/ux/Drawing.hpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
library/include/ux/Drawing.hpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #ifndef UXAPI_UX_DRAWING_HPP_ #define UXAPI_UX_DRAWING_HPP_ #include <sdk/types.h> #include "sgfx/Bitmap.hpp" #include "sgfx/Pen.hpp" #include "sgfx/Theme.hpp" namespace ux { /*! \details Drawing size (unsigned) */ typedef u16 drawing_size_t; /*! \details Drawing position (signed) */ typedef s16 drawing_int_t; /*! \brief Holds a coordinate (point) in the drawing system */ typedef struct MCU_PACK { drawing_int_t x /*! X position */; drawing_int_t y /*! Y position */; } drawing_point_t; /*! \brief Holds a dimension in the drawing system */ typedef struct MCU_PACK { drawing_size_t width /*! Width of the object */; drawing_size_t height /*! Height of the object */; } drawing_area_t; typedef struct MCU_PACK { drawing_point_t point /*! Point in the region */; drawing_area_t area /*! Height of the object */; } drawing_region_t; sg_color_t color_transparent(); /*! \brief Data used for drawing a draw::Drawing on a bitmap * \details This data structure holds a real bitmap but the point * and dimensions haven't been mapped to the bitmap. * The point \a p and dimension \a d are both in a universal coordinate * system from 0 to draw::DrawingAttributes::scale(). For example * if draw::DrawingAttributes::scale() is 1000 and p.x and p.y both are equal to * 500, the top left corner of any item drawn using these attibutes will be in * the center of the target bitmap (regardless of the target bitmap's size). */ typedef struct MCU_PACK { sgfx::Bitmap *bitmap /*! A pointer to the target bitmap */; drawing_region_t region /*! The region on the bitmap where draw::Drawing will be drawn */; } drawing_attr_t; /*! \brief Attributes for drawing directly on a bitmap using bitmap coordinates */ typedef struct MCU_PACK { sgfx::Bitmap *bitmap /*! The local bitmap */; sg_region_t region /*! The region on the bitmap where draw::DrawingScaled will be drawn */ ; sg_region_t window /*! The window on the display where the drawing will be drawn */; } drawing_scaled_attr_t; /*! \details This returns a drawing_point_t populated with x and y */ drawing_point_t drawing_point(drawing_int_t x, drawing_int_t y); /*! \details This returns a drawing_area_t populated with the width and height. * * @param w Width of the returned data * @param h Height of the retured data * @return A drawing_area_t with w and h populated as specified */ drawing_area_t drawing_area(drawing_size_t w, drawing_size_t h); drawing_area_t drawing_dim(drawing_size_t w, drawing_size_t h); class DrawingArea { public: DrawingArea() { m_area.height = 0; m_area.width = 0; } DrawingArea(drawing_size_t w, drawing_size_t h) { m_area.height = h; m_area.width = w; } DrawingArea(const drawing_area_t &area) { m_area = area; } bool is_valid() const { return m_area.width && m_area.height; } static DrawingArea maximum(); drawing_size_t width() const { return m_area.width; } drawing_size_t height() const { return m_area.height; } DrawingArea &set_width(drawing_size_t value) { m_area.width = value; return *this; } DrawingArea &set_height(drawing_size_t value) { m_area.height = value; return *this; } const drawing_area_t &area() const { return m_area; } drawing_area_t &area() { return m_area; } operator const drawing_area_t &() const { return m_area; } private: drawing_area_t m_area; }; class DrawingPoint { public: DrawingPoint() { m_point.x = 0; m_point.y = 0; } DrawingPoint(drawing_int_t x, drawing_int_t y) { m_point.x = x; m_point.y = y; } DrawingPoint(const drawing_point_t &point) { m_point = point; } static DrawingPoint origin() { return DrawingPoint(0, 0); } DrawingPoint operator+(const DrawingPoint &point) const { DrawingPoint result(*this); result.m_point.x += point.x(); result.m_point.y += point.y(); return result; } DrawingPoint &operator+=(const DrawingPoint &point) { *this = *this + point; return *this; } DrawingPoint operator-(const DrawingPoint &point) const { DrawingPoint result(*this); result.m_point.x -= point.x(); result.m_point.y -= point.y(); return result; } DrawingPoint &operator-=(const DrawingPoint &point) { *this = *this - point; return *this; } drawing_int_t x() const { return m_point.x; } DrawingPoint &set_x(drawing_int_t value) { m_point.x = value; return *this; } drawing_int_t y() const { return m_point.y; } DrawingPoint &set_y(drawing_int_t value) { m_point.y = value; return *this; } const drawing_point_t &point() const { return m_point; } drawing_point_t &point() { return m_point; } operator const drawing_point_t &() const { return m_point; } private: drawing_point_t m_point; }; class DrawingRegion { public: DrawingRegion() { m_region.point = DrawingPoint(0, 0); } DrawingRegion(const drawing_region_t &region) { m_region = region; } bool is_valid() const { return DrawingArea(m_region.area).is_valid(); } DrawingRegion(const DrawingPoint &point, const DrawingArea &area) { m_region.point = point; m_region.area = area; } DrawingRegion &operator<<(const DrawingArea &area) { m_region.area = area; return *this; } DrawingRegion &operator<<(const DrawingPoint &point) { m_region.point = point; return *this; } DrawingArea area() const { return m_region.area; } DrawingPoint point() const { return m_region.point; } operator const drawing_region_t &() const { return m_region; } private: drawing_region_t m_region; }; /*! \brief Drawing Attribute Class * \details This class contains the information needed to draw various * Drawing objects on a bitmap. * * This class is passed to Drawing::draw() to render graphics on a bitmap. * * The following code will draw an rectangle in the middle of a 64x64 * pixel bitmap. * * ``` * #include <sgfx.hpp> * #include <draw.hpp> * * Bitmap bitmap(64,64); //64x64 pixel bitmap * DrawingAttributes attributes; * * attributes << bitmap; //apply bitmap to attributes * * Rectangle().draw(attributes + DrawingPoint(250,250) + DrawingArea(500,500)); * ``` * * A DrawingAttributes object is always passed to the Drawing::draw() method. * * The + operator when adding a DrawingPoint will create a new * DrawingAttributes object that starts at the specified point. The coordinates * are the width of the bitmap / 1000. * * The + operator when adding a DrawingArea will scale the region of the * DrawingAttributes based on the size of the bitmap where 1000 represents * full width and height. * * So in the example above, the top left corner of the rectangle is mapped * to 16,16 (64*250/1000=16). The width and height of the rectangle are both * 32 (64*500/1000=32). * * These operators allow the cascading of drawing objects as the region scales. * For example, if we create a DrawingAttributes object that is already * region limited, the + operators will operate within the existing region. * * ``` * Bitmap bitmap(64,64); //64x64 pixel bitmap * DrawingAttributes attributes; * * DrawingRegion region(DrawingPoint(0,0), DrawingArea(500,500)); * attributes << bitmap << region; //apply bitmap and region to attributes * * //rectangle will be 500/1000 of 500/1000 of the area of the bitmap * Rectangle().draw(attributes + DrawingArea(500,500)); * ``` * * In this second example, because the DrawingAttributes region was already set * to a subregion of the bitmap, the + operator with the DrawingArea scales * the region down by 500/1000. So the rectangle is 16,16 (64*500/1000 * * 500/1000). * * Using these operators to cascade is great for creating compound * drawing objects like a button. * * ``` * class Button: public Drawing { * public: * void draw(const DrawingAttributes & attributes){ * RoundedRectangle().draw(attributes); //files entire attributes region * * //The Icon is scaled down to half the width/height and centered * Icon().set_name("OK").draw(attributes + DrawingPoint(250,250) + * DrawingArea(500,500)); * * } * }; * ``` * */ class DrawingAttributes { public: /*! \details Construct an object */ DrawingAttributes(); /*! \details Construct an object from a drawing_attr_t */ DrawingAttributes(const drawing_attr_t &attr); DrawingAttributes(sgfx::Bitmap *bitmap, const DrawingRegion &region) { m_attr.bitmap = bitmap; m_attr.region = region; } /*! \details Access the underlying attr object */ drawing_attr_t &attributes() { return m_attr; } const drawing_attr_t &attributes() const { return m_attr; } DrawingAttributes(sgfx::Bitmap &bitmap); DrawingAttributes(sgfx::Bitmap &bitmap, const DrawingRegion &region); bool is_valid() const { return m_attr.bitmap != 0; } /*! \details Set the bitmap */ DrawingAttributes &set_bitmap(sgfx::Bitmap &b) { m_attr.bitmap = &b; return *this; } /*! \details Set the dimensions. Both width and height are from 0 to 1000. */ DrawingAttributes &set_area(const DrawingArea &value) { m_attr.region.area = value; return *this; } /*! \details Set the location. Both x and y are from 0 to 1000. */ DrawingAttributes &set_point(const DrawingPoint &p) { m_attr.region.point = p; return *this; } /*! \details Return the width */ drawing_size_t width() const { return m_attr.region.area.width; } /*! \details Return the height */ drawing_size_t height() const { return m_attr.region.area.height; } /*! \details Return the x value */ drawing_int_t x() const { return m_attr.region.point.x; } /*! \details Return the y value */ drawing_int_t y() const { return m_attr.region.point.y; } /*! \details Checks to see if bitmap is available. */ bool is_bitmap_available() const { return m_attr.bitmap != 0; } /*! \details Access the bitmap */ sgfx::Bitmap &bitmap() const { return *(m_attr.bitmap); } /*! \details Returns a copy of the region. */ DrawingRegion region() const { return m_attr.region; } /*! \details Returns a copy of the position. */ DrawingPoint point() const { return m_attr.region.point; } /*! \details Returns a copy of the dimensions. */ DrawingArea area() const { return m_attr.region.area; } /*! \details Calculate the scaled height relative to the height of the * DrawingAttributes object. * * @param v The value to calculate * * This method will calculate a height relative to the heigh of the object * and the scale() value. For example, if the current object maps to a region * of a bitmap height of 500 pixels, this method will return a drawing height * that will be from 0 to 500 pixels with \a v being from 0 to * DrawingAttributes::scale(). * */ drawing_int_t calculate_height(drawing_int_t v) const; /*! \details Calculate the scaled width (width of object on the bitmap) */ drawing_int_t calculate_width(drawing_int_t v) const; /*! \details Add a drawing_point_t offset * * This operated can be used to create a subregion within the object * when used with operation+ (drawing_area_t). * * For example: * \code * DrawingAttributes attr0; * DrawingAttributes attr1; * attr0 = attr1 + DrawingPoint(250,250) + DrawingArea(500,500); * \endcode * * When mapped to the same bitmap, attr0 will be half the height and half * the width of attr1. attr0 and attr1 will have the same center point. * * These operators can be used to draw sub-drawings on drawings. The following * example draws a rectangles recursively in an object. * * ``` * void draw_rect_recursive(const DrawingAttributes & attr){ * static sg_color_t color = 0; * Rectangle().set_color(color++ % 1).draw(attr + DrawingPoint(250,250) + *DrawingArea(500,500); if( attr.width() > 100 ){ draw_rect_recursive(attr); * } * } * ``` * */ DrawingAttributes operator+(const drawing_point_t &d) const; /*! \details Update the dimension (must come after adding drawing_point_t) */ DrawingAttributes operator+(const drawing_area_t &d) const; DrawingAttributes operator+(const DrawingPoint &d) const; DrawingAttributes operator+(const DrawingArea &d) const; DrawingAttributes operator+(DrawingRegion region) const { return *this + region.point() + region.area(); } /*! \details Calculate dimensions that will map to the bitmap as a square. * * @param v The maximum width or height * @return Square dimensions */ drawing_area_t calculate_square(drawing_size_t v) const; /*! \details Calculate dimensions that will map to the bitmap as a square * with the given width. * * @param v The width (height will be calculated) * @return Square dimensions */ drawing_area_t calculate_square_width(drawing_size_t v) const; /*! \details Calculate dimensions that will map to the bitmap as a square * with the given height. * * @param v The height (width will be calculated) * @return Square dimensions */ drawing_area_t calculate_square_height(drawing_size_t v) const; static sg_area_t calculate_area_on_bitmap(const DrawingAttributes &attr); static sg_size_t calculate_height_on_bitmap(const DrawingAttributes &attr); static sg_size_t calculate_height_on_bitmap( const DrawingAttributes &attr, drawing_size_t value); static sg_size_t calculate_width_on_bitmap(const DrawingAttributes &attr); static sg_size_t calculate_width_on_bitmap( const DrawingAttributes &attr, drawing_size_t value); static sg_point_t calculate_point_on_bitmap(const DrawingAttributes &attr); static sg_region_t calculate_region_on_bitmap(const DrawingAttributes &attr); sg_area_t calculate_area_on_bitmap() const { return calculate_area_on_bitmap(*this); } sg_size_t calculate_height_on_bitmap() const { return calculate_height_on_bitmap(*this); } sg_size_t calculate_height_on_bitmap(drawing_size_t value) const { return calculate_height_on_bitmap(*this, value); } sg_size_t calculate_width_on_bitmap() const { return calculate_width_on_bitmap(*this); } sg_size_t calculate_width_on_bitmap(drawing_size_t value) const { return calculate_width_on_bitmap(*this, value); } sg_point_t calculate_point_on_bitmap() const { return calculate_point_on_bitmap(*this); } sg_region_t calculate_region_on_bitmap() const { return calculate_region_on_bitmap(*this); } drawing_size_t calculate_height_on_drawing(sg_size_t height); drawing_size_t calculate_width_on_drawing(sg_size_t width); /*! \details This value determines how all objects are scaled. * * The default value is 1000. This means a value of 500 is half the target * bitmap. * * sg_size_t * drawing_size_t / scale() = sg_size_t (drawing_size_t cancels * with scale()) * */ static drawing_size_t scale() { return 1000; } private: /*! \cond */ drawing_attr_t m_attr; /*! \endcond */ }; /*! \brief Scaled Drawing Attributes * \details This is similar to draw::DrawingAttributes but the point * and area have been scaled to fit in the target bitmap. */ class DrawingScaledAttributes { public: DrawingScaledAttributes() {} DrawingScaledAttributes(const DrawingAttributes &attr) { set( attr.bitmap(), attr.calculate_point_on_bitmap(), attr.calculate_area_on_bitmap()); } operator drawing_scaled_attr_t() { return m_attr; } void set(sgfx::Bitmap &b, sg_point_t p, sg_area_t d); /*! \details Assign a value to the bitmap pointer using a reference. */ DrawingScaledAttributes &set_bitmap(sgfx::Bitmap &b) { m_attr.bitmap = &b; return *this; } /*! \details Assigns area. */ DrawingScaledAttributes &set_area(const sgfx::Area &area) { m_attr.region.area = area.area(); return *this; } /*! \details Sets the height of the object */ DrawingScaledAttributes &set_height(sg_size_t h) { m_attr.region.area.height = h; return *this; } /*! \details Sets the width of the object. */ DrawingScaledAttributes &set_width(sg_size_t w) { m_attr.region.area.height = w; return *this; } /*! \details Sets the x value of the object. */ DrawingScaledAttributes &set_x(sg_int_t x) { m_attr.region.point.x = x; return *this; } /*! \details Sets the y value of the object. */ DrawingScaledAttributes &set_y(sg_int_t y) { m_attr.region.point.y = y; return *this; } /*! \details Assign the position */ void set_point(sg_point_t p) { m_attr.region.point = p; } sgfx::Bitmap &bitmap() const { return *m_attr.bitmap; } sgfx::Region region() const { return m_attr.region; } sgfx::Point point() const { return m_attr.region.point; } sgfx::Area area() const { return m_attr.region.area; } drawing_scaled_attr_t &attributes() { return m_attr; } const drawing_scaled_attr_t &attributes() const { return m_attr; } /*! \details Return the width */ sg_size_t width() const { return m_attr.region.area.width; } /*! \details Return the height */ sg_size_t height() const { return m_attr.region.area.height; } /*! \details Return the x value */ sg_int_t x() const { return m_attr.region.point.x; } /*! \details Return the y value */ sg_int_t y() const { return m_attr.region.point.y; } /*! \details Add an sg_point_t */ DrawingScaledAttributes operator+(const sgfx::Point &p) const; /*! \details Add an sg_area_t */ DrawingScaledAttributes operator+(const sgfx::Area &a) const; /*! \details Calculate a width value * * @param v Unscaled drawing dimensions * @return */ sg_size_t calculate_width(drawing_size_t v) const; sg_size_t calculate_height(drawing_size_t v) const; private: drawing_scaled_attr_t m_attr; }; template <typename T> class DrawingComponentProperties { public: bool is_align_left() const { return m_flags & flag_align_left; } bool is_align_right() const { return m_flags & (flag_align_right); } bool is_align_center() const { return (m_flags & (flag_align_left | flag_align_right)) == 0; } bool is_align_top() const { return m_flags & (flag_align_top); } bool is_align_bottom() const { return m_flags & (flag_align_bottom); } bool is_align_middle() const { return (m_flags & (flag_align_top | flag_align_bottom)) == 0; } T & set_font_name(const var::StringView value){ m_font_name = value; return derived_this(); } var::StringView font_name() const { return m_font_name; } T &set_align_left(bool v = true) { v ? m_flags |= flag_align_left : 0; return derived_this(); } T &set_align_right(bool v = true) { v ? m_flags |= flag_align_right : 0; return derived_this(); } T &set_align_center(bool v = true) { if (v) { m_flags &= ~(flag_align_left | flag_align_right); } return derived_this(); } T &set_align_top(bool v = true) { v ? m_flags |= flag_align_top : 0; return derived_this(); } T &set_align_bottom(bool v = true) { v ? m_flags |= flag_align_bottom : 0; return derived_this(); } T &set_align_middle(bool v = true) { if (v) { m_flags &= ~(flag_align_top | flag_align_bottom); } return derived_this(); } u32 alignment() const { return m_flags; } T &set_alignment(u32 value) { m_flags = value; return derived_this(); } T &set_border(u8 value) { m_border.top = value; m_border.bottom = value; m_border.left = value; m_border.right = value; return derived_this(); } T &set_border_size(u8 value) { return set_border(value); } T &set_top_border(u8 value) { m_border.top = value; return derived_this(); } T &set_bottom_border(u8 value) { m_border.bottom = value; return derived_this(); } T &set_left_border(u8 value) { m_border.left = value; return derived_this(); } T &set_right_border(u8 value) { m_border.right = value; return derived_this(); } T &set_horizontal_border(u8 value) { m_border.right = value; m_border.left = value; return derived_this(); } T &set_vertical_border(u8 value) { m_border.top = value; m_border.bottom = value; return derived_this(); } T &set_padding(u8 value) { m_padding.top = value; m_padding.bottom = value; m_padding.left = value; m_padding.right = value; return derived_this(); } T &set_vertical_padding(u8 value) { m_padding.top = value; m_padding.bottom = value; return derived_this(); } T &set_top_padding(u8 value) { m_padding.top = value; return derived_this(); } T &set_bottom_padding(u8 value) { m_padding.bottom = value; return derived_this(); } T &set_horizontal_padding(u8 value) { m_padding.left = value; m_padding.right = value; return derived_this(); } T &set_left_padding(u8 value) { m_padding.left = value; return derived_this(); } T &set_right_padding(u8 value) { m_padding.right = value; return derived_this(); } T &set_margin(u8 value) { m_margin.top = value; m_margin.bottom = value; m_margin.left = value; m_margin.right = value; return derived_this(); } T &set_vertical_margin(u8 value) { m_margin.top = value; m_margin.bottom = value; return derived_this(); } T &set_top_margin(u8 value) { m_margin.top = value; return derived_this(); } T &set_bottom_margin(u8 value) { m_margin.bottom = value; return derived_this(); } T &set_horizontal_margin(u8 value) { m_margin.left = value; m_margin.right = value; return derived_this(); } T &set_left_margin(u8 value) { m_margin.left = value; return derived_this(); } T &set_right_margin(u8 value) { m_margin.right = value; return derived_this(); } T &set_outline(u8 value) { m_margin.top = value; m_margin.bottom = value; m_margin.left = value; m_margin.right = value; return derived_this(); } T &set_vertical_outline(u8 value) { m_outline.top = value; m_outline.bottom = value; return derived_this(); } T &set_top_outline(u8 value) { m_outline.top = value; return derived_this(); } T &set_bottom_outline(u8 value) { m_outline.bottom = value; return derived_this(); } T &set_horizontal_outline(u8 value) { m_outline.left = value; m_outline.right = value; return derived_this(); } T &set_left_outline(u8 value) { m_outline.left = value; return derived_this(); } T &set_right_outline(u8 value) { m_outline.right = value; return derived_this(); } u8 border_size() const { return (m_border.top + m_border.bottom + m_border.left + m_border.right) / 4; } u8 left_border() const { return m_border.left; } u8 right_border() const { return m_border.right; } u8 top_border() const { return m_border.top; } u8 bottom_border() const { return m_border.bottom; } u8 vertical_padding() const { return m_padding.top + m_padding.bottom; } u8 horizontal_padding() const { return m_padding.left + m_padding.right; } u8 left_padding() const { return m_padding.left; } u8 right_padding() const { return m_padding.right; } u8 top_padding() const { return m_padding.top; } u8 bottom_padding() const { return m_padding.bottom; } u8 vertical_margin() const { return m_margin.top + m_margin.bottom; } u8 horizontal_margin() const { return m_margin.left + m_margin.right; } u8 left_margin() const { return m_margin.left; } u8 right_margin() const { return m_margin.right; } u8 top_margin() const { return m_margin.top; } u8 bottom_margin() const { return m_margin.bottom; } u8 vertical_outline() const { return m_outline.top + m_outline.bottom; } u8 horizontal_outline() const { return m_outline.left + m_outline.right; } u8 left_outline() const { return m_outline.left; } u8 right_outline() const { return m_outline.right; } u8 top_outline() const { return m_outline.top; } u8 bottom_outline() const { return m_outline.bottom; } protected: enum flags { flag_align_left = 1 << 0, flag_align_right = 1 << 1, flag_align_top = 1 << 2, flag_align_bottom = 1 << 3 }; typedef struct { u8 top; u8 right; u8 bottom; u8 left; } dimension_t; sg_size_t calculate_border_size(sg_size_t height) { return calculate_pixel_size(border_size(), height); } sgfx::Region calculate_region_inside( const sgfx::Region &region, const dimension_t &dimension) const { dimension_t effective; effective.left = calculate_pixel_size(dimension.left, region.width()); effective.right = calculate_pixel_size(dimension.right, region.width()); effective.top = calculate_pixel_size(dimension.top, region.height()); effective.bottom = calculate_pixel_size(dimension.bottom, region.height()); return sgfx::Region( sgfx::Point(region.x() + effective.left, region.y() + effective.top), sgfx::Area( region.width() - (effective.left + effective.right), region.height() - (effective.top + effective.bottom))); } sgfx::Region calculate_region_inside_outline(const sgfx::Region &region) const { return calculate_region_inside(region, m_outline); } sgfx::Region calculate_region_inside_margin(const sgfx::Region &region) const { return calculate_region_inside(region, m_margin); } sgfx::Region calculate_region_inside_border(const sgfx::Region &region) const { return calculate_region_inside( calculate_region_inside_margin(region), m_border); } sgfx::Region calculate_region_inside_padding(const sgfx::Region &region) const { return calculate_region_inside( calculate_region_inside_border(region), m_padding); } void draw_base_properties( sgfx::Bitmap &bitmap, const sgfx::Region &region, const sgfx::Theme *theme) const { const sgfx::Region inside_outline = calculate_region_inside_outline(region); const sgfx::Region inside_margin = calculate_region_inside_margin(region); bitmap.set_pen(sgfx::Pen().set_color(theme->border_color())) .draw_rectangle(region) .set_pen(sgfx::Pen().set_color(theme->background_color())) .draw_rectangle(inside_outline) .set_pen(sgfx::Pen().set_color(theme->border_color())) .draw_rectangle(inside_margin) .set_pen(sgfx::Pen().set_color(theme->color())) .draw_rectangle(calculate_region_inside_border(region)); } private: dimension_t m_padding = {5, 5, 5, 5}; dimension_t m_margin = {0}; dimension_t m_border = {1, 1, 1, 1}; dimension_t m_outline = {0}; var::StringView m_font_name; u32 m_flags = 0; // default is middle/center static sg_size_t calculate_pixel_size(u8 value, sg_size_t dimension) { sg_size_t result = (dimension * value + 100) / 200; if (!result && value) { result = 1; } return result; } T &derived_this() { return static_cast<T &>(*this); } }; #define DRAWING_COMPONENT_PROPERTIES_ACCESS(DERIVED_TYPE) \ DERIVED_TYPE &set_align_left(bool v = true) { \ DrawingComponentProperties::set_align_left(v); \ return *this; \ } \ DERIVED_TYPE &set_align_right(bool v = true) { \ DrawingComponentProperties::set_align_right(v); \ return *this; \ } \ DERIVED_TYPE &set_align_center(bool v = true) { \ DrawingComponentProperties::set_align_center(v); \ return *this; \ } \ DERIVED_TYPE &set_align_top(bool v = true) { \ DrawingComponentProperties::set_align_top(v); \ return *this; \ } \ DERIVED_TYPE &set_align_bottom(bool v = true) { \ DrawingComponentProperties::set_align_bottom(v); \ return *this; \ } \ DERIVED_TYPE &set_align_middle(bool v = true) { \ DrawingComponentProperties::set_align_middle(v); \ return *this; \ } \ DERIVED_TYPE &set_alignment(u32 value) { \ DrawingComponentProperties::set_alignment(value); \ return *this; \ } \ DERIVED_TYPE &set_border(u8 value) { \ DrawingComponentProperties::set_border(value); \ return *this; \ } \ DERIVED_TYPE &set_top_border(u8 value) { \ DrawingComponentProperties::set_top_border(value); \ return *this; \ } \ DERIVED_TYPE &set_bottom_border(u8 value) { \ DrawingComponentProperties::set_bottom_border(value); \ return *this; \ } \ DERIVED_TYPE &set_left_border(u8 value) { \ DrawingComponentProperties::set_left_border(value); \ return *this; \ } \ DERIVED_TYPE &set_right_border(u8 value) { \ DrawingComponentProperties::set_right_border(value); \ return *this; \ } \ DERIVED_TYPE &set_horizontal_border(u8 value) { \ DrawingComponentProperties::set_horizontal_border(value); \ return *this; \ } \ DERIVED_TYPE &set_vertical_border(u8 value) { \ DrawingComponentProperties::set_vertical_border(value); \ return *this; \ } \ DERIVED_TYPE &set_padding(u8 value) { \ DrawingComponentProperties::set_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_top_padding(u8 value) { \ DrawingComponentProperties::set_top_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_bottom_padding(u8 value) { \ DrawingComponentProperties::set_bottom_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_left_padding(u8 value) { \ DrawingComponentProperties::set_left_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_right_padding(u8 value) { \ DrawingComponentProperties::set_right_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_horizontal_padding(u8 value) { \ DrawingComponentProperties::set_horizontal_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_vertical_padding(u8 value) { \ DrawingComponentProperties::set_vertical_padding(value); \ return *this; \ } \ DERIVED_TYPE &set_margin(u8 value) { \ DrawingComponentProperties::set_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_top_margin(u8 value) { \ DrawingComponentProperties::set_top_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_bottom_margin(u8 value) { \ DrawingComponentProperties::set_bottom_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_left_margin(u8 value) { \ DrawingComponentProperties::set_left_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_right_margin(u8 value) { \ DrawingComponentProperties::set_right_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_horizontal_margin(u8 value) { \ DrawingComponentProperties::set_horizontal_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_vertical_margin(u8 value) { \ DrawingComponentProperties::set_vertical_margin(value); \ return *this; \ } \ DERIVED_TYPE &set_outline(u8 value) { \ DrawingComponentProperties::set_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_top_outline(u8 value) { \ DrawingComponentProperties::set_top_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_bottom_outline(u8 value) { \ DrawingComponentProperties::set_bottom_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_left_outline(u8 value) { \ DrawingComponentProperties::set_left_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_right_outline(u8 value) { \ DrawingComponentProperties::set_right_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_horizontal_outline(u8 value) { \ DrawingComponentProperties::set_horizontal_outline(value); \ return *this; \ } \ DERIVED_TYPE &set_vertical_outline(u8 value) { \ DrawingComponentProperties::set_vertical_outline(value); \ return *this; \ } class Drawing : public api::ExecutionContext { public: Drawing(); static sg_size_t width(sg_size_t scale, sg_area_t d); static sg_size_t height(sg_size_t scale, sg_area_t d); /*! \details This method draws the object using the specified drawing * attributes. * * The attributes specify which bitmap to draw on, what size to draw, and * where to draw. The dimensions and position are scaled to fit on the bitmap. * */ virtual void draw(const DrawingAttributes &attr); void draw( const DrawingAttributes &attr, const DrawingPoint &point, const DrawingArea &area) { draw(attr + point + area); } /*! \details This method will clear the pixels in the area of the bitmap * specified. * * @param attr Specifies the bitmap and area * @param v Specifies the fill pattern */ static void clear(const DrawingAttributes &attr); /*! \brief Sets the scale value (see Element::scale() for details). */ static void set_scale(drawing_size_t s) { m_scale = s; } /*! \details This methods draws the drawing on the specified attributes. * * @param attr Specifies the bitmap, point and area to draw the drawing */ virtual void draw(const DrawingScaledAttributes &attr); static drawing_size_t scale() { return m_scale; } protected: /*! \cond */ sg_point_t point_on_bitmap( sgfx::Bitmap &b, drawing_size_t x, drawing_size_t y, sg_area_t d); sg_area_t dim_on_bitmap(sgfx::Bitmap &b) const; private: static drawing_size_t m_scale; static void draw_rectangle(const DrawingAttributes &attr, const sgfx::Pen &pen); /*! \endcond */ }; } // namespace ux #endif /* SAPI_DRAW_DRAWING_HPP_ */
35.151754
80
0.579243
[ "render", "object" ]
dca9e281656836f89f517cc4d80d26b5ce0849b1
1,058
cpp
C++
tests/partners.cpp
hguo/diy
3a3473e8289872903de2763792cc570817a00a3f
[ "BSD-3-Clause-LBNL" ]
null
null
null
tests/partners.cpp
hguo/diy
3a3473e8289872903de2763792cc570817a00a3f
[ "BSD-3-Clause-LBNL" ]
null
null
null
tests/partners.cpp
hguo/diy
3a3473e8289872903de2763792cc570817a00a3f
[ "BSD-3-Clause-LBNL" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <diy/decomposition.hpp> #include <diy/partners/common.hpp> void test(int n, int k) { int dim = 2; diy::DiscreteBounds global_bounds(dim); global_bounds.min[0] = global_bounds.min[1] = 0; global_bounds.max[0] = global_bounds.min[1] = 1023; diy::RegularDecomposer<diy::DiscreteBounds> decomposer(dim, global_bounds, n); diy::RegularPartners partners(decomposer, k, false); int kvs_product = 1; for (size_t i = 0; i < partners.rounds(); ++i) kvs_product *= partners.size(i); REQUIRE(kvs_product == n); for (int gid = 0; gid < n; ++gid) for (size_t i = 0; i < partners.rounds(); ++i) { std::vector<int> nbr_gids; partners.fill(i, gid, nbr_gids); for (int nbr_gid : nbr_gids) CHECK(nbr_gid <= n); } } TEST_CASE("RegularPartners", "[partners]") { SECTION("n = 189, k = 8") { test(189, 8); } SECTION("n = 10, k = 8") { test(10, 8); } }
23
82
0.571834
[ "vector" ]
dcac127beded438f2581b13270b7e2e423ba6630
3,276
hpp
C++
Declarations/Takion/FrontEnd/UnitMetadataDecl.hpp
jwkim98/Takion
5e7351c5bd3400429dc7d28c0be4cddcc1324180
[ "MIT" ]
1
2021-07-06T10:52:41.000Z
2021-07-06T10:52:41.000Z
Declarations/Takion/FrontEnd/UnitMetadataDecl.hpp
jwkim98/Takion
5e7351c5bd3400429dc7d28c0be4cddcc1324180
[ "MIT" ]
null
null
null
Declarations/Takion/FrontEnd/UnitMetadataDecl.hpp
jwkim98/Takion
5e7351c5bd3400429dc7d28c0be4cddcc1324180
[ "MIT" ]
3
2020-08-08T15:03:28.000Z
2020-11-04T17:17:59.000Z
// Copyright (c) 2020, Jaewoo Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef TAKION_GRAPH_UNITMETADATA_DECL_HPP #define TAKION_GRAPH_UNITMETADATA_DECL_HPP #include <Takion/Units/UnitType.hpp> #include <Takion/Utils/Shape.hpp> #include <Takion/Utils/Parameter.hpp> #include <Takion/Computations/Initializers/InitializerType.hpp> #include <vector> #include <memory> #include <unordered_map> namespace Takion::FrontEnd { template <typename T> class UnitMetaData { public: UnitMetaData() = default; UnitMetaData( UnitId unitId, std::size_t batchSize, std::unordered_map<std::string, Shape> internalVariableShapeMap, std::unordered_map<std::string, std::unique_ptr<Compute::Initializer<T>>> initializerMap, std::unordered_map<std::string, Shape> inputShapeMap, Shape outputShape, std::unordered_map<std::string, UnitId> inputUnitIdMap, Compute::Device device, Parameter params = Parameter()); ~UnitMetaData() = default; UnitMetaData(const UnitMetaData& unitMetaData) = delete; UnitMetaData(UnitMetaData&& unitMetaData) noexcept; UnitMetaData& operator=(const UnitMetaData& unitMetaData) = delete; UnitMetaData& operator=(UnitMetaData&& unitMetaData) noexcept; void AppendOutputUnitId(UnitId unitId); void SetOutputUnitIdVector(std::vector<UnitId> unitIdVector); //! Used to add internal tensor if required //! \param key : key to store the tensor //! \param tensor: tensor to store void AddInternalTensor(const std::string& key, Tensor<T> tensor); [[nodiscard]] std::size_t BatchSize() const; [[nodiscard]] UnitId Id() const; [[nodiscard]] const Tensor<T>& GetInternalTensor( const std::string& key) const; [[nodiscard]] Shape GetInputShape(const std::string& key) const; [[nodiscard]] UnitId GetInputUnitId(const std::string& key) const; [[nodiscard]] Shape GetOutputShape() const; [[nodiscard]] std::unordered_map<std::string, UnitId> InputUnitMap() const; [[nodiscard]] std::vector<UnitId> OutputUnitVector() const; [[nodiscard]] const std::unique_ptr<Compute::Initializer<T>>& GetInitializer( const std::string& name) const; [[nodiscard]] Shape InternalVariableShape(const std::string& name) const; private: UnitId m_unitId = UnitId(); std::unordered_map<std::string, Shape> m_internalVariableShapeMap; std::unordered_map<std::string, std::unique_ptr<Compute::Initializer<T>>> m_initializerMap; std::unordered_map<std::string, Tensor<T>> m_internalTensorMap; //! Input names and their shape std::unordered_map<std::string, Shape> m_inputShapeMap; Shape m_outputShape; //! Input names and their unitId //! key of inputShapeMap and inputUnitIdMap must be identical std::unordered_map<std::string, UnitId> m_inputUnitMap; std::vector<UnitId> m_outputUnitIdVector; std::size_t m_batchSize = 0; public: Compute::Device Device; Parameter Params = Parameter(); }; } #endif
33.090909
82
0.696276
[ "shape", "vector" ]
dcad3cb42bf504944fcec45f53a2eedf4d447979
2,453
hxx
C++
Legolas/BlockMatrix/Structures/Sparse/SparseScalarVecMapContainer.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Sparse/SparseScalarVecMapContainer.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Sparse/SparseScalarVecMapContainer.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
1
2021-02-11T14:43:25.000Z
2021-02-11T14:43:25.000Z
#ifndef __LEGOLAS_SPARSESCALARVECMAPCONTAINER_HXX__ #define __LEGOLAS_SPARSESCALARVECMAPCONTAINER_HXX__ #include "Legolas/BlockMatrix/Matrix.hxx" namespace Legolas{ class SparseScalarVecMapContainer{ public: template <class SCALAR> class Engine: public Matrix{ public: typedef SCALAR RealType; typedef Engine<SCALAR> Container; private: typedef std::map<int,SCALAR> Row; typedef std::vector< Row > SparseData; SparseData sparseData_; public: virtual ~Engine( void ){} inline Engine(const VirtualMatrixShape & virtualMatrixShape):Matrix(virtualMatrixShape), sparseData_(virtualMatrixShape.nrows()){} inline Engine(const Container & container):Matrix(container), sparseData_(container.sparseData_){} inline void setSparseElement(int i, int j, const SCALAR & value){ sparseData_[i][j]=value; } inline const SCALAR & sparseGetElement(int i, int j) const{ const Row & rowI=sparseData_[i]; typename Row::const_iterator it=rowI.find(j); if (it==rowI.end()){ INFOS("Element does not exist"); INFOS("i="<<i); INFOS("j="<<j); throw std::runtime_error("Element does not exist"); } return (*it).second; } inline SCALAR & sparseGetElement(int i, int j){ Row & rowI=sparseData_[i]; typename Row::iterator it=rowI.find(j); if (it==rowI.end()){ INFOS("Element does not exist"); INFOS("i="<<i); INFOS("j="<<j); throw std::runtime_error("Element does not exist"); } return (*it).second; } inline int beginRow( void ) const {return 0;} inline int endRow( void ) const {return sparseData_.size(); } inline int beginColInRow( int i ) const { int result=0; const Row & rowI=sparseData_[i]; if (rowI.begin()!=sparseData_[i].end()) result=(*(rowI.begin())).first; return result;; } inline int endColInRow( int i ) const { int result=0; const Row & rowI=sparseData_[i]; if (rowI.begin()!=rowI.end()){ result=(*(--rowI.end())).first+1; } return result; } inline int nextColInRow(int i, int j) const { const Row & rowI=sparseData_[i]; typename Row::const_iterator it=rowI.find(j); if (it!=rowI.end()) it++; int result=j+1; if (it!=rowI.end()){ result=(*it).first; } return result; } }; }; } #endif
22.504587
94
0.618426
[ "vector" ]
dcad95a5ee56662761292346b40ccbeca3b43d4d
3,230
cpp
C++
src/frameworks/wilhelm/src/objects/CAudioPlayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
src/frameworks/wilhelm/src/objects/CAudioPlayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/wilhelm/src/objects/CAudioPlayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* * Copyright (C) 2010 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. */ /** \file CAudioPlayer.c AudioPlayer class */ #include "sles_allinclusive.h" /** \brief Hook called by Object::Realize when an audio player is realized */ SLresult CAudioPlayer_Realize(void *self, SLboolean async) { CAudioPlayer *thiz = (CAudioPlayer *) self; SLresult result = SL_RESULT_SUCCESS; #ifdef ANDROID result = android_audioPlayer_realize(thiz, async); #endif #ifdef USE_SNDFILE result = SndFile_Realize(thiz); #endif // At this point the channel count and sample rate might still be unknown, // depending on the data source and the platform implementation. // If they are unknown here, then they will be determined during prefetch. return result; } /** \brief Hook called by Object::Resume when an audio player is resumed */ SLresult CAudioPlayer_Resume(void *self, SLboolean async) { return SL_RESULT_SUCCESS; } /** \brief Hook called by Object::Destroy when an audio player is destroyed */ void CAudioPlayer_Destroy(void *self) { CAudioPlayer *thiz = (CAudioPlayer *) self; #ifdef ANDROID android_audioPlayer_destroy(thiz); #endif freeDataLocatorFormat(&thiz->mDataSource); freeDataLocatorFormat(&thiz->mDataSink); #ifdef USE_SNDFILE SndFile_Destroy(thiz); #endif } /** \brief Hook called by Object::Destroy before an audio player is about to be destroyed */ predestroy_t CAudioPlayer_PreDestroy(void *self) { CAudioPlayer *thiz = (CAudioPlayer *) self; #ifdef ANDROID android_audioPlayer_preDestroy(thiz); #endif #ifdef USE_OUTPUTMIXEXT // Safe to proceed immediately if a track has not yet been assigned Track *track = thiz->mTrack; if (NULL == track) { return predestroy_ok; } CAudioPlayer *audioPlayer = track->mAudioPlayer; if (NULL == audioPlayer) { return predestroy_ok; } assert(audioPlayer == thiz); // Request the mixer thread to unlink this audio player's track thiz->mDestroyRequested = true; while (thiz->mDestroyRequested) { object_cond_wait(self); } // Mixer thread has acknowledged the request #endif return predestroy_ok; } /** \brief Given an audio player, return its data sink, which is guaranteed to be a non-NULL output * mix. This function is used by effect send. */ COutputMix *CAudioPlayer_GetOutputMix(CAudioPlayer *audioPlayer) { assert(NULL != audioPlayer); assert(SL_DATALOCATOR_OUTPUTMIX == audioPlayer->mDataSink.mLocator.mLocatorType); SLObjectItf outputMix = audioPlayer->mDataSink.mLocator.mOutputMix.outputMix; assert(NULL != outputMix); return (COutputMix *) outputMix; }
28.839286
99
0.725077
[ "object" ]
dcadaeb56f78fc132e21256e45e8a8766ea46f1e
2,261
cpp
C++
dialog_project_list.cpp
corsotechnology/drd-replicator-sym
958bb39263b5669006af08b149c70846f315c569
[ "BSD-3-Clause" ]
1
2021-07-26T13:06:17.000Z
2021-07-26T13:06:17.000Z
dialog_project_list.cpp
corsotechnology/drd-replicator-sym
958bb39263b5669006af08b149c70846f315c569
[ "BSD-3-Clause" ]
null
null
null
dialog_project_list.cpp
corsotechnology/drd-replicator-sym
958bb39263b5669006af08b149c70846f315c569
[ "BSD-3-Clause" ]
null
null
null
#include "dialog_project_list.h" #include "ui_dialog_project_list.h" #include <QMessageBox> #include <QSqlError> #include <QSqlQueryModel> #include <QTimer> Dialog_project_list::Dialog_project_list(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog_project_list) { ui->setupUi(this); QAction *sup_pro = new QAction(this); sup_pro->setText("Remove project"); connect(sup_pro, &QAction::triggered, this, &Dialog_project_list::Sup_project); ui->tableView->addAction(sup_pro); db = QSqlDatabase::addDatabase("QSQLITE","CHILD-"+QVariant(rand()+rand()).toString()); db.setDatabaseName("projects.db"); if (!db.open()) { QMessageBox::information(this,"Projects DB-Error",db.lastError().text()); close(); } QTimer::singleShot(300,this,SLOT(Display_projects())); } Dialog_project_list::~Dialog_project_list() { delete ui; } void Dialog_project_list::Display_projects() { QSqlQueryModel *mdl = new QSqlQueryModel(); mdl->setQuery("select name from project;",db); ui->tableView->setModel(mdl); ui->tableView->setColumnWidth(0,ui->tableView->width()); } void Dialog_project_list::Sup_project() { QItemSelectionModel *selectionmodel = ui->tableView->selectionModel(); QModelIndexList indexes = selectionmodel->selectedIndexes(); QModelIndex index; if (indexes.isEmpty())return; int row=0; foreach(index, indexes)row = index.row(); QAbstractItemModel *mdl = ui->tableView->model(); QString pro_name = mdl->index(row,0,QModelIndex()).data(Qt::EditRole).toString(); QSqlQuery qr(db); qr.prepare("delete from project where name = :name;"); qr.bindValue(":name",pro_name); if (!qr.exec()) { QMessageBox::information(this,"Projects DB-Error",qr.lastError().text()); return; } Display_projects(); } void Dialog_project_list::on_pushButton_exit_clicked() { is_exit = true; db.close(); close(); } void Dialog_project_list::on_tableView_doubleClicked(const QModelIndex &index) { selected_pro=index.data(Qt::EditRole).toString(); close(); } void Dialog_project_list::on_pushButton_new_clicked() { Dialog_new_project dl(this); dl.exec(); Display_projects(); }
28.2625
90
0.684211
[ "model" ]
dcadfa07a66ef1138c9fb82c39a848b99a1d72e6
7,707
cpp
C++
pxr/usd/lib/usdGeom/pointBased.cpp
WD-stefaang/USD
9a827fc4687bd09b15688437324d51141825d6f0
[ "Unlicense" ]
1
2018-01-27T23:21:57.000Z
2018-01-27T23:21:57.000Z
pxr/usd/lib/usdGeom/pointBased.cpp
WD-stefaang/USD
9a827fc4687bd09b15688437324d51141825d6f0
[ "Unlicense" ]
null
null
null
pxr/usd/lib/usdGeom/pointBased.cpp
WD-stefaang/USD
9a827fc4687bd09b15688437324d51141825d6f0
[ "Unlicense" ]
1
2019-10-04T21:57:06.000Z
2019-10-04T21:57:06.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdGeom/pointBased.h" #include "pxr/usd/usd/schemaRegistry.h" #include "pxr/usd/usd/typed.h" #include "pxr/usd/sdf/types.h" #include "pxr/usd/sdf/assetPath.h" PXR_NAMESPACE_OPEN_SCOPE // Register the schema with the TfType system. TF_REGISTRY_FUNCTION(TfType) { TfType::Define<UsdGeomPointBased, TfType::Bases< UsdGeomGprim > >(); } /* virtual */ UsdGeomPointBased::~UsdGeomPointBased() { } /* static */ UsdGeomPointBased UsdGeomPointBased::Get(const UsdStagePtr &stage, const SdfPath &path) { if (!stage) { TF_CODING_ERROR("Invalid stage"); return UsdGeomPointBased(); } return UsdGeomPointBased(stage->GetPrimAtPath(path)); } /* virtual */ UsdSchemaType UsdGeomPointBased::_GetSchemaType() const { return UsdGeomPointBased::schemaType; } /* static */ const TfType & UsdGeomPointBased::_GetStaticTfType() { static TfType tfType = TfType::Find<UsdGeomPointBased>(); return tfType; } /* static */ bool UsdGeomPointBased::_IsTypedSchema() { static bool isTyped = _GetStaticTfType().IsA<UsdTyped>(); return isTyped; } /* virtual */ const TfType & UsdGeomPointBased::_GetTfType() const { return _GetStaticTfType(); } UsdAttribute UsdGeomPointBased::GetPointsAttr() const { return GetPrim().GetAttribute(UsdGeomTokens->points); } UsdAttribute UsdGeomPointBased::CreatePointsAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdGeomTokens->points, SdfValueTypeNames->Point3fArray, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute UsdGeomPointBased::GetVelocitiesAttr() const { return GetPrim().GetAttribute(UsdGeomTokens->velocities); } UsdAttribute UsdGeomPointBased::CreateVelocitiesAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdGeomTokens->velocities, SdfValueTypeNames->Vector3fArray, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute UsdGeomPointBased::GetNormalsAttr() const { return GetPrim().GetAttribute(UsdGeomTokens->normals); } UsdAttribute UsdGeomPointBased::CreateNormalsAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(UsdGeomTokens->normals, SdfValueTypeNames->Normal3fArray, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } namespace { static inline TfTokenVector _ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right) { TfTokenVector result; result.reserve(left.size() + right.size()); result.insert(result.end(), left.begin(), left.end()); result.insert(result.end(), right.begin(), right.end()); return result; } } /*static*/ const TfTokenVector& UsdGeomPointBased::GetSchemaAttributeNames(bool includeInherited) { static TfTokenVector localNames = { UsdGeomTokens->points, UsdGeomTokens->velocities, UsdGeomTokens->normals, }; static TfTokenVector allNames = _ConcatenateAttributeNames( UsdGeomGprim::GetSchemaAttributeNames(true), localNames); if (includeInherited) return allNames; else return localNames; } PXR_NAMESPACE_CLOSE_SCOPE // ===================================================================== // // Feel free to add custom code below this line. It will be preserved by // the code generator. // // Just remember to wrap code in the appropriate delimiters: // 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'. // ===================================================================== // // --(BEGIN CUSTOM CODE)-- #include "pxr/usd/usdGeom/boundableComputeExtent.h" #include "pxr/base/tf/registryManager.h" PXR_NAMESPACE_OPEN_SCOPE TfToken UsdGeomPointBased::GetNormalsInterpolation() const { // Because normals is a builtin, we don't need to check validity // of the attribute before using it TfToken interp; if (GetNormalsAttr().GetMetadata(UsdGeomTokens->interpolation, &interp)){ return interp; } return UsdGeomTokens->vertex; } bool UsdGeomPointBased::SetNormalsInterpolation(TfToken const &interpolation) { if (UsdGeomPrimvar::IsValidInterpolation(interpolation)){ return GetNormalsAttr().SetMetadata(UsdGeomTokens->interpolation, interpolation); } TF_CODING_ERROR("Attempt to set invalid interpolation " "\"%s\" for normals attr on prim %s", interpolation.GetText(), GetPrim().GetPath().GetString().c_str()); return false; } bool UsdGeomPointBased::ComputeExtent(const VtVec3fArray& points, VtVec3fArray* extent) { // Create Sized Extent extent->resize(2); // Calculate bounds GfRange3d bbox; TF_FOR_ALL(pointsItr, points) { bbox.UnionWith(*pointsItr); } (*extent)[0] = GfVec3f(bbox.GetMin()); (*extent)[1] = GfVec3f(bbox.GetMax()); return true; } bool UsdGeomPointBased::ComputeExtent(const VtVec3fArray& points, const GfMatrix4d& transform, VtVec3fArray* extent) { // Create Sized Extent extent->resize(2); // Calculate bounds GfRange3d bbox; TF_FOR_ALL(pointsItr, points) { GfVec3f point = *pointsItr; point = transform.Transform(point); bbox.UnionWith(point); } (*extent)[0] = GfVec3f(bbox.GetMin()); (*extent)[1] = GfVec3f(bbox.GetMax()); return true; } static bool _ComputeExtentForPointBased( const UsdGeomBoundable& boundable, const UsdTimeCode& time, const GfMatrix4d* transform, VtVec3fArray* extent) { const UsdGeomPointBased pointBased(boundable); if (!TF_VERIFY(pointBased)) { return false; } VtVec3fArray points; if (!pointBased.GetPointsAttr().Get(&points, time)) { return false; } if (transform) { return UsdGeomPointBased::ComputeExtent(points, *transform, extent); } else { return UsdGeomPointBased::ComputeExtent(points, extent); } } TF_REGISTRY_FUNCTION(UsdGeomBoundable) { UsdGeomRegisterComputeExtentFunction<UsdGeomPointBased>( _ComputeExtentForPointBased); } PXR_NAMESPACE_CLOSE_SCOPE
27.042105
94
0.667964
[ "transform" ]
dcae29f2c5903a38ffa150df2795875ffef1d727
2,036
cxx
C++
src/Cxx/PolyData/PolyDataPointNormals.cxx
cvandijck/VTKExamples
b6bb89414522afc1467be8a1f0089a37d0c16883
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/PolyData/PolyDataPointNormals.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/PolyData/PolyDataPointNormals.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkCellData.h> #include <vtkCellArray.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> int main(int, char *[]) { ///////// Set Point Normals /////////// // Create 3 points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(1.0, 0.0, 0.0); points->InsertNextPoint(0.0, 0.0, 0.0); points->InsertNextPoint(0.0, 1.0, 0.0); // Add the points to a polydata vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New(); polydata->SetPoints(points); // Set point normals vtkSmartPointer<vtkDoubleArray> pointNormalsArray = vtkSmartPointer<vtkDoubleArray>::New(); pointNormalsArray->SetNumberOfComponents(3); //3d normals (ie x,y,z) pointNormalsArray->SetNumberOfTuples(polydata->GetNumberOfPoints()); // Construct the normal vectors double pN1[3] = {1.0, 0.0, 0.0}; double pN2[3] = {0.0, 1.0, 0.0}; double pN3[3] = {0.0, 0.0, 1.0}; // Add the data to the normals array pointNormalsArray->SetTuple(0, pN1) ; pointNormalsArray->SetTuple(1, pN2) ; pointNormalsArray->SetTuple(2, pN3) ; // Add the normals to the points in the polydata polydata->GetPointData()->SetNormals(pointNormalsArray); ///////// Get Point Normals /////////// vtkSmartPointer<vtkDoubleArray> pointNormalsRetrieved = dynamic_cast<vtkDoubleArray*>(polydata->GetPointData()->GetNormals()); if(pointNormalsRetrieved) { std::cout << "There are " << pointNormalsRetrieved->GetNumberOfTuples() << " point normals." << std::endl; for(vtkIdType i = 0; i < pointNormalsRetrieved->GetNumberOfTuples(); i++) { double pN[3]; pointNormalsRetrieved->GetTuple(i, pN); std::cout << "Point normal " << i << ": " << pN[0] << " " << pN[1] << " " << pN[2] << std::endl; } }//end if(pointNormalsRetrieved) else { std::cout << "No point normals." << std::endl; } return EXIT_SUCCESS; }
30.38806
77
0.651768
[ "3d" ]
dcaf7a7f7eaaf54e5e978d40ed065a71d4c8be54
33,150
cpp
C++
src/ssd_ftl.cpp
miuho/SSD-Flash-Translation-Layer
dc40fd00cfe89fb21ee9f5f92d99447a330b216c
[ "MIT" ]
13
2018-09-10T01:42:14.000Z
2021-12-16T07:11:46.000Z
src/ssd_ftl.cpp
miuho/SSD-Flash-Translation-Layer
dc40fd00cfe89fb21ee9f5f92d99447a330b216c
[ "MIT" ]
null
null
null
src/ssd_ftl.cpp
miuho/SSD-Flash-Translation-Layer
dc40fd00cfe89fb21ee9f5f92d99447a330b216c
[ "MIT" ]
10
2019-04-29T02:52:37.000Z
2022-03-26T13:58:34.000Z
/* Copyright 2009, 2010 Brendan Tauras */ /* ssd_ftl.cpp is part of FlashSim. */ /* FlashSim is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. */ /* FlashSim 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 FlashSim. If not, see <http://www.gnu.org/licenses/>. */ /****************************************************************************/ /* Ftl class * Brendan Tauras 2009-11-04 * * This class is a stub class for the user to use as a template for implementing * his/her FTL scheme. A few functions to gather information from lower-level * hardware are added to assist writing a FTL scheme. The Ftl class should * rely on the Garbage_collector and Wear_leveler classes for modularity and * simplicity. */ /* * @ssd_ftl.cpp * * HingOn Miu (hmiu) * Carnegie Mellon University * 2015-10-15 */ #include <new> #include <assert.h> #include <stdio.h> #include "ssd.h" #include <string> #include <tuple> #include <unordered_map> #include <vector> using namespace ssd; // total number of pages in raw capacity #define RAW_SIZE (SSD_SIZE * PACKAGE_SIZE * DIE_SIZE * PLANE_SIZE * BLOCK_SIZE) // total number of physical blocks #define NUM_OF_PHY_B (RAW_SIZE / BLOCK_SIZE) // total number of pages in overprovisioning #define OP_SIZE ((RAW_SIZE * OVERPROVISIONING) / 100) // total number of blocks in overprovisioning #define NUM_OF_OP_B (OP_SIZE / BLOCK_SIZE) // total number of pages in usable capacity #define USABLE_SIZE (RAW_SIZE - OP_SIZE) // total number of logical blocks #define NUM_OF_LGC_B ((unsigned int)(USABLE_SIZE / BLOCK_SIZE)) // total number of physical data blocks #define NUM_OF_DATA_B (NUM_OF_LGC_B) // track the emptiness of each logical page unsigned int *logical_to_emptiness; // track the number of erases for each log block unsigned int *erase_count; // track the mapping of logical blocks to physical blocks int *logical_to_physical; // track the mapping of physical data blocks to physical log blocks int *data_to_log; // track the pages in each physical log block std::unordered_map <unsigned long, std::string> log_to_pages; // store the start time of input event double start_time; // store the over-provisioning blocks std::vector<unsigned long> op_blocks; // record the current cleaning block unsigned long current_cln_address; /** * @brief Checks if the input logial address has been written */ bool check_page_empty(unsigned long lba) { // fetch the corresponding unsigned int unsigned int flag = logical_to_emptiness[lba / sizeof (unsigned int)]; // check the corresponding bit return (((flag >> (lba % sizeof(unsigned int))) & 1) == 0); } /** * @brief Flag the input logical address as written */ void set_page_written(unsigned long lba) { // fetch the corresponding unsigned int and set corresponding bit logical_to_emptiness[lba / sizeof (unsigned int)] |= (1 << (lba % sizeof(unsigned int))); } unsigned long check_physical_address(unsigned long logical_address) { unsigned page = logical_address % BLOCK_SIZE; int nth_logical_block = (int)(logical_address / BLOCK_SIZE); int offset = logical_to_physical[nth_logical_block]; int nth_physical_block = nth_logical_block + offset; return page + ((unsigned long)nth_physical_block) * BLOCK_SIZE; } void set_physical_address(unsigned long logical_address, unsigned long physical_address) { int nth_logical_block = (int)(logical_address / BLOCK_SIZE); int nth_physical_block = (int)(physical_address / BLOCK_SIZE); logical_to_physical[nth_logical_block] = (nth_physical_block - nth_logical_block); } bool check_log_block(unsigned long data_address, unsigned long *log_address) { unsigned page = data_address % BLOCK_SIZE; int nth_data_block = (int)(data_address / BLOCK_SIZE); int offset = data_to_log[nth_data_block]; if (offset == 0) // data block to log block mapping cannot be 0 return false; int nth_log_block = nth_data_block + offset; *log_address = page + ((unsigned long)nth_log_block) * BLOCK_SIZE; return true; } void set_log_block(unsigned long data_address, unsigned long log_address) { int nth_data_block = (int)(data_address / BLOCK_SIZE); int nth_log_block = (int)(log_address / BLOCK_SIZE); data_to_log[nth_data_block] = (nth_log_block - nth_data_block); } void cancel_log_block(unsigned long data_address) { unsigned long log_address; if (check_log_block(data_address, &log_address)) { if (log_to_pages.find(log_address) != log_to_pages.end()) { log_to_pages.erase(log_address); } } // this will clear the offset to 0 set_log_block(data_address, data_address); } /** * @brief Fetch the most recent copy of the page in log block * corresponding to the page in data block */ bool fetch_log_page(std::string offsets, unsigned int data_page, unsigned int *log_page) { if (offsets == "") { return false; } // find the position of the last occurance of data_page // check locations beside the first page size_t loc = offsets.rfind("," + std::to_string((long long)data_page) + ","); // found nothing in locations beside the first page if (loc == std::string::npos) { // check the first page of overprovision block loc = offsets.find(std::to_string((long long)data_page) + ","); // found in the first page if (loc == 0) { *log_page = 0; return true; } // found nothing in first page and rest of pages return false; } // found the page (not the first page) // count the index of this page unsigned int count = 0; size_t index = offsets.find(","); while (index != loc) { count++; index++; index = offsets.find(",", index); } *log_page = count + 1; return true; } /** * @brief Find the next free page in log block */ bool next_free_log_page(std::string offsets, unsigned int *page) { unsigned int count = 0; size_t loc = offsets.find(","); while (loc != std::string::npos) { count++; loc++; loc = offsets.find(",", loc); } if (count >= BLOCK_SIZE) { // no more empty pages in log block return false; } *page = count; //fprintf(log_file, return true; } void Ftl::print_info(void) { int count = 0; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { //unsigned long data_address = check_physical_address(i * BLOCK_SIZE); bool non_empty = false; for (unsigned int j = 0; j < BLOCK_SIZE; j++) { if (!check_page_empty(i * BLOCK_SIZE + j)) { non_empty = true; break; } } if (non_empty == false) { count++; } } fprintf(log_file, "%d empty data blocks\n", count); for (unsigned int i = 0; i <= BLOCK_ERASES; i++) { int sum = 0; for (unsigned int logical_b = 0; logical_b < NUM_OF_LGC_B; logical_b++) { unsigned long data_address = check_physical_address(logical_b * BLOCK_SIZE); if (erase_count[data_address / BLOCK_SIZE] == i) { sum++; } } fprintf(log_file, "%d data blocks have %u erases\n", sum, i); } fprintf(log_file, "total # of op blocks %d\n", (int)NUM_OF_OP_B); fprintf(log_file, "free op blocks left %d\n", op_blocks.size()); int big_sum = 0; for (unsigned int i = 0; i <= BLOCK_ERASES; i++) { int sum = 0; for (unsigned int logical_b = 0; logical_b < NUM_OF_LGC_B; logical_b++) { unsigned long data_address = check_physical_address(logical_b * BLOCK_SIZE); unsigned long log_address; if (check_log_block(data_address, &log_address)) { if (erase_count[log_address / BLOCK_SIZE] == i) { sum++; } } } fprintf(log_file, "%d log blocks have %u erases\n", sum, i); big_sum += sum; } if ((unsigned int)big_sum != log_to_pages.size()) fprintf(log_file, "wrong\n"); fprintf(log_file, "log blocks used %d\n", big_sum); } /** * @brief Check if the block exceeds erase limit */ bool over_erase_limit(unsigned long physical_address) { return (erase_count[physical_address / BLOCK_SIZE] >= BLOCK_ERASES); } /** * @brief Update the erase count for a block */ void update_erase_count(unsigned long physical_address) { (erase_count[physical_address / BLOCK_SIZE]) += 1; } bool find_empty_data_block_for_cleaning(unsigned long *empty_data_address) { unsigned int min_count = BLOCK_ERASES + 1; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { unsigned long data_address = check_physical_address(i * BLOCK_SIZE); bool non_empty = false; for (unsigned int j = 0; j < BLOCK_SIZE; j++) { if (!check_page_empty(i * BLOCK_SIZE + j)) { non_empty = true; break; } } unsigned int count = erase_count[data_address / BLOCK_SIZE]; if (non_empty == false && count < min_count && count < BLOCK_ERASES) { min_count = count; *empty_data_address = data_address; } } return (min_count != BLOCK_ERASES + 1); } bool find_empty_data_block_for_remapping(unsigned long *empty_data_address, unsigned long *empty_logical_block) { unsigned int min_count = BLOCK_ERASES + 1; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { unsigned long data_address = check_physical_address(i * BLOCK_SIZE); bool non_empty = false; for (unsigned int j = 0; j < BLOCK_SIZE; j++) { if (!check_page_empty(i * BLOCK_SIZE + j)) { non_empty = true; break; } } unsigned int count = erase_count[data_address / BLOCK_SIZE]; if (non_empty == false && count < min_count && count < BLOCK_ERASES) { min_count = count; *empty_logical_block = i * BLOCK_SIZE; *empty_data_address = data_address; } } return (min_count != BLOCK_ERASES + 1); } /** * @brief Returns the numerical mapping from physical address to SSD address */ void map_physical_to_SSD(unsigned long phy, unsigned int *package, unsigned int *die, unsigned int *plane, unsigned int *block, unsigned int *page) { *package = ((((phy / BLOCK_SIZE) / PLANE_SIZE ) / DIE_SIZE) / PACKAGE_SIZE) % SSD_SIZE; *die = (((phy / BLOCK_SIZE) / PLANE_SIZE ) / DIE_SIZE) % PACKAGE_SIZE; *plane = ((phy / BLOCK_SIZE) / PLANE_SIZE ) % DIE_SIZE; *block = (phy / BLOCK_SIZE) % PLANE_SIZE; *page = phy % BLOCK_SIZE; } bool Garbage_collector::shuffle_data_log(void) { // find a log/data block pair with at most BLOCK_ERASES - 1 erases unsigned int max_count = 0; unsigned long max_erase_log = RAW_SIZE; unsigned long max_erase_data = RAW_SIZE; for (unsigned int i = 0; i < NUM_OF_PHY_B; i++) { unsigned long log_address; unsigned long data_address = i * BLOCK_SIZE; if (check_log_block(data_address, &log_address)) { unsigned int log_count = erase_count[log_address / BLOCK_SIZE]; unsigned int data_count = erase_count[data_address / BLOCK_SIZE]; if (log_count != BLOCK_ERASES && data_count != BLOCK_ERASES && (log_count + data_count) >= max_count) { max_erase_log = log_address; max_erase_data = data_address; max_count = (log_count + data_count); } } } if (max_erase_data == RAW_SIZE || max_erase_log == RAW_SIZE) return false; // find the corresponding logical block unsigned long logical_block = RAW_SIZE; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { unsigned long logical_address = i * BLOCK_SIZE; unsigned long to_match = check_physical_address(logical_address); if (to_match == max_erase_data) { logical_block = logical_address; break; } } if (logical_block == RAW_SIZE) return false; // find a data block (unmapped to log block) with the fewest erases unsigned int min_count = BLOCK_ERASES + 1; unsigned long min_erase_data = RAW_SIZE; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { unsigned long logical_address = i * BLOCK_SIZE; unsigned long data_address = check_physical_address(logical_address); unsigned long dummy; // make sure the data block has no log block mapped if (!check_log_block(data_address, &dummy)) { unsigned int count = erase_count[data_address / BLOCK_SIZE]; if (count < min_count) { min_erase_data = data_address; min_count = count; } } } if (min_erase_data == RAW_SIZE) return false; if (min_count >= BLOCK_ERASES - 1) return false; // free up the log block if (clean(logical_block, max_erase_data, max_erase_log) == false) return false; cancel_log_block(max_erase_data); // find the corresponding logical block logical_block = RAW_SIZE; for (unsigned int i = 0; i < NUM_OF_LGC_B; i++) { unsigned long logical_address = i * BLOCK_SIZE; unsigned long to_match = check_physical_address(logical_address); if (to_match == min_erase_data) { logical_block = logical_address; break; } } if (logical_block == RAW_SIZE) return false; unsigned int package; unsigned int die; unsigned int plane; unsigned int block; unsigned int dummy; // move pages from data block to log block for (unsigned int i = 0; i < BLOCK_SIZE; i++) { // move the page if only it is a written page if (!check_page_empty(logical_block + i)) { map_physical_to_SSD(min_erase_data, &package, &die, &plane, &block, &dummy); Address src_addr = Address(package, die, plane, block, i, PAGE); Event read_event = Event(READ, logical_block + i, 1, start_time); read_event.set_address(src_addr); ftl.controller.issue(read_event); map_physical_to_SSD(max_erase_log, &package, &die, &plane, &block, &dummy); Event write_event = Event(WRITE, logical_block + i, 1, start_time); Address des_addr = Address(package, die, plane, block, i, PAGE); write_event.set_address(des_addr); ftl.controller.issue(write_event); } } // erase data block map_physical_to_SSD(min_erase_data, &package, &die, &plane, &block, &dummy); Address data_addr = Address(package, die, plane, block, 0, BLOCK); Event erase_data_event = Event(ERASE, logical_block, 1, start_time); erase_data_event.set_address(data_addr); ftl.controller.issue(erase_data_event); // now the data block becomes new unmapped log block, and the log // block becomes the data block set_physical_address(logical_block, max_erase_log); op_blocks.push_back(min_erase_data); fprintf(log_file, "[shuffle_data_log] log block %lu <-> data block %lu\n", max_erase_log, min_erase_data); return true; } /** * @brief Find next unmapped log block */ bool Garbage_collector::next_unmapped_log_block(unsigned long *log_address, unsigned int *package, unsigned int *die, unsigned int *plane, unsigned int *block) { if (op_blocks.empty()) { if (shuffle_data_log() == false) return false; } unsigned int i = 0; while (i < op_blocks.size()) { *log_address = op_blocks[op_blocks.size() - 1 - i]; unsigned int dummy; map_physical_to_SSD(*log_address, package, die, plane, block, &dummy); op_blocks.pop_back(); if (!over_erase_limit(*log_address)) return true; i++; } return false; } /** * @brief Find the cleaning block to use */ bool next_unmapped_cln_block(unsigned long *cln_address) { return false; /* if (over_erase_limit(current_cln_address)) { if (op_blocks.empty()) { if (find_empty_data_block_for_cleaning(cln_address) == true) return true; return false; } *cln_address = op_blocks[op_blocks.size() - 1]; current_cln_address = *cln_address; op_blocks.pop_back(); return true; } else { *cln_address = current_cln_address; return true; }*/ } unsigned long Garbage_collector::remap_data_block(unsigned long logical_block, unsigned long old_data_pba, unsigned long log_pba) { unsigned int package; unsigned int die; unsigned int plane; unsigned int block; unsigned int dummy; unsigned long new_data_pba; unsigned long new_logical_block = RAW_SIZE; // check if a block available if (find_empty_data_block_for_remapping(&new_data_pba, &new_logical_block) == false) { fprintf(log_file, "[remap_data_block] no empty data block left\n"); if (next_unmapped_log_block(&new_data_pba, &package, &die, &plane, &block) == false) { fprintf(log_file, "[remap_data_block] no log block left\n"); return log_pba; } } // copy pages from old data block to new data block std::unordered_map<unsigned long, std::string>::const_iterator log_pages = log_to_pages.find(log_pba); for (unsigned int i = 0; i < BLOCK_SIZE; i++) { // move the page if only it is a written page if (!check_page_empty(logical_block + i)) { // find if the latest copy unsigned int log_page; if (!fetch_log_page(log_pages->second, i, &log_page)) { // read from latest copy of page in data block map_physical_to_SSD(old_data_pba, &package, &die, &plane, &block, &dummy); Address src_addr = Address(package, die, plane, block, i, PAGE); Event read_event = Event(READ, logical_block + i, 1, start_time); read_event.set_address(src_addr); ftl.controller.issue(read_event); map_physical_to_SSD(new_data_pba, &package, &die, &plane, &block, &dummy); Event write_event = Event(WRITE, logical_block + i, 1, start_time); Address des_addr = Address(package, die, plane, block, i, PAGE); write_event.set_address(des_addr); ftl.controller.issue(write_event); } } } fprintf(log_file, "[remap_data_block] moved pages to new data block\n"); if (new_logical_block != RAW_SIZE) set_physical_address(new_logical_block, old_data_pba); set_physical_address(logical_block, new_data_pba); set_log_block(old_data_pba, old_data_pba); set_log_block(new_data_pba, log_pba); return new_data_pba; } unsigned long Garbage_collector::remap_log_block(unsigned long logical_block, unsigned long data_pba, unsigned long old_log_pba) { unsigned int package; unsigned int die; unsigned int plane; unsigned int block; unsigned int dummy; unsigned long new_log_pba; // check if a unmapped log block available if (next_unmapped_log_block(&new_log_pba, &package, &die, &plane, &block) == false) { fprintf(log_file, "[remap_log_block] no log block left\n"); return data_pba; } // copy pages from old log block to new log block std::unordered_map<unsigned long, std::string>::const_iterator log_pages = log_to_pages.find(old_log_pba); int j = 0; std::string offsets = ""; for (unsigned int i = 0; i < BLOCK_SIZE; i++) { // move the page if only it is a written page if (!check_page_empty(logical_block + i)) { // find if the latest copy unsigned int log_page; if (fetch_log_page(log_pages->second, i, &log_page)) { // read from latest copy of page in log block map_physical_to_SSD(old_log_pba, &package, &die, &plane, &block, &dummy); Address src_addr = Address(package, die, plane, block, log_page, PAGE); Event read_event = Event(READ, logical_block + i, 1, start_time); read_event.set_address(src_addr); ftl.controller.issue(read_event); map_physical_to_SSD(new_log_pba, &package, &die, &plane, &block, &dummy); Event write_event = Event(WRITE, logical_block + i, 1, start_time); Address des_addr = Address(package, die, plane, block, j, PAGE); write_event.set_address(des_addr); ftl.controller.issue(write_event); j++; offsets += (std::to_string((long long)i) + ","); } } } fprintf(log_file, "[remap_log_block] moved pages to new log block\n"); cancel_log_block(data_pba); set_log_block(data_pba, new_log_pba); log_to_pages[new_log_pba] = offsets; return new_log_pba; } /** * @brief Move data to cleaning black and move back */ bool Garbage_collector::clean(unsigned long logical_block, unsigned long data_pba, unsigned long log_pba) { unsigned int package; unsigned int die; unsigned int plane; unsigned int block; unsigned int dummy; unsigned long cln_pba; // calculate log block map_physical_to_SSD(log_pba, &package, &die, &plane, &block, &dummy); Address log_addr = Address(package, die, plane, block, 0, BLOCK); // calculate data block map_physical_to_SSD(data_pba, &package, &die, &plane, &block, &dummy); Address data_addr = Address(package, die, plane, block, 0, BLOCK); // check if a unmapped cleaning block available if (find_empty_data_block_for_cleaning(&cln_pba) == false) { fprintf(log_file, "[clean] no empty data block left\n"); //if (next_unmapped_cln_block(&cln_pba) == false) { // no free cleaning block // fprintf(log_file, "[clean] no cleaning block left\n"); return false; //} } fprintf(log_file, "[clean] data block %lu, log block %lu\n", data_pba, log_pba); // calculate cleaning block map_physical_to_SSD(cln_pba, &package, &die, &plane, &block, &dummy); Address cln_addr = Address(package, die, plane, block, 0, BLOCK); // copy live pages from data block and log block to cleaning block std::unordered_map<unsigned long, std::string>::const_iterator log_pages = log_to_pages.find(log_pba); for (unsigned int i = 0; i < BLOCK_SIZE; i++) { // move the page if only it is a written page if (!check_page_empty(logical_block + i)) { // find if the latest copy unsigned int log_page; Address src_addr; if (fetch_log_page(log_pages->second, i, &log_page)) { // read from latest copy of page in log block map_physical_to_SSD(log_pba, &package, &die, &plane, &block, &dummy); src_addr = Address(package, die, plane, block, log_page, PAGE); } else { // read from latest copy in data block map_physical_to_SSD(data_pba, &package, &die, &plane, &block, &dummy); src_addr = Address(package, die, plane, block, i, PAGE); } Event read_event = Event(READ, logical_block + i, 1, start_time); read_event.set_address(src_addr); ftl.controller.issue(read_event); Event write_event = Event(WRITE, logical_block + i, 1, start_time); map_physical_to_SSD(cln_pba, &package, &die, &plane, &block, &dummy); Address des_addr = Address(package, die, plane, block, i, PAGE); write_event.set_address(des_addr); ftl.controller.issue(write_event); } } // erase data block Event erase_data_event = Event(ERASE, logical_block, 1, start_time); erase_data_event.set_address(data_addr); ftl.controller.issue(erase_data_event); // erase log block Event erase_log_event = Event(ERASE, logical_block, 1, start_time); erase_log_event.set_address(log_addr); ftl.controller.issue(erase_log_event); // copy live pages from cleaning block to data block for (unsigned int i = 0; i < BLOCK_SIZE; i++) { // move the page if only it is a written page if (!check_page_empty(logical_block + i)) { Event read_event = Event(READ, logical_block + i, 1, start_time); map_physical_to_SSD(cln_pba, &package, &die, &plane, &block, &dummy); Address src_addr = Address(package, die, plane, block, i, PAGE); read_event.set_address(src_addr); ftl.controller.issue(read_event); Event write_event = Event(WRITE, logical_block + i, 1, start_time); map_physical_to_SSD(data_pba, &package, &die, &plane, &block, &dummy); Address des_addr = Address(package, die, plane, block, i, PAGE); write_event.set_address(des_addr); ftl.controller.issue(write_event); } } // erase cleaning block Event erase_cln_event = Event(ERASE, logical_block, 1, start_time); erase_cln_event.set_address(cln_addr); ftl.controller.issue(erase_cln_event); // update erase counts update_erase_count(data_pba); update_erase_count(log_pba); update_erase_count(cln_pba); return true; } void Ftl::init_ftl_user() { // initialize the bit checking emptiness array unsigned int emp_len = (USABLE_SIZE + sizeof(unsigned int) - 1) / sizeof(unsigned int); // 0 bit for empty, 1 bit for written logical_to_emptiness = new unsigned int [emp_len](); // initialize erases count for all physical blocks erase_count = new unsigned int [NUM_OF_PHY_B](); // initialize offset mapping table from logical block to physical block logical_to_physical = new int [NUM_OF_LGC_B](); // initialize offset mapping table from physical data block to physical log block data_to_log = new int [NUM_OF_PHY_B](); // initialize a cleaning block //current_cln_address = USABLE_SIZE; // initialize the list of overprovisioning blocks for (unsigned int i = USABLE_SIZE; i < RAW_SIZE; i += BLOCK_SIZE) { op_blocks.push_back(i); } } enum status Ftl::translate( Event &event ){ unsigned int package; unsigned int die; unsigned int plane; unsigned int block; unsigned int page; unsigned long data_address; unsigned long log_address; unsigned long logical_address; unsigned long physical_address; logical_address = event.get_logical_address(); fprintf(log_file, "[translate] input LBA: %lu *******************************\n", logical_address); //print_info(); // legal logical address is only from 0 to USABLE_SIZE - 1 if (logical_address >= USABLE_SIZE) { fprintf(log_file, "[translate] LBA not assessible\n"); return FAILURE; } // set start time start_time = event.get_start_time(); // find the physical address physical_address = check_physical_address(logical_address); map_physical_to_SSD(physical_address, &package, &die, &plane, &block, &page); fprintf(log_file, "[translate] original mapping is (%u,%u,%u,%u,%u)\n", package, die, plane, block, page); // find the physical data block address data_address = physical_address - page; fprintf(log_file, "[translate] data block address is %lu\n", data_address); enum event_type operation = event.get_event_type(); if (operation == WRITE) { // check if page is empty if (check_page_empty(logical_address)) { set_page_written(logical_address); // original translation Address pba = Address(package, die, plane, block, page, PAGE); event.set_address(pba); fprintf(log_file, "[translate] wrote to an empty page\n"); return SUCCESS; } // check if log block mapped to data block if (check_log_block(data_address, &log_address)) { fprintf(log_file, "[translate] data block %lu maps to log block %lu\n", data_address, log_address); // check if there is a empty page in log block std::unordered_map<unsigned long, std::string>::const_iterator log_pages = log_to_pages.find(log_address); unsigned int log_page; if (next_free_log_page(log_pages->second, &log_page)) { log_to_pages[log_address] = log_pages->second + std::to_string((long long)page) + ","; fprintf(log_file, "[translate] log block pba %lu contains %s\n", log_address, log_to_pages[log_address].c_str()); map_physical_to_SSD(log_address, &package, &die, &plane, &block, &page); // logging translation Address pba = Address(package, die, plane, block, log_page, PAGE); event.set_address(pba); return SUCCESS; } fprintf(log_file, "[translate] mapped log block has no free page\n"); // this data block needs cleaning if (over_erase_limit(data_address) == true) { data_address = garbage.remap_data_block(logical_address - page, data_address, log_address); if (log_address == data_address) { fprintf(log_file, "[translate] data block remapping failed\n"); return FAILURE; } } // this log block needs cleaning if (over_erase_limit(log_address) == true) { log_address = garbage.remap_log_block(logical_address - page, data_address, log_address); if (log_address == data_address) { fprintf(log_file, "[translate] log block remapping failed\n"); return FAILURE; } } if (garbage.clean(logical_address - page, data_address, log_address) == false) { fprintf(log_file, "[translate] cleaning failed\n"); return FAILURE; } // give the first page of this cleaned log block std::string offsets = std::to_string((long long) page) + ","; log_to_pages[log_address] = offsets; fprintf(log_file, "[translate] after cleaning, log block %lu contains %s\n", log_address, offsets.c_str()); map_physical_to_SSD(log_address, &package, &die, &plane, &block, &page); // logging translation Address pba = Address(package, die, plane, block, 0, PAGE); event.set_address(pba); return SUCCESS; } // check if there is a free log block if (garbage.next_unmapped_log_block(&log_address, &package, &die, &plane, &block)) { fprintf(log_file, "[translate] found free log block (%u,%u,%u,%u,0)\n", package, die, plane, block); // map log block to data block set_log_block(data_address, log_address); std::string offsets = std::to_string((long long) page) + ","; log_to_pages.insert({{log_address, offsets}}); fprintf(log_file, "[translate] log block pba %lu contains %s\n", log_address, offsets.c_str()); // logging translation Address pba = Address(package, die, plane, block, 0, PAGE); event.set_address(pba); return SUCCESS; } fprintf(log_file, "[translate] fail to rotate log blocks\n"); return FAILURE; } if (operation == READ) { // check if page is valid if (check_page_empty(logical_address)) { fprintf(log_file, "[translate] read a empty page\n"); return FAILURE; } // check if log block mapped to data block if (check_log_block(data_address, &log_address)) { fprintf(log_file, "[translate] data block %lu maps to log block %lu\n", data_address, log_address); // check if there is a corresponding page in log block std::unordered_map<unsigned long, std::string>::const_iterator log_pages = log_to_pages.find(log_address); fprintf(log_file, "[translate] log block %lu contains %s\n", log_address, log_pages->second.c_str()); unsigned int log_page; if (fetch_log_page(log_pages->second, page, &log_page)) { // read from recent copy of page in log block map_physical_to_SSD(log_address, &package, &die, &plane, &block, &page); Address pba = Address(package, die, plane, block, log_page, PAGE); event.set_address(pba); fprintf(log_file, "[translate] reading page %u in log block\n", log_page); return SUCCESS; } } // read from original calculated page Address pba = Address(package, die, plane, block, page, PAGE); event.set_address(pba); fprintf(log_file, "[translate] reading original data block page\n"); return SUCCESS; } fprintf(log_file, "[translate] unkown operation\n"); return FAILURE; } enum status Garbage_collector::collect(Event &event __attribute__((unused)), enum GC_POLICY policy __attribute__((unused))) { /* * No need to use this function */ return FAILURE; } enum status Wear_leveler::level( Event &event __attribute__((unused))) { /* * No need to use this function */ return FAILURE; }
37.373168
124
0.651885
[ "vector" ]
dcb2ae359b3743f93f45cfd98c26c19f1c447299
35,622
cpp
C++
client/mainwindow.cpp
KeltorHD/Client-Server-Application-Design-Patterns-Teaching
7461234f828ebfa900366f5a5f965b4aa0d02ce6
[ "MIT" ]
2
2021-05-26T08:47:27.000Z
2021-06-30T08:37:40.000Z
client/mainwindow.cpp
KeltorHD/Client-Server-Application-Design-Patterns-Teaching
7461234f828ebfa900366f5a5f965b4aa0d02ce6
[ "MIT" ]
null
null
null
client/mainwindow.cpp
KeltorHD/Client-Server-Application-Design-Patterns-Teaching
7461234f828ebfa900366f5a5f965b4aa0d02ce6
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" bool fileExists(QString path) { QFileInfo check_file(path); return check_file.exists() && check_file.isFile(); } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->popup = new Popup(this); this->test_widget = new Test_widget(this); this->ui->test_layout->addWidget(this->test_widget); this->validator = new QRegularExpressionValidator(QRegularExpression("[A-Za-z0-9_]+"), this); this->ui->reg_login->setValidator(this->validator); this->ui->reg_pas->setValidator(this->validator); if (!fileExists(QDir::currentPath() + "/connection.txt")) { QFile file("connection.txt"); file.open(QIODevice::WriteOnly | QIODevice::Text); file.write("localhost\n"); file.write("20002"); file.close(); } QFile file("connection.txt"); file.open(QIODevice::ReadOnly | QIODevice::Text); this->host = file.readLine(); this->host = this->host.simplified(); this->port = file.readLine().toInt(); file.close(); QDir dir1(QDir::currentPath()); dir1.mkdir("images"); QDir dir2(QDir::currentPath() + "/images"); dir2.mkdir("patterns"); for (size_t i = 0; i < this->test_widget->back.size(); i++) { connect(this->test_widget->back[i], &QPushButton::clicked, [this] { this->back_to_list(); }); } connect(this->test_widget->result_done, &QPushButton::clicked, [this] { this->check_test(); }); if (!fileExists(QDir::currentPath() + "/main.db")) { this->ui->screen_stacked->setCurrentIndex((int)screen::login); this->forward = type_forward::login; this->is_auth = false; this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); } else { this->is_auth = true; this->db = QSqlDatabase::addDatabase("QSQLITE"); this->db.setDatabaseName(QDir::currentPath() + "/main.db"); if (!this->db.open()) { qDebug() << this->db.lastError().text(); } this->fill_personal_area(); this->fill_result_test_form(); this->ui->screen_stacked->setCurrentIndex((int)screen::personal_area); } } MainWindow::~MainWindow() { QFile file("connection.txt"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) qDebug() << "not open to write!"; file.write(QString(this->host + "\n").toUtf8()); file.write(QString::number(this->port).toUtf8()); file.close(); delete ui; } void MainWindow::on_login_2_clicked() { if (!this->ui->login_lineEdit->text().size() || !this->ui->password_lineEdit->text().size()) return; this->send_auth(this->ui->login_lineEdit->text(), this->ui->password_lineEdit->text()); } void MainWindow::slotReadyRead() { if (this->msg_length == -1) { char buf[sizeof(int32_t)]{0}; this->socket->read(buf, sizeof(int32_t)); int32_t length; std::memcpy(&length, buf, sizeof(int32_t)); this->msg_length = length - 1; } if (this->socket->bytesAvailable() >= this->msg_length) { this->msg_length = -1; this->recv_data_handler(this->socket->readAll()); } } void MainWindow::slotError(QAbstractSocket::SocketError) { this->popup->set_title("Произошла ошибка"); this->popup->set_description("Ошибка соединения с сервером"); this->popup->exec(); if (this->forward == type_forward::login || this->forward == type_forward::registration) { this->socket->close(); socket->connectToHost(this->host, this->port); } } void MainWindow::slotConnected() { user_info_t info; switch (this->forward) { case (type_forward::login): case (type_forward::registration): this->ui->login_2->setEnabled(true); this->ui->register_2->setEnabled(true); break; case (type_forward::load_result): info = this->get_user_info(); this->send_auth(info.login, info.password); break; case (type_forward::upload_result): info = this->get_user_info(); this->send_test_result(info.login, info.password); break; case (type_forward::load_patterns): this->send_patterns_request(); break; } } void MainWindow::send(const QString &data) { int32_t length = int32_t(data.toUtf8().length()); length++; char buf[4]; std::memcpy(buf, &length, 4); this->socket->write(buf, 4); this->socket->write(data.toUtf8()); } //QString MainWindow::recv() //{ // char buf[sizeof(int32_t)]{0}; // this->socket->read(buf, sizeof(int32_t)); // int32_t length; // std::memcpy(&length, buf, sizeof(int32_t)); // qDebug() << "len buf: " <<length; // length--; // QString data; // while (1) // { // data.append(this->socket->readAll()); // if (data.size() >= length) // break; // } // qDebug() << data.length(); // return data; //} void MainWindow::create_db() { this->db = QSqlDatabase::addDatabase("QSQLITE"); this->db.setDatabaseName(QDir::currentPath() + "/main.db"); if (!this->db.open()) { qDebug() << this->db.lastError().text(); } QSqlQuery query; query.exec("CREATE TABLE Pattern ( " "id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT," "name VARCHAR(45) NOT NULL UNIQUE, " "description TEXT NOT NULL, " "code TEXT NOT NULL, " "path_to_image VARCHAR(256) NOT NULL); "); query.exec("CREATE TABLE Pattern_test ( " "pattern_name VARCHAR(45) NOT NULL, " "question TEXT NOT NULL, " "id_type INTEGER NOT NULL, " "a1 VARCHAR(45) NULL DEFAULT 'NULL', " "a2 VARCHAR(45) NULL DEFAULT 'NULL', " "a3 VARCHAR(45) NULL DEFAULT 'NULL', " "a4 VARCHAR(45) NULL DEFAULT 'NULL', " "correct_answer VARCHAR(45) NOT NULL); " ); query.exec("CREATE TABLE User ( " "login VARCHAR(45) NOT NULL UNIQUE, " "password VARCHAR(45) NOT NULL UNIQUE, " "path_to_image VARCHAR(256) NOT NULL UNIQUE);" ); query.exec("CREATE TABLE User_test ( " "pattern VARCHAR(45) NOT NULL UNIQUE, " "count_corrent INTEGER NOT NULL); " ); } void MainWindow::recv_data_handler(const QString &data) { try { tinyxml2::XMLDocument doc; // QString data = this->recv(); doc.Parse(data.toUtf8()); // qDebug() << data.size() << ", " << (doc.FirstChildElement("body") == nullptr); switch (this->forward) { case (type_forward::login): { auto type = doc.FirstChildElement("body")->FirstChildElement("answer"); if (type->GetText() == QString("correct")) { this->ui->screen_stacked->setCurrentIndex((int)screen::personal_area); this->create_db(); this->fill_db_login(doc.FirstChildElement("body")); this->fill_personal_area(); this->is_auth = true; this->socket.reset(); } else { throw "Неверный логин или пароль!"; } break; } case (type_forward::registration): { auto type = doc.FirstChildElement("body")->FirstChildElement("answer"); if (type->GetText() == QString("correct")) { this->ui->screen_stacked->setCurrentIndex((int)screen::personal_area); this->create_db(); this->fill_db_register(); this->fill_personal_area(); this->base64_file = ""; this->file_type = ""; this->is_auth = true; this->socket.reset(); } else { throw "Пользователь с таким логином уже существует!"; } break; } case (type_forward::load_result): { auto type = doc.FirstChildElement("body")->FirstChildElement("answer"); if (type->GetText() == QString("correct")) { this->fill_db_result_test(doc.FirstChildElement("body")); this->fill_result_test_form(); this->popup->set_title("Успешно"); this->popup->set_description("Данные успешно скачаны с сервера!"); this->popup->exec(); this->socket.reset(); } else { this->popup->set_title("Ошибка"); this->popup->set_description("Неверный логин или пароль!"); this->popup->exec(); } break; } case (type_forward::upload_result): { auto type = doc.FirstChildElement("body")->FirstChildElement("answer"); if (type->GetText() == QString("correct")) { this->popup->set_title("Успешно"); this->popup->set_description("Данные успешно загружены на сервер!"); this->popup->exec(); this->socket.reset(); } else { this->popup->set_title("Ошибка"); this->popup->set_description("Неверный логин или пароль!"); this->popup->exec(); } break; } case (type_forward::load_patterns): { this->fill_db_patterns(doc.FirstChildElement("body")); this->fill_patterns_list_form(); this->popup->set_title("Успешно"); this->popup->set_description("Список паттернов обновлен!"); this->popup->exec(); this->socket.reset(); break; } } if (this->socket) this->socket->close(); } catch (const char* e) { this->ui->login_2->setEnabled(false); this->ui->register_2->setEnabled(false); this->popup->set_title("Произошла ошибка"); this->popup->set_description(e); this->popup->exec(); this->socket->close(); socket->connectToHost(this->host, this->port); } catch (...) { this->ui->login_2->setEnabled(false); this->ui->register_2->setEnabled(false); this->popup->set_title("Произошла ошибка"); this->popup->set_description("Неопознанная ошибка"); this->popup->exec(); this->socket->close(); socket->connectToHost(this->host, this->port); } } void MainWindow::send_auth(const QString &login, const QString &password) { tinyxml2::XMLDocument doc; tinyxml2::XMLDeclaration* decl = doc.NewDeclaration("xml version=\"1.1\" encoding=\"UTF-8\""); doc.InsertEndChild(decl); tinyxml2::XMLElement* type = doc.NewElement("type"); type->SetText("authorization"); doc.InsertEndChild(type); tinyxml2::XMLElement* body = doc.NewElement("body"); doc.InsertEndChild(body); tinyxml2::XMLElement* login_xml = doc.NewElement("login"); login_xml->SetText(login.toLocal8Bit().data()); body->InsertEndChild(login_xml); tinyxml2::XMLElement* password_xml = doc.NewElement("password"); password_xml->SetText(password.toLocal8Bit().data()); body->InsertEndChild(password_xml); tinyxml2::XMLPrinter printer; doc.Print(&printer); this->send(printer.CStr()); } void MainWindow::send_test_result(const QString &login, const QString &password) { tinyxml2::XMLDocument doc; tinyxml2::XMLDeclaration* decl = doc.NewDeclaration("xml version=\"1.1\" encoding=\"UTF-8\""); doc.InsertEndChild(decl); tinyxml2::XMLElement* type = doc.NewElement("type"); type->SetText("set_all_result"); doc.InsertEndChild(type); tinyxml2::XMLElement* body = doc.NewElement("body"); doc.InsertEndChild(body); tinyxml2::XMLElement* login_xml = doc.NewElement("login"); login_xml->SetText(login.toLocal8Bit().data()); body->InsertEndChild(login_xml); tinyxml2::XMLElement* password_xml = doc.NewElement("password"); password_xml->SetText(password.toLocal8Bit().data()); body->InsertEndChild(password_xml); int counter{ 0 }; QSqlQuery query("SELECT COUNT(*) FROM User_test"); if (query.next()) counter = query.value(0).toInt(); tinyxml2::XMLElement* count_test = doc.NewElement("count_test"); count_test->SetText(counter); body->InsertEndChild(count_test); if (counter) { tinyxml2::XMLElement* tests = doc.NewElement("tests"); QSqlQuery res_tests("SELECT * FROM User_test"); while (res_tests.next()) { tinyxml2::XMLElement* test = doc.NewElement("test"); tinyxml2::XMLElement* xml_name = doc.NewElement("name"); xml_name->SetText(res_tests.value(0).toString().toUtf8().data()); test->InsertEndChild(xml_name); tinyxml2::XMLElement* result = doc.NewElement("result"); result->SetText(res_tests.value(1).toString().toUtf8().data()); test->InsertEndChild(result); tests->InsertEndChild(test); } body->InsertEndChild(tests); } tinyxml2::XMLPrinter printer; doc.Print(&printer); this->send(printer.CStr()); } void MainWindow::send_patterns_request() { QString request{"<?xml version=\"1.1\" encoding=\"UTF-8\"?><type>patterns</type>"}; this->send(request); } void MainWindow::fill_db_login(tinyxml2::XMLElement *body) { QString login {this->ui->login_lineEdit->text()}; QString password {this->ui->password_lineEdit->text()}; QString type_image {body->FirstChildElement("img_type")->GetText()}; QString path_to_image {QDir::currentPath() + "/images/user." + type_image}; this->base64_file = body->FirstChildElement("img")->GetText(); this->save_img_to_file(path_to_image, this->base64_file); QSqlQuery insert; insert.exec("INSERT INTO User (login, password, path_to_image) VALUES ('" + login + "', '" + password + "', '" + path_to_image + "')"); this->fill_db_result_test(body); } void MainWindow::fill_db_register() { QString login {this->ui->reg_login->text()}; QString password {this->ui->reg_pas->text()}; QString path_to_image {QDir::currentPath() + "/images/user." + this->file_type}; this->save_img_to_file(path_to_image, this->base64_file); QSqlQuery insert; insert.exec("INSERT INTO User (login, password, path_to_image) VALUES ('" + login + "', '" + password + "', '" + path_to_image + "')"); } void MainWindow::save_img_to_file(const QString &path, const QString &img) { std::ofstream tmp_file(path.toUtf8()); tmp_file.close(); std::ofstream file(path.toUtf8(), std::ios::out | std::ios::binary); auto data{ base64_decode(img.toStdString()) }; for (size_t i = 0; i < data.size(); i++) { file << data[i]; } file.close(); } void MainWindow::quit() { this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); this->ui->screen_stacked->setCurrentIndex((int)screen::login); this->forward = type_forward::login; this->db.close(); QFile::remove(QDir::currentPath() + "/main.db"); QDir image_dir(QDir::currentPath() + "/images"); image_dir.removeRecursively(); QDir dir1(QDir::currentPath()); dir1.mkdir("images"); QDir dir2(QDir::currentPath() + "/images"); dir2.mkdir("patterns"); this->ui->login_2->setEnabled(false); this->ui->register_2->setEnabled(false); } void MainWindow::fill_personal_area() { user_info_t info{this->get_user_info()}; this->profile_pic = QPixmap(); this->profile_pic.load(info.path_to_image); int width{this->profile_pic.width()}; int height{this->profile_pic.height()}; bool is_width{ width >= height }; int big{ width >= height ? width : height }; if (width == height) { this->profile_pic = this->profile_pic.scaled ( 512, 512, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ); } else if (big > 512) { double ratio {big / 512.0}; this->profile_pic = this->profile_pic.scaled ( is_width ? 512 : int(this->profile_pic.width() / ratio), is_width ? int(this->profile_pic.height() / ratio) : 512, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ); } else { double ratio {512.0 / big}; this->profile_pic = this->profile_pic.scaled ( is_width ? 512 : int(this->profile_pic.width() * ratio), is_width ? int(this->profile_pic.height() * ratio) : 512, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ); } this->ui->img_profile->setPixmap(this->profile_pic); this->ui->show_login->setText("Логин: " + info.login); } void MainWindow::fill_db_result_test(tinyxml2::XMLElement *body) { QSqlQuery insert; insert.exec("DELETE FROM User_test"); int length {body->FirstChildElement("count_test")->IntText()}; if (length > 0) { tinyxml2::XMLElement * tests = body->FirstChildElement("tests"); tinyxml2::XMLElement * test = tests->FirstChildElement("test"); while (test) { QString name {test->FirstChildElement("name")->GetText()}; QString result {test->FirstChildElement("result")->GetText()}; insert.exec("INSERT INTO User_test (pattern, count_corrent) VALUES ('" + name + "', " + result + ")"); test = test->NextSiblingElement("test"); } } } void MainWindow::fill_db_patterns(tinyxml2::XMLElement *body) { QSqlQuery query1("DELETE FROM Pattern"); QSqlQuery query2("DELETE FROM Pattern_test"); QDir image_dir(QDir::currentPath() + "/images/patterns"); image_dir.removeRecursively(); QDir dir1(QDir::currentPath()); dir1.mkdir("images"); QDir dir2(QDir::currentPath() + "/images"); dir2.mkdir("patterns"); tinyxml2::XMLElement * patterns = body->FirstChildElement("pattern_list"); tinyxml2::XMLElement * pattern = patterns->FirstChildElement("pattern"); while (pattern) { QString name {pattern->FirstChildElement("name")->GetText()}; QString description {pattern->FirstChildElement("description")->GetText()}; QString code {pattern->FirstChildElement("code")->GetText()}; QString img_64 {pattern->FirstChildElement("img")->GetText()}; QString img_type {pattern->FirstChildElement("img_type")->GetText()}; QSqlQuery insert; insert.exec("INSERT INTO Pattern (name, description, code, path_to_image)" " VALUES ('" + name + "', '" + description + "', '" + code + "', 'temp')"); QSqlQuery id_query("SELECT id FROM Pattern ORDER BY id DESC"); id_query.next(); QString id{QString::number(id_query.value(0).toInt() + 1)}; QString path_to_image {QDir::currentPath() + "/images/patterns/" + id + "." + img_type}; this->save_img_to_file(path_to_image, img_64); QSqlQuery update("UPDATE Pattern SET path_to_image = '" + path_to_image + "' WHERE name = '" + name + "'"); tinyxml2::XMLElement * tests = pattern->FirstChildElement("test_list"); if (tests) { tinyxml2::XMLElement * test = tests->FirstChildElement("test"); while(test) { QString question {test->FirstChildElement("question")->GetText()}; QString correct_answer {test->FirstChildElement("correct_answer")->GetText()}; int type {test->FirstChildElement("id_description")->IntText()}; if (type == 1) { QString a1 {test->FirstChildElement("a1")->GetText()}; QString a2 {test->FirstChildElement("a2")->GetText()}; QString a3 {test->FirstChildElement("a3")->GetText()}; QString a4 {test->FirstChildElement("a4")->GetText()}; QSqlQuery insert("INSERT INTO Pattern_test (pattern_name, question, id_type, a1, a2, a3, a4, correct_answer) " "VALUES ('" + name + "', '" + question + "', '" + QString::number(type) + "', " "'" + a1 + "', '" + a2 + "', '" + a3 + "', '" + a4 + "'," " '" + correct_answer + "')"); } else if (type == 2) { QSqlQuery insert("INSERT INTO Pattern_test (pattern_name, question, id_type, correct_answer) " "VALUES ('" + name + "', '" + question + "', '" + QString::number(type) + "', '" + correct_answer + "')"); } test = test->NextSiblingElement("test"); } } pattern = pattern->NextSiblingElement("pattern"); } } void MainWindow::fill_result_test_form() { auto data {this->get_result_test_info()}; /*clear*/ size_t i = 0; for (size_t i = 0; i < label_test.size(); i++) { delete this->label_test[i]; if (int(i) != int(label_test.size()) - 1) { delete this->lines_test[i]; } } this->label_test.clear(); this->lines_test.clear(); /*results*/ i = 0; this->ui->result_layout->setSizeConstraint(QLayout::SetMinimumSize); for (i = 0; i < data.size(); i++) { this->label_test.push_back(new QLabel(this)); this->label_test[i]->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); this->label_test[i]->setWordWrap(true); this->label_test[i]->setText(data[i].name + ": " + data[i].result + "/" + QString::number(this->get_count_question(data[i].name))); this->ui->result_layout->addWidget(this->label_test[i]); if (int(i) != int(data.size()) - 1) { this->lines_test.push_back(new QFrame()); this->lines_test[i]->setFrameShape(QFrame::HLine); this->ui->result_layout->addWidget(this->lines_test[i]); } } } void MainWindow::fill_patterns_list_form() { auto data{this->get_patterns_name()}; /*clear*/ size_t i = 0; for (size_t i = 0; i < pattern_label_list.size(); i++) { delete this->pattern_label_list[i]; delete this->pattern_btn_more_list[i]; delete this->pattern_btn_test_list[i]; delete this->pattern_laoyut_list[i]; if (int(i) != int(pattern_label_list.size()) - 1) { delete this->pattern_frame_list[i]; } } this->pattern_label_list.clear(); this->pattern_btn_more_list.clear(); this->pattern_btn_test_list.clear(); this->pattern_laoyut_list.clear(); this->pattern_frame_list.clear(); /*results*/ i = 0; for (i = 0; i < data.size(); i++) { this->pattern_laoyut_list.push_back(new QHBoxLayout(this)); this->pattern_label_list.push_back(new QLabel(this)); this->pattern_label_list[i]->setWordWrap(true); this->pattern_label_list[i]->setText(data[i]); this->pattern_laoyut_list[i]->addWidget(this->pattern_label_list[i]); this->pattern_btn_more_list.push_back(new QPushButton(this)); this->pattern_btn_more_list[i]->setText("Подробнее"); this->pattern_laoyut_list[i]->addWidget(this->pattern_btn_more_list[i]); QString lambda{data[i]}; connect(this->pattern_btn_more_list[i], &QPushButton::clicked, [this, lambda] { this->on_more_btn_clicked(lambda); }); this->pattern_btn_test_list.push_back(new QPushButton(this)); this->pattern_btn_test_list[i]->setText("Тест"); this->pattern_laoyut_list[i]->addWidget(this->pattern_btn_test_list[i]); connect(this->pattern_btn_test_list[i], &QPushButton::clicked, [this, lambda] { this->on_to_test_btn_clicked(lambda); }); this->ui->pattern_list_2->addLayout(this->pattern_laoyut_list[i]); if (int(i) != int(data.size()) - 1) { this->pattern_frame_list.push_back(new QFrame()); this->pattern_frame_list[i]->setFrameShape(QFrame::HLine); this->ui->pattern_list_2->addWidget(this->pattern_frame_list[i]); } } } user_info_t MainWindow::get_user_info() { QSqlQuery query; query.exec("SELECT login, password, path_to_image FROM User"); QString login; QString path_to_file; QString password; while (query.next()) { login = query.value(0).toString(); password = query.value(1).toString(); path_to_file = query.value(2).toString(); } return {login, password, path_to_file}; } std::vector<result_test_t> MainWindow::get_result_test_info() { std::vector<result_test_t> res; QSqlQuery query; query.exec("SELECT pattern, count_corrent FROM User_test"); while (query.next()) { result_test_t tmp; tmp.name = query.value(0).toString(); tmp.result = query.value(1).toString(); res.push_back(std::move(tmp)); } return res; } std::vector<QString> MainWindow::get_patterns_name() { std::vector<QString> res; QSqlQuery query; query.exec("SELECT name FROM Pattern"); while (query.next()) { res.push_back(query.value(0).toString()); } return res; } pattern_info_t MainWindow::get_pattern_info(QString name) { QSqlQuery query; query.exec("SELECT name, description, code, path_to_image FROM Pattern WHERE name = '" + name + "'"); query.next(); return {query.value(0).toString(), query.value(1).toString(), query.value(2).toString(), query.value(3).toString()}; } int MainWindow::get_count_question(QString name) { QSqlQuery query; query.exec("SELECT COUNT(*) FROM Pattern_test WHERE pattern_name = '" + name + "'"); query.next(); return query.value(0).toInt(); } void MainWindow::on_more_btn_clicked(const QString& name) { this->ui->screen_stacked->setCurrentIndex((int)screen::more_pattern); this->ui->name_more->setText("Название: " + name); pattern_info_t data{this->get_pattern_info(name)}; this->ui->description_more->setText(data.description); this->ui->code_more->setText(data.code); this->pattern_pic = QPixmap(); this->pattern_pic.load(data.path_to_image); int width{this->pattern_pic.width()}; if (width > 512) { double ratio {width / 512.0}; this->pattern_pic = this->pattern_pic.scaled(512, int(this->pattern_pic.height() / ratio), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } else { double ratio {512.0 / width}; this->pattern_pic = this->pattern_pic.scaled(512, int(this->pattern_pic.height() * ratio), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } this->ui->img_more->setPixmap(this->pattern_pic); } void MainWindow::on_to_test_btn_clicked(const QString &name) { QFile file("tmp.txt"); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream questions(&file); QSqlQuery select("SELECT * FROM Pattern_test WHERE pattern_name = '" + name + "'"); QSqlQuery count("SELECT COUNT(*) FROM Pattern_test WHERE pattern_name = '" + name + "'"); count.next(); int counter {count.value(0).toInt()}; questions << counter << "\n"; while (select.next()) { int type {select.value(2).toInt()}; if (type == 1) { questions << "1\n"; questions << select.value(1).toString() << "\n"; /*вопрос*/ questions << select.value(3).toString() << "\n"; /*ответы*/ questions << select.value(4).toString() << "\n"; questions << select.value(5).toString() << "\n"; questions << select.value(6).toString() << "\n"; questions << select.value(7).toString() << "\n"; /*правильный ответ*/ } else if (type == 2) { questions << "3\n"; questions << select.value(1).toString() << "\n"; /*вопрос*/ questions << select.value(7).toString() << "\n"; /*правильный ответ*/ } } file.close(); this->test_widget->pattern = name; this->test_widget->init("tmp.txt"); QFile::remove("tmp.txt"); this->ui->screen_stacked->setCurrentIndex((int)screen::test_pattern); } void MainWindow::back_to_list() { this->test_widget->stop_timer(); this->ui->screen_stacked->setCurrentIndex((int)screen::patterns); } void MainWindow::check_test() { QSqlQuery delete_query("DELETE FROM User_test WHERE pattern = '" + this->test_widget->pattern + "'"); QSqlQuery insert("INSERT INTO User_test (pattern, count_corrent) VALUES ('" + this->test_widget->pattern + "', " + QString::number(this->test_widget->count_correct) + ")"); this->fill_result_test_form(); } void MainWindow::on_to_register_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::registration); this->forward = type_forward::registration; } void MainWindow::on_to_login_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::login); this->forward = type_forward::login; } void MainWindow::on_register_2_clicked() { if (!this->ui->reg_login->text().size() || !this->ui->reg_pas->text().size() || !this->base64_file.size()) { qDebug() << "not reg"; return; } tinyxml2::XMLDocument doc; tinyxml2::XMLDeclaration* decl = doc.NewDeclaration("xml version=\"1.1\" encoding=\"UTF-8\""); doc.InsertEndChild(decl); tinyxml2::XMLElement* type = doc.NewElement("type"); type->SetText("registration"); doc.InsertEndChild(type); tinyxml2::XMLElement* body = doc.NewElement("body"); doc.InsertEndChild(body); tinyxml2::XMLElement* login = doc.NewElement("login"); login->SetText(this->ui->reg_login->text().toLocal8Bit().data()); body->InsertEndChild(login); tinyxml2::XMLElement* password = doc.NewElement("password"); password->SetText(this->ui->reg_pas->text().toLocal8Bit().data()); body->InsertEndChild(password); tinyxml2::XMLElement* img = doc.NewElement("img"); img->SetText(this->base64_file.toLocal8Bit().data()); body->InsertEndChild(img); tinyxml2::XMLElement* img_type = doc.NewElement("img_type"); img_type->SetText(this->file_type.toLocal8Bit().data()); body->InsertEndChild(img_type); tinyxml2::XMLPrinter printer; doc.Print(&printer); this->send(printer.CStr()); } void MainWindow::on_reg_img_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "", tr("Image Files (*.png *.jpg *.bmp)")); qDebug() << "file path: " << fileName; std::ifstream file(fileName.toUtf8(), std::ios::in | std::ios::binary); if (!file.is_open()) { this->popup->set_title("Ошибка"); this->popup->set_description("Не удается открыть файл!"); this->popup->exec(); return; } std::vector<uint8_t> data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); this->base64_file = base64_encode(data).c_str(); this->file_type = fileName.split(".").back(); } void MainWindow::on_quit_clicked() { this->is_auth = false; this->quit(); } void MainWindow::on_to_result_test_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::result_test); } void MainWindow::on_to_personal_area_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::personal_area); } void MainWindow::on_load_result_clicked() { this->forward = type_forward::load_result; this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); } void MainWindow::on_upload_result_clicked() { this->forward = type_forward::upload_result; this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); } void MainWindow::on_to_patterns_clicked() { this->fill_patterns_list_form(); this->ui->screen_stacked->setCurrentIndex((int)screen::patterns); } void MainWindow::on_to_personal_area_2_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::personal_area); } void MainWindow::on_update_patterns_clicked() { this->forward = type_forward::load_patterns; this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); } void MainWindow::on_to_pattern_list_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::patterns); } void MainWindow::on_to_settings_clicked() { this->ui->screen_stacked->setCurrentIndex((int)screen::settings); this->ui->adress->setText(this->host); this->ui->port->setValue(this->port); } void MainWindow::on_to_back_clicked() { this->ui->screen_stacked->setCurrentIndex((int)(this->is_auth?screen::personal_area : screen::login)); } void MainWindow::on_settings_save_clicked() { this->host = this->ui->adress->text(); this->port = this->ui->port->value(); if (this->socket) { this->ui->login_2->setEnabled(false); this->ui->register_2->setEnabled(false); this->socket.reset(new QTcpSocket()); socket->connectToHost(this->host, this->port); connect(socket.get(), SIGNAL(connected()), SLOT(slotConnected())); connect(socket.get(), SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(socket.get(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); } } void MainWindow::on_to_settings_register_clicked() { this->on_to_settings_clicked(); } void MainWindow::on_to_settings_login_clicked() { this->on_to_settings_clicked(); }
32.983333
176
0.604289
[ "vector" ]
dcb4761d7672a7190f721d6aebfc4b4728b4c3f3
999
cpp
C++
CodeChef/LongChallenge/OctLongChallenge2017/oct_long_2017_chefgp_partial.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
1
2019-04-19T13:06:33.000Z
2019-04-19T13:06:33.000Z
CodeChef/LongChallenge/OctLongChallenge2017/oct_long_2017_chefgp_partial.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
CodeChef/LongChallenge/OctLongChallenge2017/oct_long_2017_chefgp_partial.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string str; cin>>str; int count_a = 0, count_b = 0; for(int i = 0; i< str.length(); i++) { if(str[i] == 'a') count_a++; else count_b++; } //vector<string> v; if(count_a > count_b) { for(int i = 0; i < 2*count_b ; i++) { if(i % 2 == 0) cout<<"a"; else cout<<"b"; } for(int i = 0; i < 2*(count_a - count_b) - 1; i++) { if(i %2 == 0) cout<<"a"; else cout<<"*"; } } else if(count_b > count_a) { for(int i = 0; i < 2*count_a ; i++) { if(i % 2 == 0) cout<<"b"; else cout<<"a"; } for(int i = 0; i < 2*(count_b - count_a) - 1 ; i++) { if(i %2 == 0) cout<<"b"; else cout<<"*"; } } else { for(int i = 0; i < 2*count_a ; i++) { if(i % 2 == 0) cout<<"a"; else cout<<"b"; } } cout<<"\n"; } return 0; }
12.182927
54
0.396396
[ "vector" ]
dcb66bcdafcc90aed75f89dc3e70d1fdfed3dc59
2,521
cpp
C++
code/wxWidgets/src/common/clntdata.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
38
2016-02-20T02:46:28.000Z
2021-11-17T11:39:57.000Z
code/wxWidgets/src/common/clntdata.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
17
2016-02-20T02:19:55.000Z
2021-02-08T15:15:17.000Z
code/wxWidgets/src/common/clntdata.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
46
2016-02-20T02:47:33.000Z
2021-01-31T15:46:05.000Z
///////////////////////////////////////////////////////////////////////////// // Name: common/clntdata.cpp // Purpose: A mixin class for holding a wxClientData or void pointer // Author: Robin Dunn // Modified by: // Created: 9-Oct-2001 // RCS-ID: $Id: clntdata.cpp,v 1.7 2004/05/23 20:51:58 JS Exp $ // Copyright: (c) wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "clntdata.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/clntdata.h" // ---------------------------------------------------------------------------- wxClientDataContainer::wxClientDataContainer() { // no client data (yet) m_clientData = NULL; m_clientDataType = wxClientData_None; } wxClientDataContainer::~wxClientDataContainer() { // we only delete object data, not untyped if ( m_clientDataType == wxClientData_Object ) delete m_clientObject; } void wxClientDataContainer::DoSetClientObject( wxClientData *data ) { wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxT("can't have both object and void client data") ); if ( m_clientObject ) delete m_clientObject; m_clientObject = data; m_clientDataType = wxClientData_Object; } wxClientData *wxClientDataContainer::DoGetClientObject() const { // it's not an error to call GetClientObject() on a window which doesn't // have client data at all - NULL will be returned wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxT("this window doesn't have object client data") ); return m_clientObject; } void wxClientDataContainer::DoSetClientData( void *data ) { wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxT("can't have both object and void client data") ); m_clientData = data; m_clientDataType = wxClientData_Void; } void *wxClientDataContainer::DoGetClientData() const { // it's not an error to call GetClientData() on a window which doesn't have // client data at all - NULL will be returned wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxT("this window doesn't have void client data") ); return m_clientData; } // ----------------------------------------------------------------------------
28.647727
79
0.604522
[ "object" ]
dcb9199a7e1ebea56299dc1d4009b71f6e95c0e3
1,860
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/le/TruncatedFilter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/le/TruncatedFilter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/le/TruncatedFilter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "elastos/droid/bluetooth/le/TruncatedFilter.h" namespace Elastos { namespace Droid { namespace Bluetooth { namespace LE { //===================================================================== // TruncatedFilter //===================================================================== CAR_INTERFACE_IMPL(TruncatedFilter, Object, ITruncatedFilter); TruncatedFilter::TruncatedFilter() { } ECode TruncatedFilter::constructor( /* [in] */ IScanFilter* filter, /* [in] */ IList* storageDescriptors) { mFilter = filter; mStorageDescriptors = storageDescriptors; return NOERROR; } ECode TruncatedFilter::GetFilter( /* [out] */ IScanFilter** result) { VALIDATE_NOT_NULL(result); *result = mFilter; REFCOUNT_ADD(*result); return NOERROR; } ECode TruncatedFilter::GetStorageDescriptors( /* [out] */ IList** result) { VALIDATE_NOT_NULL(result); *result = mStorageDescriptors; REFCOUNT_ADD(*result); return NOERROR; } } // namespace LE } // namespace Bluetooth } // namespace Droid } // namespace Elastos
29.0625
75
0.596237
[ "object" ]
dcbb842ecbecc17c14115c61f6b193ae020f47b3
1,929
hpp
C++
tst/for_each_test.hpp
Anomander/typelist
46b003ccd77c1964a365aa8d4195e0cf536d8743
[ "MIT" ]
2
2017-12-30T05:27:59.000Z
2020-07-22T06:44:53.000Z
tst/for_each_test.hpp
Anomander/typelist
46b003ccd77c1964a365aa8d4195e0cf536d8743
[ "MIT" ]
null
null
null
tst/for_each_test.hpp
Anomander/typelist
46b003ccd77c1964a365aa8d4195e0cf536d8743
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2013 Stan Pavlovski * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __tst_for_each_test_hpp__ #define __tst_for_each_test_hpp__ #include "test_common.h" using for_each_list = list <int, char, float, double, list<long long, long>>; TEST(for_each_tests, SimpleTest) { std::vector<std::string> v; for_each <for_each_list> :: run <test_helpers::Iterator> (std::ref(v)); EXPECT_EQ(v.size(), length<for_each_list>::value); EXPECT_EQ("int", v[0]); EXPECT_EQ("char", v[1]); EXPECT_EQ("float", v[2]); EXPECT_EQ("double", v[3]); EXPECT_EQ("long long", v[4]); EXPECT_EQ("long", v[5]); } TEST(for_each_tests, TestEmpty) { std::vector<std::string> v; for_each <erase<int, list<int>>::type> :: run <test_helpers::Iterator> (std::ref(v)); EXPECT_EQ(0, v.size()); } #endif//__tst_for_each_test_hpp__
38.58
83
0.718507
[ "vector" ]
dcbc91cda065393fb6d7788f1f000062e851f361
4,469
cpp
C++
trainings/2015-08-08-Zhejiang-Province-2015/I.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-08-08-Zhejiang-Province-2015/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-08-08-Zhejiang-Province-2015/I.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> const int N = 111111; int n, m, stamp, comps, top; std::vector<int> edge[N]; int dfn[N], low[N], comp[N], stack[N], vertex[N], edges[N]; class Node { public: Node *child[26], *fail; int index; bool ban; Node() { memset(child, 0, sizeof(child)); fail = NULL; index = 0; ban = false; } Node(int index) : index(index) { memset(child, 0, sizeof(child)); fail = NULL; ban = false; } }; int size; Node pool[N]; Node *apply() { pool[size] = Node(size); return &pool[size++]; } void insert(Node *x, char *text) { int length = (int)strlen(text); for (int i = 0; i < length; ++i) { int token = text[i] - 'a'; if (!x->child[token]) { x->child[token] = apply(); } x = x->child[token]; } x->ban = true; } void build(Node *root) { std::vector<Node *> queue; queue.push_back(root->fail = root); for (int head = 0; head < (int)queue.size(); ++head) { Node *x = queue[head]; for (int token = 0; token < 26; ++token) { if (x->child[token]) { x->child[token]->fail = (x == root) ? root : x->fail->child[token]; x->child[token]->ban |= x->child[token]->fail->ban; queue.push_back(x->child[token]); } else { x->child[token] = (x == root) ? root : x->fail->child[token]; } } } } bool legal(char *text) { int length = (int)strlen(text); for (int i = 0; i < length; ++i) { if (text[i] < 'a' || text[i] > 'a' + m) { return false; } } return true; } void tarjan(int x) { dfn[x] = low[x] = ++stamp; stack[top++] = x; for (int i = 0; i < (int)edge[x].size(); ++i) { int y = edge[x][i]; if (!dfn[y]) { tarjan(y); low[x] = std::min(low[x], low[y]); } else if (!comp[y]) { low[x] = std::min(low[x], dfn[y]); } } if (low[x] == dfn[x]) { comps++; do { int y = stack[--top]; comp[y] = comps; } while (stack[top] != x); } } void solve(void) { size = 0; Node *root = apply(); scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) { static char text[N]; scanf("%s", text); if (legal(text)) { insert(root, text); } } build(root); for (int i = 0; i < size; ++i) { edge[i].clear(); } for (int i = 0; i < size; ++i) { Node *x = &pool[i]; if (x->ban) { continue; } for (int token = 0; token < m; ++token) { Node *y = x->child[token]; if (y->ban) { continue; } edge[x - pool].push_back(y - pool); } } /* printf("!!!%d\n", size); for (int i = 0; i < size; ++i) { for (int j = 0; j < (int)edge[i].size(); ++j) { printf("%d ", edge[i][j]); } puts(""); }*/ for (int i = 0; i < size; ++i) { std::sort(edge[i].begin(), edge[i].end()); edge[i].erase(std::unique(edge[i].begin(), edge[i].end()), edge[i].end()); } /* printf("%d\n", size); for (int i = 0; i < size; ++i) { for (int j = 0; j < (int)edge[i].size(); ++j) { printf("%d %d\n", i, edge[i][j]); } } */ stamp = comps = top = 0; std::fill(dfn, dfn + size, 0); std::fill(comp, comp + size, 0); for (int i = 0; i < size; ++i) { if (!dfn[i]) { tarjan(i); } } /* for (int i = 0; i < size; ++i) { printf("%d ", comp[i]); } puts(""); */ std::fill(vertex + 1, vertex + comps + 1, 0); std::fill(edges + 1, edges + comps + 1, 0); for (int x = 0; x < size; ++x) { vertex[comp[x]]++; for (int i = 0; i < (int)edge[x].size(); ++i) { int y = edge[x][i]; if (comp[x] == comp[y]) { edges[comp[x]]++; } } } for (int i = 1; i <= comps; ++i) { if (vertex[i] < edges[i]) { puts("Yes"); return; } } puts("No"); } int main(void) { int tests; for (scanf("%d", &tests); tests--; solve()) { } }
23.276042
83
0.406802
[ "vector" ]
dcc0f38463269480d5260f70e2726a6538de333c
13,352
cpp
C++
amara/amara_geometry.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_geometry.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_geometry.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
#pragma once #ifndef AMARA_GEOMETRY #define AMARA_GEOMETRY #include "amara.h" namespace Amara { typedef struct IntVector2 { int x = 0; int y = 0; } IntVector2; typedef struct FloatVector2 { float x = 0; float y = 0; } FloatVector2; typedef struct IntVector3 { int x = 0; int y = 0; int z = 0; } IntVector; typedef struct FloatVector3{ float x = 0; float y = 0; float z = 0; } FloatVector3; float distanceBetween(float sx, float sy, float ex, float ey) { float xDist = ex-sx; float yDist = ey-sy; return sqrt(xDist*xDist + yDist*yDist); } float distanceBetween(IntVector2 s, IntVector2 e) { return distanceBetween(s.x, s.y, e.x, e.y); } float distanceBetween(FloatVector2 s, FloatVector2 e) { return distanceBetween(s.x, s.y, e.x, e.y); } float radiansToDegrees(float rads) { return rads*180/M_PI; } float degreesToRadians(float degrees) { return degrees*M_PI/180; } float angleBetween(FloatVector2 p1, FloatVector2 p2) { float angle = -atan2(p2.y-p1.y, p2.x-p1.x) + M_PI/2.0; angle = fmod(angle, 2*M_PI); while (angle < 0) { angle += 2*M_PI; } return angle; } float angleBetween(float p1x, float p1y, float p2x, float p2y) { float angle = -atan2(p2y-p1y, p2x-p1x) + M_PI/2.0; angle = fmod(angle, 2*M_PI); while (angle < 0) { angle += 2*M_PI; } return angle; } typedef struct IntRect { int x = 0; int y = 0; int width = 0; int height = 0; } IntRect; typedef struct FloatRect { float x = 0; float y = 0; float width = 0; float height = 0; } FloatRect; typedef struct FloatCircle { float x = 0; float y = 0; float radius = 0; } FloatCircle; typedef struct FloatLine { FloatVector2 p1 = {0, 0}; FloatVector2 p2 = {0, 0}; } FloatLine; std::vector<FloatVector2> getPointsAlongLine(FloatLine line, int divisions) { std::vector<FloatVector2> points; points.clear(); float step; for (int i = 0; i <= divisions; i++) { step = i/(float)divisions; FloatVector2 point = { line.p1.x + (line.p2.x - line.p1.x)*step, line.p1.y + (line.p2.y - line.p1.y)*step }; points.push_back(point); } return points; } std::vector<FloatVector2> getPointsAlongLine(FloatVector2 start, FloatVector2 end, int divisions) { return getPointsAlongLine({start, end}, divisions); } std::vector<FloatVector2> getPointsAlongLine(float x1, float y1, float x2, float y2, float divisions) { return getPointsAlongLine({{x1, y1}, {x2, y2}}, divisions); } std::vector<FloatVector2> travelAlongLine(FloatLine line, float step) { std::vector<FloatVector2> points; points.clear(); float angle = angleBetween(line.p1, line.p2); float fullDist = distanceBetween(line.p1, line.p2); bool nowExit = false; float curDist = 0; while (true) { FloatVector2 point = { line.p1.x + sin(angle)*curDist, line.p1.y + cos(angle)*curDist }; points.push_back(point); curDist += step; if (nowExit) { break; } else if (curDist >= fullDist) { curDist = fullDist; nowExit = true; } } return points; } bool overlapping(float px, float py, FloatCircle* circle) { return (Amara::distanceBetween(px, py, circle->x, circle->y) <= circle->radius); } bool overlapping(FloatVector2* p, FloatCircle* circle) { return overlapping(p->x, p->y, circle); } bool overlapping(float px, float py, FloatRect* rect) { if (px < rect->x) return false; if (px > rect->x+rect->width) return false; if (py < rect->y) return false; if (py > rect->y+rect->height) return false; return true; } bool overlapping(FloatVector2* p, FloatRect* rect) { return overlapping(p->x, p->y, rect); } bool overlapping(float px, float py, FloatLine* line, float buffer) { float lineLen = distanceBetween(line->p1.x, line->p1.y, line->p2.x, line->p2.y); float d1 = distanceBetween(px ,py, line->p1.x, line->p1.y); float d2 = distanceBetween(px, py, line->p1.y, line->p2.y); if (d1+d2 >= lineLen-buffer && d1+d2 <= lineLen+buffer) { return true; } return false; } bool overlapping(float px, float py, FloatLine* line) { return overlapping(px, py, line, 0.1); } bool overlapping(IntRect* rect1, IntRect* rect2) { bool overlapX = abs((rect1->x + rect1->width/2.0) - (rect2->x + rect2->width/2.0)) < (rect1->width/2.0 + rect2->width/2.0); bool overlapY = abs((rect1->y + rect1->height/2.0) - (rect2->y + rect2->height/2.0)) < (rect1->height/2.0 + rect2->height/2.0); return overlapX && overlapY; } bool overlapping(FloatRect* rect1, FloatRect* rect2) { bool overlapX = abs((rect1->x + rect1->width/2.0) - (rect2->x + rect2->width/2.0)) < (rect1->width/2.0 + rect2->width/2.0); bool overlapY = abs((rect1->y + rect1->height/2.0) - (rect2->y + rect2->height/2.0)) < (rect1->height/2.0 + rect2->height/2.0); return overlapX && overlapY; } bool overlapping(FloatRect* rect, FloatCircle* circle) { float cx = circle->x; float cy = circle->y; if (cx < rect->x) cx = rect->x; if (cx > rect->x + rect->width) cx = rect->x + rect->width; if (cy < rect->y) cy = rect->y; if (cy > rect->y + rect->height) cy = rect->y + rect->height; if (Amara::distanceBetween(cx, cy, circle->x, circle->y) < circle->radius) { return true; } return false; } bool overlapping(FloatCircle* circle, FloatRect* rect) { return Amara::overlapping(rect, circle); } bool overlapping(FloatCircle* circle1, FloatCircle* circle2) { return Amara::distanceBetween(circle1->x, circle1->y, circle2->x, circle2->y) < (circle1->radius + circle2->radius); } bool overlapping(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { float uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)); float uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)); if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) { return true; } return false; } bool overlapping(FloatLine* line1, FloatLine* line2) { return overlapping( line1->p1.x, line1->p1.y, line1->p2.x, line1->p2.y, line2->p1.x, line2->p1.y, line2->p2.x, line2->p2.y ); } bool overlapping(FloatLine* line, FloatRect* rect) { FloatLine rectLine = {{rect->x, rect->y},{rect->x+rect->width, rect->y}}; if (overlapping(line, &rectLine)) return true; rectLine = {{rect->x, rect->y},{rect->x, rect->y+rect->height}}; if (overlapping(line, &rectLine)) return true; rectLine = {{rect->x+rect->width, rect->y},{rect->x+rect->width, rect->y+rect->height}}; if (overlapping(line, &rectLine)) return true; rectLine = {{rect->x, rect->y+rect->height},{rect->x+rect->width, rect->y+rect->height}}; return false; } bool overlapping(FloatRect* rect, FloatLine* line) { return overlapping(line, rect); } bool overlapping(FloatLine* line, FloatCircle* circle) { if (overlapping(&line->p1, circle) || overlapping(&line->p2, circle)) return true; float distX = line->p1.x - line->p2.x; float distY = line->p1.y - line->p2.y; float len = sqrt((distX*distX) + (distY*distY)); float dot = ( ((circle->x-line->p1.x)*(line->p2.x-line->p1.x)) + ((circle->y-line->p1.y)*(line->p2.y-line->p1.y)) ) / pow(len,2); float closestX = line->p1.x + (dot * (line->p2.x-line->p1.x)); float closestY = line->p1.y + (dot * (line->p2.y-line->p1.y)); FloatLine closeLine = { line->p1.x, line->p1.y, line->p2.x, line->p2.y }; bool onSegment = overlapping(closestX, closestY, &closeLine); if (!onSegment) return false; distX = closestX - circle->x; distY = closestY - circle->y; float distance = sqrt( (distX*distX) + (distY*distY) ); if (distance <= circle->radius) { return true; } return false; } bool overlapping(FloatCircle* circle, FloatLine* line) { return overlapping(line, circle); } int getOffsetX(Amara::Direction dir) { switch (dir) { case Up: return 0; break; case UpLeft: return -1; break; case UpRight: return 1; break; case Down: return 0; break; case DownLeft: return -1; break; case DownRight: return 1; break; case Left: return -1; break; case Right: return 1; break; } return 0; } int getOffsetY(Amara::Direction dir) { switch (dir) { case Up: return -1; break; case UpLeft: return -1; break; case UpRight: return -1; break; case Down: return 1; break; case DownLeft: return 1; break; case DownRight: return 1; break; case Left: return 0; break; case Right: return 0; break; } return 0; } Amara::Direction flipDirection(Amara::Direction dir, bool diagonals) { std::vector<Amara::Direction> list = (diagonals) ? DirectionsInOrder : FourDirections; for (int i = 0; i < list.size(); i++) { if (list[i] == dir) { int newIndex = i + list.size()/2; newIndex = newIndex % list.size(); return list[newIndex]; } } return dir; } Amara::Direction flipDirection(Amara::Direction dir) { return flipDirection(dir, true); } Amara::Direction turnDirection(Amara::Direction dir, std::vector<Direction> list, int turn) { int num = 0; for (int i = 0; i < list.size(); i++) { if (list[i] == dir) { num = i; break; } } num += turn; num = num % list.size(); if (num < 0) num += list.size(); return list[num]; } Amara::Direction turnDirection(Amara::Direction dir, int turn) { return turnDirection(dir, DirectionsInOrder, turn); } Amara::Direction getDirectionBetween(int x1, int y1, int x2, int y2, std::vector<Amara::Direction> list) { if (x1 == x2 && y1 == y2) { return NoDir; } double angle = atan2(y2 - y1, x2 - x1); int dirNum = floor(fmod(round(angle/(2*M_PI/list.size())), list.size())); if (dirNum < 0) { dirNum += list.size(); } Amara::Direction direction = list[dirNum]; return direction; } Amara::Direction getDirectionBetween(int x1, int y1, int x2, int y2) { return getDirectionBetween(x1, y1, x2, y2, DirectionsInOrder); } Amara::Direction getDirectionBetween(IntVector2 p1, IntVector2 p2, std::vector<Amara::Direction> list) { return getDirectionBetween(p1.x, p1.y, p2.x, p2.y, list); } Amara::Direction getDirectionBetween(IntVector2 p1, IntVector2 p2) { return getDirectionBetween(p1.x, p1.y, p2.x, p2.y); } Amara::Direction getDirectionFromString(std::string dir) { if (dir.compare("up") == 0) return Up; if (dir.compare("down") == 0) return Down; if (dir.compare("left") == 0) return Left; if (dir.compare("right") == 0) return Right; if (dir.compare("upLeft") == 0) return UpLeft; if (dir.compare("upRight") == 0) return UpRight; if (dir.compare("downLeft") == 0) return DownLeft; if (dir.compare("downRight") == 0) return DownRight; return NoDir; } std::string getStringFromDirection(Amara::Direction dir) { switch (dir) { case Up: return "up"; break; case Down: return "down"; break; case Left: return "left"; break; case Right: return "right"; break; case UpLeft: return "upLeft"; break; case UpRight: return "upRight"; break; case DownLeft: return "downLeft"; break; case DownRight: return "downRight"; break; } return "noDir"; } } #endif
31.565012
137
0.532804
[ "vector" ]
dcc0f9cb902fc821761f115a29f53a51ed91381c
2,569
cpp
C++
Projects/Skylicht/Engine/Source/Lighting/CLight.cpp
niansa/skylicht-engine
ea3010aea3402bd050b62c3fd7effa16b33e96f5
[ "MIT" ]
null
null
null
Projects/Skylicht/Engine/Source/Lighting/CLight.cpp
niansa/skylicht-engine
ea3010aea3402bd050b62c3fd7effa16b33e96f5
[ "MIT" ]
null
null
null
Projects/Skylicht/Engine/Source/Lighting/CLight.cpp
niansa/skylicht-engine
ea3010aea3402bd050b62c3fd7effa16b33e96f5
[ "MIT" ]
null
null
null
/* !@ MIT License Copyright (c) 2019 Skylicht Technology CO., LTD 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. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #include "pch.h" #include "CLight.h" namespace Skylicht { CLight::CLight() : m_castShadow(false), m_color(1.0f, 1.0f, 1.0f, 1.0f), m_spotCutoff(core::PI / 4.0f), m_intensity(1.0f), m_bakeBounce(1) { setRadius(3.0f); } CLight::~CLight() { } CObjectSerializable* CLight::createSerializable() { CObjectSerializable* object = CComponentSystem::createSerializable(); object->addAutoRelease(new CBoolProperty(object, "castShadow", m_castShadow)); object->addAutoRelease(new CColorProperty(object, "color", m_color.toSColor())); object->addAutoRelease(new CFloatProperty(object, "spotCutoff", m_spotCutoff)); object->addAutoRelease(new CFloatProperty(object, "intensity", m_intensity)); object->addAutoRelease(new CFloatProperty(object, "radius", m_radius)); object->addAutoRelease(new CUIntProperty(object, "bakeBounce", m_bakeBounce)); return object; } void CLight::loadSerializable(CObjectSerializable* object) { CComponentSystem::loadSerializable(object); m_castShadow = object->get<bool>("castShadow", false); m_color = object->get<SColor>("color", SColor(255, 255, 255, 255)); m_spotCutoff = object->get<float>("spotCutoff", core::PI / 4.0f); m_intensity = object->get<float>("intensity", 1.0f); m_radius = object->get<float>("radius", 3.0f); m_bakeBounce = object->get<u32>("bakeBounce", 1); setRadius(m_radius); } }
37.231884
141
0.753601
[ "object" ]
dcc3e4f871c7bb7118c086ff5b54fe6ad28d0422
303
cpp
C++
hackerrank/practice/data_structures/arrays/arrays_ds.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/data_structures/arrays/arrays_ds.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/data_structures/arrays/arrays_ds.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/arrays-ds #include "common/stl/base.h" #include "common/vector/read.h" #include "common/vector/write.h" int main_arrays_ds() { unsigned n; cin >> n; vector<int> v = nvector::Read<int>(n); reverse(v.begin(), v.end()); nvector::Write(v); return 0; }
20.2
50
0.663366
[ "vector" ]
dcc837649e7dc8e2d45c2206edea92fedb5234dd
9,465
cpp
C++
src/saiga/vulkan/VulkanForwardRenderer.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
114
2017-08-13T22:37:32.000Z
2022-03-25T12:28:39.000Z
src/saiga/vulkan/VulkanForwardRenderer.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
7
2019-10-14T18:19:11.000Z
2021-06-11T09:41:52.000Z
src/saiga/vulkan/VulkanForwardRenderer.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
18
2017-08-14T01:22:05.000Z
2022-03-12T12:35:07.000Z
/* * Vulkan Example base class * * Copyright (C) 2016-2017 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "VulkanForwardRenderer.h" #include "saiga/vulkan/Shader/all.h" #include "VulkanInitializers.hpp" #if defined(SAIGA_OPENGL_INCLUDED) # error OpenGL was included somewhere. #endif namespace Saiga { namespace Vulkan { VulkanForwardRenderer::VulkanForwardRenderer(VulkanWindow& window, VulkanParameters vulkanParameters) : VulkanRenderer(window, vulkanParameters) { setupRenderPass(); renderCommandPool = base().mainQueue.createCommandPool(vk::CommandPoolCreateFlagBits::eResetCommandBuffer); std::cout << "VulkanForwardRenderer init done." << std::endl; } VulkanForwardRenderer::~VulkanForwardRenderer() { base().device.destroyRenderPass(renderPass); } void VulkanForwardRenderer::createBuffers(int numImages, int w, int h) { depthBuffer.init(base(), w, h); frameBuffers.clear(); frameBuffers.resize(numImages); for (int i = 0; i < numImages; i++) { frameBuffers[i].createColorDepthStencil(w, h, swapChain.buffers[i].view, depthBuffer.location->data.view, renderPass, base().device); } renderCommandPool.freeCommandBuffers(drawCmdBuffers); drawCmdBuffers.clear(); drawCmdBuffers = renderCommandPool.allocateCommandBuffers(numImages, vk::CommandBufferLevel::ePrimary); if (imGui) imGui->initResources(base(), renderPass); } void VulkanForwardRenderer::setupRenderPass() { std::array<VkAttachmentDescription, 2> attachments = {}; // Color attachment attachments[0].format = swapChain.colorFormat; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Depth attachment attachments[1].format = (VkFormat)depthBuffer.format; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = {}; colorReference.attachment = 0; colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference = {}; depthReference.attachment = 1; depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; subpassDescription.pDepthStencilAttachment = &depthReference; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; subpassDescription.pResolveAttachments = nullptr; // Subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; VkRenderPassCreateInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 2; // static_cast<uint32_t>(attachments.size()); renderPassInfo.pAttachments = attachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpassDescription; renderPassInfo.dependencyCount = 1; // static_cast<uint32_t>(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); VK_CHECK_RESULT(vkCreateRenderPass(base().device, &renderPassInfo, nullptr, &renderPass)); } void VulkanForwardRenderer::render(FrameSync& sync, int currentImage) { VulkanForwardRenderingInterface* renderingInterface = dynamic_cast<VulkanForwardRenderingInterface*>(rendering); SAIGA_ASSERT(renderingInterface); // std::cout << "VulkanForwardRenderer::render" << std::endl; if (imGui && should_render_imgui) { // std::thread t([&](){ imGui->beginFrame(); renderingInterface->renderGUI(); imGui->endFrame(); // }); // t.join(); } VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); // cmdBufInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; VkClearValue clearValues[2]; // This is blender's default viewport background color :) vec4 clearColor = vec4(57, 57, 57, 255) / 255.0f; clearValues[0].color = {{clearColor[0], clearColor[1], clearColor[2], clearColor[3]}}; clearValues[1].depthStencil = {1.0f, 0}; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = surfaceWidth; renderPassBeginInfo.renderArea.extent.height = SurfaceHeight; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; vk::CommandBuffer& cmd = drawCmdBuffers[currentImage]; // cmd.reset(vk::CommandBufferResetFlagBits::eReleaseResources); // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[currentImage].framebuffer; cmd.begin(cmdBufInfo); timings.resetFrame(cmd); timings.enterSection("TRANSFER", cmd); // VK_CHECK_RESULT(vkBeginCommandBuffer(cmd, &cmdBufInfo)); renderingInterface->transfer(cmd); timings.leaveSection("TRANSFER", cmd); if (imGui && should_render_imgui) imGui->updateBuffers(cmd, currentImage); vkCmdBeginRenderPass(cmd, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)surfaceWidth, (float)SurfaceHeight, 0.0f, 1.0f); vkCmdSetViewport(cmd, 0, 1, &viewport); VkRect2D scissor = vks::initializers::rect2D(surfaceWidth, SurfaceHeight, 0, 0); vkCmdSetScissor(cmd, 0, 1, &scissor); { // Actual rendering timings.enterSection("MAIN", cmd); renderingInterface->render(cmd); timings.leaveSection("MAIN", cmd); timings.enterSection("IMGUI", cmd); if (imGui && should_render_imgui) imGui->render(cmd, currentImage); timings.leaveSection("IMGUI", cmd); } vkCmdEndRenderPass(cmd); VK_CHECK_RESULT(vkEndCommandBuffer(cmd)); vk::PipelineStageFlags submitPipelineStages = vk::PipelineStageFlagBits::eColorAttachmentOutput; std::array<vk::Semaphore, 2> signalSemaphores{sync.renderComplete, sync.defragMayStart}; vk::SubmitInfo submitInfo; // submitInfo = vks::initializers::submitInfo(); submitInfo.pWaitDstStageMask = &submitPipelineStages; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &sync.imageAvailable; submitInfo.signalSemaphoreCount = 2; submitInfo.pSignalSemaphores = signalSemaphores.data(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &cmd; // VK_CHECK_RESULT(vkQueueSubmit(graphicsQueue, 1, &submitInfo, sync.frameFence)); base().mainQueue.submit(submitInfo, sync.frameFence); timings.finishFrame(sync.defragMayStart); // graphicsQueue.queue.submit(submitInfo,vk::Fence()); // VK_CHECK_RESULT(swapChain.queuePresent(presentQueue, currentBuffer, sync.renderComplete)); base().finish_frame(); } } // namespace Vulkan } // namespace Saiga
39.273859
116
0.718859
[ "render" ]
dcc933c84e0cb7f712c5a4a54fca6751208cb810
2,044
cpp
C++
graph-measures/features_algorithms/accelerated_graph_features/src/utils/MathUtils.cpp
Unknown-Data/QGCN
e074ada31c13b6de6eabba2b2ebce90e88fdfdbf
[ "MIT" ]
3
2021-04-21T16:06:51.000Z
2022-03-31T12:09:01.000Z
graph-measures/features_algorithms/accelerated_graph_features/src/utils/MathUtils.cpp
Unknown-Data/QGCN
e074ada31c13b6de6eabba2b2ebce90e88fdfdbf
[ "MIT" ]
1
2021-02-04T07:48:16.000Z
2021-02-24T23:01:41.000Z
graph-measures/features_algorithms/accelerated_graph_features/src/utils/MathUtils.cpp
Unknown-Data/QGCN
e074ada31c13b6de6eabba2b2ebce90e88fdfdbf
[ "MIT" ]
null
null
null
#include "../includes/MathUtils.h" float MathUtils::calculateStd(const std::vector<float>& data) { float standartDeviation = 0.0f; int len = data.size(); int nonZero = 0; float mean = calculateMeanWithoutZeroes(data); for (int i = 0; i < len; i++) if (data[i] != 0) { nonZero++; standartDeviation += (data[i] - mean) * (data[i] - mean); } standartDeviation = sqrt(standartDeviation / ((float) nonZero)); return standartDeviation; } float MathUtils::calculateMean(const std::vector<float>& data) { int len = data.size(); float sum = 0.0f; for (int i = 0; i < len; i++) { sum += data[i]; } return sum / ((float) len); } float MathUtils::calculateMeanWithoutZeroes(const std::vector<float>& data) { int len = data.size(); int nonZero = 0; float sum = 0.0f; for (int i = 0; i < len; i++) { if (data[i] != 0) { sum += data[i]; nonZero++; } } return sum / ((float) nonZero); } float MathUtils::calculateWeightedAverage(const std::vector<float>& data, const std::vector<float>& weights) { int lenData = data.size(); int lenWeights = weights.size(); if (lenData != lenWeights) throw std::length_error("Data and weights must have the same size"); float sum = 0.0f; for (int i = 0; i < lenData; i++) sum += data[i] * weights[i]; float weightSum = 0; for (int i = 0; i < lenWeights; i++) weightSum += weights[i]; sum = sum / weightSum; return sum; } float MathUtils::calculateWeightedStd(const std::vector<float>& data, const std::vector<float>& weights) { int lenData = data.size(); int lenWeights = weights.size(); if (lenData != lenWeights) throw std::length_error("Data and weights must have the same size"); float avg = calculateWeightedAverage(data,weights); std::vector<float> modified_data; modified_data.reserve(lenData); for(auto& p:data) modified_data.push_back((p-avg)*(p-avg)); float variance = calculateWeightedAverage(modified_data,weights); return sqrt(variance); }
24.626506
78
0.636008
[ "vector" ]
dcca524e7a3ccbb970a08a523f40112067abef42
4,874
cpp
C++
Pod/Classes/algorithms/io/eqloudloader.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/io/eqloudloader.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
Pod/Classes/algorithms/io/eqloudloader.cpp
jbloit/iosEssentia
785ba29e8178942b396575dd3872bdf3d5d63cd5
[ "MIT" ]
null
null
null
/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "eqloudloader.h" #include "algorithmfactory.h" #include "essentiamath.h" using namespace std; namespace essentia { namespace streaming { const char* EqloudLoader::name = "EqloudLoader"; const char* EqloudLoader::description = DOC("Given an audio file this algorithm outputs the raw audio data downmixed to mono. Audio is resampled in case the given sampling rate does not match the sampling rate of the input signal and normalized by the given replayGain gain. In addition, audio data is filtered through an equal-loudness filter.\n" "\n" "This algorithm uses MonoLoader and thus inherits all of its input requirements and exceptions.\n" "\n" "References:\n" " [1] Replay Gain - A Proposed Standard,\n" " http://replaygain.hydrogenaudio.org\n\n" " [2] Replay Gain - Equal Loudness Filter,\n" " http://replaygain.hydrogenaudio.org/proposal/equal_loudness.html"); EqloudLoader::EqloudLoader() : AlgorithmComposite(), _monoLoader(0), _trimmer(0), _scale(0), _eqloud(0) { declareOutput(_audio, "audio", "the audio signal"); AlgorithmFactory& factory = AlgorithmFactory::instance(); _monoLoader = factory.create("MonoLoader"); _trimmer = factory.create("Trimmer"); _scale = factory.create("Scale"); _eqloud = factory.create("EqualLoudness"); _monoLoader->output("audio") >> _trimmer->input("signal"); _trimmer->output("signal") >> _scale->input("signal"); _scale->output("signal") >> _eqloud->input("signal"); attach(_eqloud->output("signal"), _audio); } void EqloudLoader::configure() { // if no file has been specified, do not do anything if (!parameter("filename").isConfigured()) return; _monoLoader->configure(INHERIT("filename"), INHERIT("sampleRate"), INHERIT("downmix")); _trimmer->configure(INHERIT("sampleRate"), INHERIT("startTime"), INHERIT("endTime")); // apply a 6dB preamp, as done by all audio players. Real scalingFactor = db2amp(parameter("replayGain").toReal() + 6.0); _scale->configure("factor", scalingFactor); _eqloud->configure(INHERIT("sampleRate")); } } // namespace streaming } // namespace essentia namespace essentia { namespace standard { const char* EqloudLoader::name = "EqloudLoader"; const char* EqloudLoader::description = DOC("Given an audio file this algorithm outputs the raw audio data downmixed to mono. Audio is resampled in case the given sampling rate does not match the sampling rate of the input signal and normalized by the given replayGain gain. In addition, audio data is filtered through an equal-loudness filter.\n" "\n" "This algorithm uses MonoLoader and thus inherits all of its input requirements and exceptions.\n" "\n" "References:\n" " [1] Replay Gain - A Proposed Standard,\n" " http://replaygain.hydrogenaudio.org" " [2] Replay Gain - Equal Loudness Filter,\n" " http://replaygain.hydrogenaudio.org/equal_loudness.html"); void EqloudLoader::createInnerNetwork() { _loader = streaming::AlgorithmFactory::create("EqloudLoader"); _audioStorage = new streaming::VectorOutput<AudioSample>(); _loader->output("audio") >> _audioStorage->input("data"); _network = new scheduler::Network(_loader); } void EqloudLoader::configure() { // if no file has been specified, do not do anything // we let the inner loader take care of correctness and sending a nice // error message if necessary if (!parameter("filename").isConfigured()) return; _loader->configure(INHERIT("filename"), INHERIT("sampleRate"), INHERIT("startTime"), INHERIT("endTime"), INHERIT("replayGain"), INHERIT("downmix")); } void EqloudLoader::compute() { vector<AudioSample>& audio = _audio.get(); // _audio.reserve(sth_meaningful); _audioStorage->setVector(&audio); _network->run(); reset(); } void EqloudLoader::reset() { _network->reset(); } } // namespace standard } // namespace essentia
35.318841
347
0.694296
[ "vector" ]
dcd8e9deb9e44612a7bd532b0237505942c41d2a
17,175
cc
C++
src/net/http/bidirectional_stream.cc
godfo/naiveproxy
369269a12832bf34bf01c7b0e7ca121555abd3eb
[ "BSD-3-Clause" ]
1
2021-03-21T10:43:16.000Z
2021-03-21T10:43:16.000Z
src/net/http/bidirectional_stream.cc
wclmgcd/naiveproxy
e32a3afb76fd21207c322f2d5e794c4f5505fb59
[ "BSD-3-Clause" ]
null
null
null
src/net/http/bidirectional_stream.cc
wclmgcd/naiveproxy
e32a3afb76fd21207c322f2d5e794c4f5505fb59
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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 "net/http/bidirectional_stream.h" #include <string> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/threading/thread_task_runner_handle.h" #include "base/timer/timer.h" #include "base/values.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/http/bidirectional_stream_request_info.h" #include "net/http/http_network_session.h" #include "net/http/http_response_headers.h" #include "net/http/http_stream.h" #include "net/log/net_log.h" #include "net/log/net_log_capture_mode.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_source_type.h" #include "net/log/net_log_values.h" #include "net/spdy/spdy_http_utils.h" #include "net/spdy/spdy_log_util.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_config.h" #include "net/third_party/quiche/src/spdy/core/spdy_header_block.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "url/gurl.h" namespace net { namespace { base::Value NetLogHeadersParams(const spdy::SpdyHeaderBlock* headers, NetLogCaptureMode capture_mode) { base::DictionaryValue dict; dict.SetKey("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode)); return std::move(dict); } base::Value NetLogParams(const GURL& url, const std::string& method, const HttpRequestHeaders* headers, NetLogCaptureMode capture_mode) { base::DictionaryValue dict; dict.SetString("url", url.possibly_invalid_spec()); dict.SetString("method", method); std::string empty; base::Value headers_param(headers->NetLogParams(empty, capture_mode)); dict.SetKey("headers", std::move(headers_param)); return std::move(dict); } } // namespace BidirectionalStream::Delegate::Delegate() = default; BidirectionalStream::Delegate::~Delegate() = default; BidirectionalStream::BidirectionalStream( std::unique_ptr<BidirectionalStreamRequestInfo> request_info, HttpNetworkSession* session, bool send_request_headers_automatically, Delegate* delegate) : BidirectionalStream(std::move(request_info), session, send_request_headers_automatically, delegate, std::make_unique<base::OneShotTimer>()) {} BidirectionalStream::BidirectionalStream( std::unique_ptr<BidirectionalStreamRequestInfo> request_info, HttpNetworkSession* session, bool send_request_headers_automatically, Delegate* delegate, std::unique_ptr<base::OneShotTimer> timer) : request_info_(std::move(request_info)), net_log_(NetLogWithSource::Make(session->net_log(), NetLogSourceType::BIDIRECTIONAL_STREAM)), session_(session), send_request_headers_automatically_(send_request_headers_automatically), request_headers_sent_(false), delegate_(delegate), timer_(std::move(timer)) { DCHECK(delegate_); DCHECK(request_info_); // Start time should be measured before connect. load_timing_info_.request_start_time = base::Time::Now(); load_timing_info_.request_start = base::TimeTicks::Now(); if (net_log_.IsCapturing()) { net_log_.BeginEvent(NetLogEventType::BIDIRECTIONAL_STREAM_ALIVE, [&](NetLogCaptureMode capture_mode) { return NetLogParams( request_info_->url, request_info_->method, &request_info_->extra_headers, capture_mode); }); } if (!request_info_->url.SchemeIs(url::kHttpsScheme)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&BidirectionalStream::NotifyFailed, weak_factory_.GetWeakPtr(), ERR_DISALLOWED_URL_SCHEME)); return; } SSLConfig ssl_config; session->GetAlpnProtos(&ssl_config.alpn_protos); StartRequest(ssl_config); } BidirectionalStream::~BidirectionalStream() { UpdateHistograms(); if (net_log_.IsCapturing()) { net_log_.EndEvent(NetLogEventType::BIDIRECTIONAL_STREAM_ALIVE); } } void BidirectionalStream::SendRequestHeaders() { DCHECK(stream_impl_); DCHECK(!request_headers_sent_); DCHECK(!send_request_headers_automatically_); stream_impl_->SendRequestHeaders(); } int BidirectionalStream::ReadData(IOBuffer* buf, int buf_len) { DCHECK(stream_impl_); int rv = stream_impl_->ReadData(buf, buf_len); if (rv > 0) { read_end_time_ = base::TimeTicks::Now(); net_log_.AddByteTransferEvent( NetLogEventType::BIDIRECTIONAL_STREAM_BYTES_RECEIVED, rv, buf->data()); } else if (rv == ERR_IO_PENDING) { read_buffer_ = buf; // Bytes will be logged in OnDataRead(). } if (net_log_.IsCapturing()) { net_log_.AddEventWithIntParams( NetLogEventType::BIDIRECTIONAL_STREAM_READ_DATA, "rv", rv); } return rv; } void BidirectionalStream::SendvData( const std::vector<scoped_refptr<IOBuffer>>& buffers, const std::vector<int>& lengths, bool end_stream) { DCHECK(stream_impl_); DCHECK_EQ(buffers.size(), lengths.size()); DCHECK(write_buffer_list_.empty()); DCHECK(write_buffer_len_list_.empty()); if (net_log_.IsCapturing()) { net_log_.AddEventWithIntParams( NetLogEventType::BIDIRECTIONAL_STREAM_SENDV_DATA, "num_buffers", buffers.size()); } stream_impl_->SendvData(buffers, lengths, end_stream); for (size_t i = 0; i < buffers.size(); ++i) { write_buffer_list_.push_back(buffers[i]); write_buffer_len_list_.push_back(lengths[i]); } } NextProto BidirectionalStream::GetProtocol() const { if (!stream_impl_) return kProtoUnknown; return stream_impl_->GetProtocol(); } int64_t BidirectionalStream::GetTotalReceivedBytes() const { if (!stream_impl_) return 0; return stream_impl_->GetTotalReceivedBytes(); } int64_t BidirectionalStream::GetTotalSentBytes() const { if (!stream_impl_) return 0; return stream_impl_->GetTotalSentBytes(); } void BidirectionalStream::GetLoadTimingInfo( LoadTimingInfo* load_timing_info) const { *load_timing_info = load_timing_info_; } void BidirectionalStream::PopulateNetErrorDetails(NetErrorDetails* details) { DCHECK(details); if (stream_impl_) stream_impl_->PopulateNetErrorDetails(details); } void BidirectionalStream::StartRequest(const SSLConfig& ssl_config) { DCHECK(!stream_request_); HttpRequestInfo http_request_info; http_request_info.url = request_info_->url; http_request_info.method = request_info_->method; http_request_info.extra_headers = request_info_->extra_headers; http_request_info.socket_tag = request_info_->socket_tag; stream_request_ = session_->http_stream_factory()->RequestBidirectionalStreamImpl( http_request_info, request_info_->priority, ssl_config, ssl_config, this, /* enable_ip_based_pooling = */ true, /* enable_alternative_services = */ true, net_log_); // Check that this call does not fail. DCHECK(stream_request_); // Check that HttpStreamFactory does not invoke OnBidirectionalStreamImplReady // synchronously. DCHECK(!stream_impl_); } void BidirectionalStream::OnStreamReady(bool request_headers_sent) { request_headers_sent_ = request_headers_sent; if (net_log_.IsCapturing()) { net_log_.AddEntryWithBoolParams( NetLogEventType::BIDIRECTIONAL_STREAM_READY, NetLogEventPhase::NONE, "request_headers_sent", request_headers_sent); } load_timing_info_.send_start = base::TimeTicks::Now(); load_timing_info_.send_end = load_timing_info_.send_start; delegate_->OnStreamReady(request_headers_sent); } void BidirectionalStream::OnHeadersReceived( const spdy::SpdyHeaderBlock& response_headers) { HttpResponseInfo response_info; if (!SpdyHeadersToHttpResponse(response_headers, &response_info)) { DLOG(WARNING) << "Invalid headers"; NotifyFailed(ERR_FAILED); return; } if (net_log_.IsCapturing()) { net_log_.AddEvent(NetLogEventType::BIDIRECTIONAL_STREAM_RECV_HEADERS, [&](NetLogCaptureMode capture_mode) { return NetLogHeadersParams(&response_headers, capture_mode); }); } // Impl should only provide |connect_timing| and |socket_reused| info, // so use a copy to get these information only. LoadTimingInfo impl_load_timing_info; bool has_load_timing = stream_impl_->GetLoadTimingInfo(&impl_load_timing_info); if (has_load_timing) { load_timing_info_.connect_timing = impl_load_timing_info.connect_timing; load_timing_info_.socket_reused = impl_load_timing_info.socket_reused; } load_timing_info_.receive_headers_end = base::TimeTicks::Now(); read_end_time_ = load_timing_info_.receive_headers_end; session_->http_stream_factory()->ProcessAlternativeServices( session_, net::NetworkIsolationKey(), response_info.headers.get(), url::SchemeHostPort(request_info_->url)); delegate_->OnHeadersReceived(response_headers); } void BidirectionalStream::OnDataRead(int bytes_read) { DCHECK(read_buffer_); if (net_log_.IsCapturing()) { net_log_.AddByteTransferEvent( NetLogEventType::BIDIRECTIONAL_STREAM_BYTES_RECEIVED, bytes_read, read_buffer_->data()); } read_end_time_ = base::TimeTicks::Now(); read_buffer_ = nullptr; delegate_->OnDataRead(bytes_read); } void BidirectionalStream::OnDataSent() { DCHECK(!write_buffer_list_.empty()); DCHECK_EQ(write_buffer_list_.size(), write_buffer_len_list_.size()); if (net_log_.IsCapturing()) { if (write_buffer_list_.size() > 1) { net_log_.BeginEvent( NetLogEventType::BIDIRECTIONAL_STREAM_BYTES_SENT_COALESCED, [&] { return NetLogParamsWithInt("num_buffers_coalesced", write_buffer_list_.size()); }); } for (size_t i = 0; i < write_buffer_list_.size(); ++i) { net_log_.AddByteTransferEvent( NetLogEventType::BIDIRECTIONAL_STREAM_BYTES_SENT, write_buffer_len_list_[i], write_buffer_list_[i]->data()); } if (write_buffer_list_.size() > 1) { net_log_.EndEvent( NetLogEventType::BIDIRECTIONAL_STREAM_BYTES_SENT_COALESCED); } } load_timing_info_.send_end = base::TimeTicks::Now(); write_buffer_list_.clear(); write_buffer_len_list_.clear(); delegate_->OnDataSent(); } void BidirectionalStream::OnTrailersReceived( const spdy::SpdyHeaderBlock& trailers) { if (net_log_.IsCapturing()) { net_log_.AddEvent(NetLogEventType::BIDIRECTIONAL_STREAM_RECV_TRAILERS, [&](NetLogCaptureMode capture_mode) { return NetLogHeadersParams(&trailers, capture_mode); }); } read_end_time_ = base::TimeTicks::Now(); delegate_->OnTrailersReceived(trailers); } void BidirectionalStream::OnFailed(int status) { if (net_log_.IsCapturing()) { net_log_.AddEventWithIntParams(NetLogEventType::BIDIRECTIONAL_STREAM_FAILED, "net_error", status); } NotifyFailed(status); } void BidirectionalStream::OnStreamReady(const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, std::unique_ptr<HttpStream> stream) { NOTREACHED(); } void BidirectionalStream::OnBidirectionalStreamImplReady( const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, std::unique_ptr<BidirectionalStreamImpl> stream) { DCHECK(!stream_impl_); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("bidirectional_stream", R"( semantics { sender: "Bidirectional Stream" description: "Bidirectional stream is used to exchange data with a server on " "behalf of an RPC API." trigger: "When an application makes an RPC to the server." data: "Any arbitrary data." destination: OTHER destination_other: "Any destination that the application chooses." } policy { cookies_allowed: NO setting: "This feature is not used in Chrome." policy_exception_justification: "This feature is not used in Chrome." } )"); stream_request_.reset(); stream_impl_ = std::move(stream); stream_impl_->Start(request_info_.get(), net_log_, send_request_headers_automatically_, this, std::move(timer_), traffic_annotation); } void BidirectionalStream::OnWebSocketHandshakeStreamReady( const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, std::unique_ptr<WebSocketHandshakeStreamBase> stream) { NOTREACHED(); } void BidirectionalStream::OnStreamFailed( int result, const NetErrorDetails& net_error_details, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, ResolveErrorInfo resolve_error_info) { DCHECK_LT(result, 0); DCHECK_NE(result, ERR_IO_PENDING); DCHECK(stream_request_); NotifyFailed(result); } void BidirectionalStream::OnCertificateError(int result, const SSLConfig& used_ssl_config, const SSLInfo& ssl_info) { DCHECK_LT(result, 0); DCHECK_NE(result, ERR_IO_PENDING); DCHECK(stream_request_); NotifyFailed(result); } void BidirectionalStream::OnNeedsProxyAuth( const HttpResponseInfo& proxy_response, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, HttpAuthController* auth_controller) { DCHECK(stream_request_); NotifyFailed(ERR_PROXY_AUTH_REQUESTED); } void BidirectionalStream::OnNeedsClientAuth(const SSLConfig& used_ssl_config, SSLCertRequestInfo* cert_info) { DCHECK(stream_request_); // BidirectionalStream doesn't support client auth. It ignores client auth // requests with null client cert and key. SSLConfig ssl_config = used_ssl_config; session_->ssl_client_context()->SetClientCertificate(cert_info->host_and_port, nullptr, nullptr); stream_request_ = nullptr; StartRequest(ssl_config); } void BidirectionalStream::OnQuicBroken() {} void BidirectionalStream::NotifyFailed(int error) { delegate_->OnFailed(error); } void BidirectionalStream::UpdateHistograms() { // If the request failed before response is started, treat the metrics as // bogus and skip logging. if (load_timing_info_.request_start.is_null() || load_timing_info_.receive_headers_end.is_null() || read_end_time_.is_null() || load_timing_info_.send_start.is_null() || load_timing_info_.send_end.is_null()) { return; } if (GetProtocol() == kProtoHTTP2) { UMA_HISTOGRAM_TIMES("Net.BidirectionalStream.TimeToReadStart.HTTP2", load_timing_info_.receive_headers_end - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES("Net.BidirectionalStream.TimeToReadEnd.HTTP2", read_end_time_ - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES( "Net.BidirectionalStream.TimeToSendStart.HTTP2", load_timing_info_.send_start - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES( "Net.BidirectionalStream.TimeToSendEnd.HTTP2", load_timing_info_.send_end - load_timing_info_.request_start); UMA_HISTOGRAM_COUNTS_1M("Net.BidirectionalStream.ReceivedBytes.HTTP2", stream_impl_->GetTotalReceivedBytes()); UMA_HISTOGRAM_COUNTS_1M("Net.BidirectionalStream.SentBytes.HTTP2", stream_impl_->GetTotalSentBytes()); } else if (GetProtocol() == kProtoQUIC) { UMA_HISTOGRAM_TIMES("Net.BidirectionalStream.TimeToReadStart.QUIC", load_timing_info_.receive_headers_end - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES("Net.BidirectionalStream.TimeToReadEnd.QUIC", read_end_time_ - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES( "Net.BidirectionalStream.TimeToSendStart.QUIC", load_timing_info_.send_start - load_timing_info_.request_start); UMA_HISTOGRAM_TIMES( "Net.BidirectionalStream.TimeToSendEnd.QUIC", load_timing_info_.send_end - load_timing_info_.request_start); UMA_HISTOGRAM_COUNTS_1M("Net.BidirectionalStream.ReceivedBytes.QUIC", stream_impl_->GetTotalReceivedBytes()); UMA_HISTOGRAM_COUNTS_1M("Net.BidirectionalStream.SentBytes.QUIC", stream_impl_->GetTotalSentBytes()); } } } // namespace net
35.85595
80
0.699563
[ "vector" ]
dcdce769999d7f5bd8e8b1a9c18b581766b457e7
1,850
hpp
C++
include/KMP.hpp
wenda84/KMP
e3a585364f6a224b79e5a05e5dfe341a4563e6a5
[ "Apache-2.0" ]
null
null
null
include/KMP.hpp
wenda84/KMP
e3a585364f6a224b79e5a05e5dfe341a4563e6a5
[ "Apache-2.0" ]
null
null
null
include/KMP.hpp
wenda84/KMP
e3a585364f6a224b79e5a05e5dfe341a4563e6a5
[ "Apache-2.0" ]
null
null
null
//参考知乎的算法介绍用CPP进行实现:https://zhuanlan.zhihu.com/p/83334559 #include <iostream> #include <vector> using std::string; using std::vector; namespace ns_KMP{ class KMP { private: #define ASC_NUM 256 string pat; public: KMP(string in_pat); ~KMP() {}; vector<vector<int> > dp; //dp means dynamic programming. void print_dp(); int search(string txt); }; KMP::KMP(string in_pat):pat(in_pat) { dp.resize(pat.length(), vector<int>(ASC_NUM)); //初始化dp的二维vector int pat_len = pat.length(); // base case dp[0][pat.at(0)] = 1; int shadow_state = 0; // 影子状态 X 初始为 0 // 当前状态 j 从 1 开始 for (int j = 1; j < pat_len; j++) { for (int c = 0; c < 256; c++) { if (pat.at(j) == c) dp[j][c] = j + 1; else dp[j][c] = dp[shadow_state][c]; } // 更新影子状态 shadow_state = dp[shadow_state][pat.at(j)]; //add for debug begin // print_dp(); // std::cout << "ss="<< shadow_state << std::endl; //add for debug end } } void KMP::print_dp() { for(auto i:dp) { for(auto j:i) std::cout << j << " "; std::cout << std::endl; } } int KMP::search(string txt){ int M = pat.length(); int N = txt.length(); // pat 的初始态为 0 int stat = 0; for (int i = 0; i < N; i++) { // 计算 pat 的下一个状态 stat = dp[stat][txt.at(i)]; // 到达终止态,返回结果 if (stat == M) return i - M + 1; } // 没到达终止态,匹配失败 return -1; } }
24.025974
74
0.416757
[ "vector" ]
dce15036a393c76be1389cc092fcc9e28abe6cd5
7,795
cpp
C++
src/shk-trace/test/cmdline_options_test.cpp
pereckerdal/shuriken
6988cf16904481e9d587b6ce9cfc7f1318518e50
[ "Apache-2.0" ]
19
2017-05-15T08:20:00.000Z
2021-12-03T05:58:32.000Z
src/shk-trace/test/cmdline_options_test.cpp
pereckerdal/shuriken
6988cf16904481e9d587b6ce9cfc7f1318518e50
[ "Apache-2.0" ]
null
null
null
src/shk-trace/test/cmdline_options_test.cpp
pereckerdal/shuriken
6988cf16904481e9d587b6ce9cfc7f1318518e50
[ "Apache-2.0" ]
3
2018-01-16T18:07:30.000Z
2021-06-30T07:33:44.000Z
// Copyright 2017 Per Grön. 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 <catch.hpp> #include "cmdline_options.h" namespace shk { namespace { CmdlineOptions parse(const std::vector<std::string> &options) { std::vector<char *> opts_cstr{ const_cast<char *>("trace") }; for (const auto &option : options) { opts_cstr.push_back(const_cast<char *>(option.c_str())); } return CmdlineOptions::parse(opts_cstr.size(), opts_cstr.data()); } } // anonymous namespace TEST_CASE("CmdlineOptions") { SECTION("Version") { CHECK(parse({ "--version" }).result == CmdlineOptions::Result::VERSION); } SECTION("Help") { CHECK(parse({ "--help" }).result == CmdlineOptions::Result::HELP); CHECK(parse({ "-h" }).result == CmdlineOptions::Result::HELP); } SECTION("Empty") { CHECK(parse({}).result == CmdlineOptions::Result::HELP); } SECTION("Nonflag") { CHECK(parse({ "xyz" }).result == CmdlineOptions::Result::HELP); } SECTION("Trailing") { CHECK(parse({ "-f", "file", "-c", "cmd", "xyz" }).result == CmdlineOptions::Result::HELP); CHECK(parse({ "-f", "file", "xyz", "-c", "cmd" }).result == CmdlineOptions::Result::HELP); } SECTION("JustCommand") { auto options = parse({ "-c", "abc" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.tracefile == "/dev/null"); CHECK(options.command == "abc"); CHECK(options.suicide_when_orphaned == false); CHECK(options.json == false); } SECTION("Json") { SECTION("Short") { auto options = parse({ "-c", "abc", "-j" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.tracefile == "/dev/null"); CHECK(options.command == "abc"); CHECK(options.suicide_when_orphaned == false); CHECK(options.json == true); } SECTION("Long") { auto options = parse({ "-c", "abc", "--json" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.tracefile == "/dev/null"); CHECK(options.command == "abc"); CHECK(options.suicide_when_orphaned == false); CHECK(options.json == true); } } SECTION("SuicideWhenOrphaned") { auto options = parse({ "-c", "hej", "--suicide-when-orphaned" }); CHECK(options.result == CmdlineOptions::Result::HELP); } SECTION("SuicideWhenOrphanedShort") { auto options = parse({ "-c", "hej", "-O" }); CHECK(options.result == CmdlineOptions::Result::HELP); } SECTION("JustTracefile") { CHECK(parse({ "-f", "xyz" }).result == CmdlineOptions::Result::HELP); } SECTION("MissingFollowup") { CHECK(parse({ "-f" }).result == CmdlineOptions::Result::HELP); CHECK(parse({ "-f", "file", "-c" }).result == CmdlineOptions::Result::HELP); CHECK(parse({ "-c", "cmd", "-f" }).result == CmdlineOptions::Result::HELP); } SECTION("TwoTracefiles") { CHECK( parse({ "-c", "abc", "-f", "xyz", "-f", "123" }).result == CmdlineOptions::Result::HELP); } SECTION("EmptyTraceFile") { CHECK( parse({ "-c", "abc", "-f", "" }).result == CmdlineOptions::Result::HELP); } SECTION("TwoCommands") { CHECK( parse({ "-c", "abc", "-c", "xyz", "-f", "123" }).result == CmdlineOptions::Result::HELP); } SECTION("CommandFirst") { auto options = parse({ "-c", "abc", "-f", "123" }); CHECK(options.tracefile == "123"); CHECK(options.command == "abc"); } SECTION("TracefileFirst") { auto options = parse({ "-f", "abc", "-c", "123" }); CHECK(options.tracefile == "abc"); CHECK(options.command == "123"); } SECTION("Server") { SECTION("Short") { auto options = parse({ "-s" }); CHECK(options.server == true); } SECTION("Long") { auto options = parse({ "--server" }); CHECK(options.server == true); } SECTION("TrailingArg") { CHECK(parse({ "-s", "xyz" }).result == CmdlineOptions::Result::HELP); } SECTION("Capture") { SECTION("Short") { auto options = parse({ "-s", "-C", "f" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.server); CHECK(options.capture == "f"); } SECTION("Long") { auto options = parse({ "-s", "--capture", "f" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.server); CHECK(options.capture == "f"); } SECTION("WithoutFile") { CHECK(parse({ "-s", "-c" }).result == CmdlineOptions::Result::HELP); } } SECTION("SuicideWhenOrphaned") { SECTION("Short") { auto options = parse({ "-s", "-O" }); CHECK(options.server == true); CHECK(options.suicide_when_orphaned == true); } SECTION("SuicideWhenOrphaned") { auto options = parse({ "-s", "--suicide-when-orphaned" }); CHECK(options.server == true); CHECK(options.suicide_when_orphaned == true); } } SECTION("WithTraceFile") { CHECK(parse({ "-s", "-f", "f" }).result == CmdlineOptions::Result::HELP); } SECTION("WithReplay") { CHECK(parse({ "-s", "-r", "f" }).result == CmdlineOptions::Result::HELP); CHECK( parse({ "-s", "--replay", "f" }).result == CmdlineOptions::Result::HELP); } SECTION("WithCommand") { CHECK(parse({ "-s", "-c", "c" }).result == CmdlineOptions::Result::HELP); } SECTION("Json") { CHECK(parse({ "-s", "-j" }).result == CmdlineOptions::Result::HELP); CHECK(parse({ "-s", "--json" }).result == CmdlineOptions::Result::HELP); } } SECTION("Replay") { SECTION("Short") { auto options = parse({ "-r", "f" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.replay == "f"); } SECTION("Long") { auto options = parse({ "--replay", "f" }); CHECK(options.result == CmdlineOptions::Result::SUCCESS); CHECK(options.replay == "f"); } SECTION("MissingFile") { CHECK(parse({ "-r" }).result == CmdlineOptions::Result::HELP); } SECTION("TrailingArg") { CHECK(parse({ "-r", "f", "xyz" }).result == CmdlineOptions::Result::HELP); } SECTION("Capture") { CHECK(parse({ "-r", "f", "-C" }).result == CmdlineOptions::Result::HELP); } SECTION("SuicideWhenOrphaned") { CHECK(parse({ "-r", "f", "-O" }).result == CmdlineOptions::Result::HELP); } SECTION("WithTraceFile") { CHECK( parse({ "-r", "f", "-f", "f" }).result == CmdlineOptions::Result::HELP); } SECTION("WithCapture") { CHECK( parse({ "-r", "f", "-C", "f" }).result == CmdlineOptions::Result::HELP); CHECK( parse({ "-r", "f", "--capture", "f" }).result == CmdlineOptions::Result::HELP); } SECTION("WithCommand") { CHECK( parse({ "-r", "f", "-c", "c" }).result == CmdlineOptions::Result::HELP); } SECTION("Json") { CHECK( parse({ "-r", "f", "-j" }).result == CmdlineOptions::Result::HELP); CHECK( parse({ "-r", "f", "--json" }).result == CmdlineOptions::Result::HELP); } } } } // namespace shk
29.304511
94
0.56331
[ "vector" ]
dce1d6e8f7e545075dc09c71ff1cb58020fb9178
27,426
cpp
C++
arangod/RocksDBEngine/RocksDBRestReplicationHandler.cpp
iamjpn/arangodb
818b3dcbbcf7dc323bbbb8f3fac34444a8afdb25
[ "Apache-2.0" ]
1
2020-10-27T12:19:33.000Z
2020-10-27T12:19:33.000Z
arangod/RocksDBEngine/RocksDBRestReplicationHandler.cpp
charity1475/arangodb
32bef3ed9abef6f41a11466fe6361ae3e6d99b5e
[ "Apache-2.0" ]
null
null
null
arangod/RocksDBEngine/RocksDBRestReplicationHandler.cpp
charity1475/arangodb
32bef3ed9abef6f41a11466fe6361ae3e6d99b5e
[ "Apache-2.0" ]
1
2020-10-01T08:49:12.000Z
2020-10-01T08:49:12.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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 holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// #include "RocksDBRestReplicationHandler.h" #include "Basics/StaticStrings.h" #include "Basics/VPackStringBufferAdapter.h" #include "Basics/VelocyPackHelper.h" #include "Basics/system-functions.h" #include "Logger/LogMacros.h" #include "Replication/ReplicationClients.h" #include "Replication/Syncer.h" #include "Replication/utilities.h" #include "Rest/HttpResponse.h" #include "RestServer/DatabaseFeature.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBEngine.h" #include "RocksDBEngine/RocksDBReplicationContext.h" #include "RocksDBEngine/RocksDBReplicationManager.h" #include "RocksDBEngine/RocksDBReplicationTailing.h" #include "StorageEngine/EngineSelectorFeature.h" #include "StorageEngine/StorageEngine.h" #include "Transaction/StandaloneContext.h" #include "VocBase/LogicalCollection.h" #include "VocBase/ticks.h" #include <velocypack/Builder.h> #include <velocypack/Dumper.h> #include <velocypack/Iterator.h> #include <velocypack/Slice.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using namespace arangodb::basics; using namespace arangodb::rest; using namespace arangodb::rocksutils; RocksDBRestReplicationHandler::RocksDBRestReplicationHandler( application_features::ApplicationServer& server, GeneralRequest* request, GeneralResponse* response) : RestReplicationHandler(server, request, response), _manager(globalRocksEngine()->replicationManager()) {} void RocksDBRestReplicationHandler::handleCommandBatch() { // extract the request type auto const type = _request->requestType(); auto const& suffixes = _request->suffixes(); size_t const len = suffixes.size(); TRI_ASSERT(len >= 1); if (type == rest::RequestType::POST) { // create a new blocker bool parseSuccess = true; VPackSlice body = this->parseVPackBody(parseSuccess); if (!parseSuccess || !body.isObject()) { // error already created return; } std::string patchCount = VelocyPackHelper::getStringValue(body, "patchCount", ""); arangodb::ServerId const clientId{ StringUtils::uint64(_request->value("serverId"))}; SyncerId const syncerId = SyncerId::fromRequest(*_request); std::string const clientInfo = _request->value("clientInfo"); // create transaction+snapshot, ttl will be default if `ttl == 0`` auto ttl = VelocyPackHelper::getNumericValue<double>(body, "ttl", replutils::BatchInfo::DefaultTimeout); auto* ctx = _manager->createContext(ttl, syncerId, clientId); RocksDBReplicationContextGuard guard(_manager, ctx); if (!patchCount.empty()) { auto triple = ctx->bindCollectionIncremental(_vocbase, patchCount); Result res = std::get<0>(triple); if (res.fail()) { LOG_TOPIC("3d5d4", WARN, Logger::REPLICATION) << "Error during first phase of" << " collection count patching: " << res.errorMessage(); } } VPackBuilder b; b.add(VPackValue(VPackValueType::Object)); b.add("id", VPackValue(std::to_string(ctx->id()))); // id always string b.add("lastTick", VPackValue(std::to_string(ctx->snapshotTick()))); b.close(); _vocbase.replicationClients().track(syncerId, clientId, clientInfo, ctx->snapshotTick(), ttl); generateResult(rest::ResponseCode::OK, b.slice()); return; } if (type == rest::RequestType::PUT && len >= 2) { // extend an existing blocker auto id = static_cast<TRI_voc_tick_t>(StringUtils::uint64(suffixes[1])); bool parseSuccess = true; VPackSlice body = this->parseVPackBody(parseSuccess); if (!parseSuccess || !body.isObject()) { // error already created return; } // extract ttl. Context uses initial ttl from batch creation, if `ttl == 0` auto ttl = VelocyPackHelper::getNumericValue<double>(body, "ttl", replutils::BatchInfo::DefaultTimeout); auto res = _manager->extendLifetime(id, ttl); if (res.fail()) { generateError(std::move(res).result()); return; } SyncerId const syncerId = std::get<SyncerId>(res.get()); arangodb::ServerId const clientId = std::get<arangodb::ServerId>(res.get()); std::string const& clientInfo = std::get<std::string>(res.get()); // last tick value in context should not have changed compared to the // initial tick value used in the context (it's only updated on bind() // call, which is only executed when a batch is initially created) _vocbase.replicationClients().extend(syncerId, clientId, clientInfo, ttl); resetResponse(rest::ResponseCode::NO_CONTENT); return; } if (type == rest::RequestType::DELETE_REQ && len >= 2) { // delete an existing blocker auto id = static_cast<TRI_voc_tick_t>(StringUtils::uint64(suffixes[1])); bool found = _manager->remove(id); if (found) { resetResponse(rest::ResponseCode::NO_CONTENT); } else { int res = TRI_ERROR_CURSOR_NOT_FOUND; generateError(GeneralResponse::responseCode(res), res); } return; } // we get here if anything above is invalid generateError(rest::ResponseCode::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); } // handled by the batch for rocksdb // TODO: remove after release of 3.8 void RocksDBRestReplicationHandler::handleCommandBarrier() { auto const type = _request->requestType(); if (type == rest::RequestType::POST) { VPackBuilder b; b.add(VPackValue(VPackValueType::Object)); // always return a non-0 barrier id // it will be ignored by the client anyway for the RocksDB engine std::string const idString = std::to_string(TRI_NewTickServer()); b.add("id", VPackValue(idString)); b.close(); generateResult(rest::ResponseCode::OK, b.slice()); } else if (type == rest::RequestType::PUT || type == rest::RequestType::DELETE_REQ) { resetResponse(rest::ResponseCode::NO_CONTENT); } else if (type == rest::RequestType::GET) { generateResult(rest::ResponseCode::OK, VPackSlice::emptyArraySlice()); } } void RocksDBRestReplicationHandler::handleCommandLoggerFollow() { bool useVst = false; if (_request->transportType() == Endpoint::TransportType::VST) { useVst = true; } // determine start and end tick TRI_voc_tick_t tickStart = 0; TRI_voc_tick_t tickEnd = UINT64_MAX; bool found; std::string const& value1 = _request->value("from", found); if (found) { tickStart = static_cast<TRI_voc_tick_t>(StringUtils::uint64(value1)); } // determine end tick for dump std::string const& value2 = _request->value("to", found); if (found) { tickEnd = static_cast<TRI_voc_tick_t>(StringUtils::uint64(value2)); } if (found && (tickStart > tickEnd || tickEnd == 0)) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid from/to values"); return; } // add client arangodb::ServerId const clientId{ StringUtils::uint64(_request->value("serverId"))}; SyncerId const syncerId = SyncerId::fromRequest(*_request); std::string const clientInfo = _request->value("clientInfo"); bool includeSystem = _request->parsedValue("includeSystem", true); auto chunkSize = _request->parsedValue<uint64_t>("chunkSize", 1024 * 1024); ExecContextSuperuserScope escope(ExecContext::current().isAdminUser()); // extract collection DataSourceId cid = DataSourceId::none(); std::string const& value6 = _request->value("collection", found); if (found) { auto c = _vocbase.lookupCollection(value6); if (c == nullptr) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND); return; } cid = c->id(); } auto trxContext = transaction::StandaloneContext::Create(_vocbase); VPackBuilder builder(trxContext->getVPackOptions()); builder.openArray(); auto result = tailWal(&_vocbase, tickStart, tickEnd, static_cast<size_t>(chunkSize), includeSystem, cid, builder); builder.close(); auto data = builder.slice(); uint64_t const latest = latestSequenceNumber(); if (result.fail()) { generateError(GeneralResponse::responseCode(result.errorNumber()), result.errorNumber(), result.errorMessage()); return; } TRI_ASSERT(latest >= result.maxTick()); bool const checkMore = (result.maxTick() > 0 && result.maxTick() < latest); // generate the result size_t length = data.length(); TRI_ASSERT(length == 0 || result.maxTick() > 0); if (length == 0) { resetResponse(rest::ResponseCode::NO_CONTENT); } else { resetResponse(rest::ResponseCode::OK); } // transfer ownership of the buffer contents _response->setContentType(rest::ContentType::DUMP); // set headers _response->setHeaderNC(StaticStrings::ReplicationHeaderCheckMore, checkMore ? "true" : "false"); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastIncluded, StringUtils::itoa((length == 0) ? 0 : result.maxTick())); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastTick, StringUtils::itoa(latest)); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastScanned, StringUtils::itoa(result.lastScannedTick())); _response->setHeaderNC(StaticStrings::ReplicationHeaderActive, "true"); // TODO remove _response->setHeaderNC(StaticStrings::ReplicationHeaderFromPresent, result.minTickIncluded() ? "true" : "false"); if (length > 0) { if (useVst) { for (auto message : arangodb::velocypack::ArrayIterator(data)) { _response->addPayload(VPackSlice(message), trxContext->getVPackOptions(), true); } } else { HttpResponse* httpResponse = dynamic_cast<HttpResponse*>(_response.get()); if (httpResponse == nullptr) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "invalid response type"); } basics::StringBuffer& buffer = httpResponse->body(); arangodb::basics::VPackStringBufferAdapter adapter(buffer.stringBuffer()); // note: we need the CustomTypeHandler here VPackDumper dumper(&adapter, trxContext->getVPackOptions()); for (auto marker : arangodb::velocypack::ArrayIterator(data)) { dumper.dump(marker); httpResponse->body().appendChar('\n'); // LOG_TOPIC("2c0b2", INFO, Logger::REPLICATION) << // marker.toJson(trxContext->getVPackOptions()); } } } // insert the start tick (minus 1 to be on the safe side) as the // minimum tick we need to keep on the master. we cannot be sure // the master's response makes it to the slave safely, so we must // not insert the maximum of the WAL entries we sent. if we did, // and the response does not make it to the slave, the master will // note a higher tick than the slave will have received, which may // lead to the master eventually deleting a WAL section that the // slave will still request later double ttl = _request->parsedValue("ttl", replutils::BatchInfo::DefaultTimeout); _vocbase.replicationClients().track(syncerId, clientId, clientInfo, tickStart == 0 ? 0 : tickStart - 1, ttl); } /// @brief run the command that determines which transactions were open at /// a given tick value /// this is an internal method use by ArangoDB's replication that should not /// be called by client drivers directly void RocksDBRestReplicationHandler::handleCommandDetermineOpenTransactions() { generateResult(rest::ResponseCode::OK, VPackSlice::emptyArraySlice()); // rocksdb only includes finished transactions in the WAL. _response->setContentType(rest::ContentType::DUMP); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastTick, "0"); // always true to satisfy continuous syncer _response->setHeaderNC(StaticStrings::ReplicationHeaderFromPresent, "true"); } void RocksDBRestReplicationHandler::handleCommandInventory() { bool found; std::string batchId = _request->value("batchId", found); if (!found) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND, "batchId not specified"); return; } RocksDBReplicationContext* ctx = _manager->find(StringUtils::uint64(batchId)); RocksDBReplicationContextGuard guard(_manager, ctx); if (ctx == nullptr) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND, "context was not found"); return; } TRI_voc_tick_t tick = TRI_CurrentTickServer(); // include system collections? bool includeSystem = _request->parsedValue("includeSystem", true); bool includeFoxxQs = _request->parsedValue("includeFoxxQueues", false); // produce inventory for all databases? bool isGlobal = false; getApplier(isGlobal); VPackBuilder builder; builder.openObject(); // add collections and views Result res; if (isGlobal) { builder.add(VPackValue("databases")); res = ctx->getInventory(_vocbase, includeSystem, includeFoxxQs, true, builder); } else { ExecContextSuperuserScope escope(ExecContext::current().isAdminUser()); res = ctx->getInventory(_vocbase, includeSystem, includeFoxxQs, false, builder); TRI_ASSERT(builder.hasKey("collections") && builder.hasKey("views")); } if (res.fail()) { generateError(rest::ResponseCode::BAD, res.errorNumber(), "inventory could not be created"); return; } const std::string snapTick = std::to_string(ctx->snapshotTick()); // <state> builder.add("state", VPackValue(VPackValueType::Object)); builder.add("running", VPackValue(true)); builder.add("lastLogTick", VPackValue(snapTick)); builder.add("lastUncommittedLogTick", VPackValue(snapTick)); builder.add("totalEvents", VPackValue(ctx->snapshotTick())); builder.add("time", VPackValue(utilities::timeString())); builder.close(); // </state> builder.add("tick", VPackValue(std::to_string(tick))); builder.close(); // Toplevel generateResult(rest::ResponseCode::OK, builder.slice()); } /// @brief produce list of keys for a specific collection void RocksDBRestReplicationHandler::handleCommandCreateKeys() { std::string const& collection = _request->value("collection"); if (collection.empty()) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid collection parameter"); return; } // to is ignored because the snapshot time is the latest point in time RocksDBReplicationContext* ctx = nullptr; // get batchId from url parameters bool found; std::string batchId = _request->value("batchId", found); // find context if (found) { ctx = _manager->find(StringUtils::uint64(batchId)); } RocksDBReplicationContextGuard guard(_manager, ctx); if (!found || ctx == nullptr) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND, "batchId not specified"); return; } // bind collection to context - will initialize iterator Result res; DataSourceId cid; uint64_t numDocs; std::tie(res, cid, numDocs) = ctx->bindCollectionIncremental(_vocbase, collection); if (res.fail()) { generateError(res); return; } // keysId = <batchId>-<cid> std::string keysId = StringUtils::itoa(ctx->id()); keysId.push_back('-'); keysId.append(StringUtils::itoa(cid.id())); VPackBuilder result; result.add(VPackValue(VPackValueType::Object)); result.add("id", VPackValue(keysId)); result.add("count", VPackValue(numDocs)); result.close(); generateResult(rest::ResponseCode::OK, result.slice()); } static std::pair<uint64_t, DataSourceId> extractBatchAndCid(std::string const& input) { auto pos = input.find('-'); if (pos != std::string::npos && input.size() > pos + 1 && pos > 1) { return std::make_pair(StringUtils::uint64(input.c_str(), pos), DataSourceId{StringUtils::uint64(input.substr(pos + 1))}); } return std::make_pair(0, DataSourceId::none()); } /// @brief returns all key ranges void RocksDBRestReplicationHandler::handleCommandGetKeys() { std::vector<std::string> const& suffixes = _request->suffixes(); if (suffixes.size() != 2) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "expecting GET /_api/replication/keys/<keys-id>"); return; } static uint64_t const DefaultChunkSize = 5000; // determine chunk size uint64_t chunkSize = _request->parsedValue("chunkSize", DefaultChunkSize); if (chunkSize < 100) { chunkSize = DefaultChunkSize; } else if (chunkSize > 20000) { chunkSize = 20000; } // first suffix needs to be the key id std::string const& keysId = suffixes[1]; // <batchId>-<cid> uint64_t batchId; DataSourceId cid; std::tie(batchId, cid) = extractBatchAndCid(keysId); // get context RocksDBReplicationContext* ctx = _manager->find(batchId); // lock context RocksDBReplicationContextGuard guard(_manager, ctx); if (ctx == nullptr) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND, "batchId not specified, expired or invalid in another way"); return; } VPackBuffer<uint8_t> buffer; VPackBuilder builder(buffer); ctx->dumpKeyChunks(_vocbase, cid, builder, chunkSize); generateResult(rest::ResponseCode::OK, std::move(buffer)); } /// @brief returns date for a key range void RocksDBRestReplicationHandler::handleCommandFetchKeys() { std::vector<std::string> const& suffixes = _request->suffixes(); if (suffixes.size() != 2) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "expecting PUT /_api/replication/keys/<keys-id>"); return; } static uint64_t const DefaultChunkSize = 5000; // determine chunk size uint64_t chunkSize = _request->parsedValue("chunkSize", DefaultChunkSize); if (chunkSize < 100) { chunkSize = DefaultChunkSize; } else if (chunkSize > 20000) { chunkSize = 20000; } // chunk is supplied by old clients, low is an optimization // for rocksdb, because seeking should be cheaper size_t chunk = static_cast<size_t>(_request->parsedValue("chunk", uint64_t(0))); bool found; std::string const& lowKey = _request->value("low", found); std::string const& value = _request->value("type", found); bool keys = true; if (value == "keys") { keys = true; } else if (value == "docs") { keys = false; } else { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid 'type' value"); return; } // first suffix needs to be the key id std::string const& keysId = suffixes[1]; // <batchId>-<cid> uint64_t batchId; DataSourceId cid; std::tie(batchId, cid) = extractBatchAndCid(keysId); RocksDBReplicationContext* ctx = _manager->find(batchId); RocksDBReplicationContextGuard guard(_manager, ctx); if (ctx == nullptr) { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND, "batchId not specified or not found"); return; } auto transactionContext = transaction::StandaloneContext::Create(_vocbase); VPackBuffer<uint8_t> buffer; VPackBuilder builder(buffer, transactionContext->getVPackOptions()); if (keys) { Result rv = ctx->dumpKeys(_vocbase, cid, builder, chunk, static_cast<size_t>(chunkSize), lowKey); if (rv.fail()) { generateError(rv); return; } } else { size_t offsetInChunk = 0; size_t maxChunkSize = SIZE_MAX; std::string const& value2 = _request->value("offset", found); if (found) { offsetInChunk = static_cast<size_t>(StringUtils::uint64(value2)); // "offset" was introduced with ArangoDB 3.3. if the client sends it, // it means we can adapt the result size dynamically and the client // may refetch data for the same chunk maxChunkSize = 8 * 1024 * 1024; // if a client does not send an "offset" parameter at all, we are // not sure if it supports this protocol (3.2 and before) or not } bool success = false; VPackSlice const parsedIds = this->parseVPackBody(success); if (!success) { generateResult(rest::ResponseCode::BAD, VPackSlice()); return; } Result rv = ctx->dumpDocuments(_vocbase, cid, builder, chunk, static_cast<size_t>(chunkSize), offsetInChunk, maxChunkSize, lowKey, parsedIds); if (rv.fail()) { generateError(rv); return; } } generateResult(rest::ResponseCode::OK, std::move(buffer), transactionContext); } void RocksDBRestReplicationHandler::handleCommandRemoveKeys() { std::vector<std::string> const& suffixes = _request->suffixes(); if (suffixes.size() != 2) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "expecting DELETE /_api/replication/keys/<keys-id>"); return; } // first suffix needs to be the key id std::string const& keysId = suffixes[1]; // <batchId>-<cid> uint64_t batchId; DataSourceId cid; std::tie(batchId, cid) = extractBatchAndCid(keysId); RocksDBReplicationContext* ctx = _manager->find(batchId); RocksDBReplicationContextGuard guard(_manager, ctx); if (ctx != nullptr) { ctx->releaseIterators(_vocbase, cid); } VPackBuilder resultBuilder; resultBuilder.openObject(); resultBuilder.add("id", VPackValue(keysId)); // id as a string resultBuilder.add(StaticStrings::Error, VPackValue(false)); resultBuilder.add(StaticStrings::Code, VPackValue(static_cast<int>(rest::ResponseCode::ACCEPTED))); resultBuilder.close(); generateResult(rest::ResponseCode::ACCEPTED, resultBuilder.slice()); } void RocksDBRestReplicationHandler::handleCommandDump() { LOG_TOPIC("213e2", TRACE, arangodb::Logger::REPLICATION) << "enter handleCommandDump"; bool found = false; uint64_t contextId = 0; // contains dump options that might need to be inspected // VPackSlice options = _request->payload(); // get collection Name std::string const& cname = _request->value("collection"); if (cname.empty()) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid collection parameter"); return; } // get contextId std::string const& contextIdString = _request->value("batchId", found); if (found) { contextId = StringUtils::uint64(contextIdString); } else { generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_HTTP_BAD_PARAMETER, "replication dump - request misses batchId"); return; } // acquire context RocksDBReplicationContext* ctx = _manager->find(contextId, /*ttl*/ 0); RocksDBReplicationContextGuard guard(_manager, ctx); if (ctx == nullptr) { generateError( rest::ResponseCode::NOT_FOUND, TRI_ERROR_HTTP_BAD_PARAMETER, "replication dump - unable to find context (it could be expired)"); return; } // print request LOG_TOPIC("2b20f", TRACE, arangodb::Logger::REPLICATION) << "requested collection dump for collection '" << collection << "' using contextId '" << ctx->id() << "'"; ExecContextSuperuserScope escope(ExecContext::current().isAdminUser()); if (!ExecContext::current().canUseCollection(_vocbase.name(), cname, auth::Level::RO)) { generateError(rest::ResponseCode::FORBIDDEN, TRI_ERROR_FORBIDDEN); return; } uint64_t chunkSize = determineChunkSize(); size_t reserve = std::max<size_t>(chunkSize, 8192); RocksDBReplicationContext::DumpResult res(TRI_ERROR_NO_ERROR); if (_request->contentTypeResponse() == ContentType::VPACK) { VPackBuffer<uint8_t> buffer; buffer.reserve(reserve); // avoid reallocs auto trxCtx = transaction::StandaloneContext::Create(_vocbase); res = ctx->dumpVPack(_vocbase, cname, buffer, chunkSize); // generate the result if (res.fail()) { generateError(res.result()); } else if (buffer.byteSize() == 0) { resetResponse(rest::ResponseCode::NO_CONTENT); } else { resetResponse(rest::ResponseCode::OK); _response->setContentType(rest::ContentType::VPACK); _response->setPayload(std::move(buffer), *trxCtx->getVPackOptions(), /*resolveExternals*/ false); } // set headers _response->setHeaderNC(StaticStrings::ReplicationHeaderCheckMore, (res.hasMore ? "true" : "false")); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastIncluded, StringUtils::itoa(buffer.empty() ? 0 : res.includedTick)); } else { StringBuffer dump(reserve, false); // do the work! res = ctx->dumpJson(_vocbase, cname, dump, determineChunkSize()); if (res.fail()) { if (res.is(TRI_ERROR_BAD_PARAMETER)) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "replication dump - " + res.errorMessage()); return; } generateError(rest::ResponseCode::SERVER_ERROR, res.errorNumber(), "replication dump - " + res.errorMessage()); return; } // generate the result if (dump.length() == 0) { resetResponse(rest::ResponseCode::NO_CONTENT); } else { resetResponse(rest::ResponseCode::OK); } _response->setContentType(rest::ContentType::DUMP); // set headers _response->setHeaderNC(StaticStrings::ReplicationHeaderCheckMore, (res.hasMore ? "true" : "false")); _response->setHeaderNC(StaticStrings::ReplicationHeaderLastIncluded, StringUtils::itoa((dump.length() == 0) ? 0 : res.includedTick)); if (_request->transportType() == Endpoint::TransportType::HTTP) { auto response = dynamic_cast<HttpResponse*>(_response.get()); if (response == nullptr) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "invalid response type"); } // transfer ownership of the buffer contents response->body().set(dump.stringBuffer()); // avoid double freeing TRI_StealStringBuffer(dump.stringBuffer()); } else { _response->addRawPayload(VPackStringRef(dump.data(), dump.length())); _response->setGenerateBody(true); } } }
35.664499
108
0.678189
[ "object", "vector" ]
dce41d60026e348a2e4ec66481fa322d273158b8
3,653
cc
C++
src/examples/src/chat_vs_go.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
174
2016-10-10T12:47:01.000Z
2022-03-09T16:06:59.000Z
src/examples/src/chat_vs_go.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
5
2017-02-01T21:30:14.000Z
2018-09-09T10:02:00.000Z
src/examples/src/chat_vs_go.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
13
2016-10-10T12:19:14.000Z
2021-12-04T08:23:26.000Z
#include "boson/boson.h" #include "boson/logger.h" #include "boson/channel.h" #include "boson/net/socket.h" #include "boson/select.h" #include "boson/shared_buffer.h" #include "fmt/format.h" #include "iostream" #include <atomic> #include <chrono> #include <fcntl.h> #include <iostream> #include <netinet/tcp.h> #include <random> #include <set> #include <signal.h> #include <string> // sudo perf stat -e 'syscalls:sys_enter_epoll*' using namespace boson; using namespace std::chrono_literals; void listen_client(int fd, channel<std::string, 5> msg_chan) { boson::shared_buffer<std::array<char, 2048>> buffer; for (;;) { ssize_t nread = boson::read(fd, buffer.get().data(), buffer.get().size()); if (nread <= 1) { boson::close(fd); std::exit(1); return; } std::string message(buffer.get().data(), nread); if (message == "quit") { boson::close(fd); return; } msg_chan << message; } } void handleNewConnections(boson::channel<int, 5> newConnChan) { int yes = 1; int sockfd = net::create_listening_socket(8080); struct sockaddr_in cli_addr; socklen_t clilen = sizeof(cli_addr); for (;;) { int newFd = boson::accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); if (0 <= newFd) { if (::setsockopt(newFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) < 0) throw boson::exception("setsockopt"); newConnChan << newFd; } } } void displayCounter(std::atomic<uint64_t>* counter) { using namespace std::chrono; auto latest = high_resolution_clock::now(); milliseconds step_duration {1000}; //for (int i = 0;i < 60; ++i) { for (;;) { ::printf("%lu\n",counter->exchange(0,std::memory_order_relaxed)*1000/step_duration.count()); boson::sleep(1000ms); auto current = high_resolution_clock::now(); step_duration = duration_cast<milliseconds>(current - latest); latest = current; } std::exit(0); } int main(int argc, char *argv[]) { boson::debug::logger_instance(&std::cout); struct sigaction action {SIG_IGN,0,0}; ::sigaction(SIGPIPE, &action, nullptr); boson::run(2, []() { channel<int, 5> new_connection; channel<std::string, 5> messages; std::atomic<uint64_t> counter {0}; boson::start(displayCounter, &counter); boson::start(handleNewConnections, new_connection); // Create socket and list to connections // Main loop //std::set<int> conns; size_t cumulatedCounter = 0; std::vector<int> conns; std::minstd_rand rand(std::random_device{}()); while(cumulatedCounter < 1e7) { int conn = 0; int scheduler = 0; std::string message; select_any( // event_read(new_connection, conn, // [&](bool) { // conns.push_back(conn); //start_explicit(++scheduler % 3 + 1, listen_client, conn, messages); start(listen_client, conn, messages); }), event_read(messages, message, [&](bool result) { // if (result) { message += "\n"; std::uniform_int_distribution<size_t> dist(0, conns.size() - 1); ssize_t rc = boson::write(conns[dist(rand)], message.data(), message.size()); if (rc < 0) std::exit(1); auto value = counter.fetch_add(1, std::memory_order_relaxed); ++cumulatedCounter; } })); }; std::exit(0); }); }
31.222222
102
0.576512
[ "vector" ]
dce6aad8069b0ddbcabc65c0b83cea9f26fee194
1,950
hpp
C++
include/NUnit/Framework/Interfaces/NodeList.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/NUnit/Framework/Interfaces/NodeList.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/NUnit/Framework/Interfaces/NodeList.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: NUnit::Framework::Interfaces namespace NUnit::Framework::Interfaces { // Forward declaring type: TNode class TNode; } // Completed forward declares // Type namespace: NUnit.Framework.Interfaces namespace NUnit::Framework::Interfaces { // WARNING Size may be invalid! // Autogenerated type: NUnit.Framework.Interfaces.NodeList class NodeList : public System::Collections::Generic::List_1<NUnit::Framework::Interfaces::TNode*> { public: // Creating value type constructor for type: NodeList NodeList() noexcept {} // public System.Void .ctor() // Offset: 0x1716D0C // Implemented from: System.Collections.Generic.List`1 // Base method: System.Void List_1::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NodeList* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("NUnit::Framework::Interfaces::NodeList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NodeList*, creationType>())); } }; // NUnit.Framework.Interfaces.NodeList } DEFINE_IL2CPP_ARG_TYPE(NUnit::Framework::Interfaces::NodeList*, "NUnit.Framework.Interfaces", "NodeList");
46.428571
118
0.704615
[ "object" ]
dce6aba043ba5dba90eff4d17035409f5f0afb6f
4,986
cpp
C++
Code/src/fftTools/FFTMD.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/src/fftTools/FFTMD.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/src/fftTools/FFTMD.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <cassert> #include <cmath> #include <vector> #include "DBox.H" #include "RectMDArray.H" //#include "CH_Timer.H" #include "FFT1D.H" #include "FFTMD.H" using namespace std; FFTMD::FFTMD(shared_ptr<FFT1D> a_fft1dPtr) { m_fft1dPtr = a_fft1dPtr; m_M = m_fft1dPtr->getM(); m_N = m_fft1dPtr->getN(); }; void FFTMD::define(shared_ptr<FFT1D> a_fft1dPtr) { m_fft1dPtr = a_fft1dPtr; m_M = m_fft1dPtr->getM(); m_N = m_fft1dPtr->getN(); }; void FFTMD::forwardCC(RectMDArray<complex<double> > & a_f) const { vector<complex<double> > f1d(m_N); vector<complex<double> > fHat1d(m_N); // CH_TIMERS("fftmdForward"); // CH_TIMER("fft1d",t1); int low[DIM],high[DIM]; for (int dir = 0;dir < DIM; dir++) { for (int dir2 = 0;dir2 < DIM;dir2++) { low[dir2]= 0; high[dir2] = m_N-1; } high[dir]=0; Point lo(low),hi(high); // cout << DIM << " " << m_N << " " << hi[0] << " " << hi[1] << " " << hi[2] << endl; DBox base(lo,hi); // int offset = Power(m_N+1,dir); Point edir = getUnitv(dir); for (Point pt=base.getLowCorner();base.notDone(pt);base.increment(pt)) { for (int l = 0 ; l < m_N;l++) { f1d[l] = a_f[pt + edir*l]; } // CH_START(t1); m_fft1dPtr->forwardFFTCC(fHat1d,f1d); // CH_STOP(t1); for (int l = 0 ; l < m_N;l++) { a_f[pt + edir*l] = fHat1d[l]; } //cout << "In FFTMD: " << ztot // << " , " << a_f[pt] << " , dir = " << dir << endl; //cout << counter << endl; } } }; void FFTMD::inverseCC(RectMDArray<complex<double> > & a_fHat) const {int low[DIM],high[DIM]; // CH_TIMERS("fftmdInverse"); // CH_TIMER("fft1drev",t3); vector<complex<double> > f1d(m_N); vector<complex<double> > fHat1d(m_N); for (int dir = 0;dir < DIM ; dir++) { for (int dir2 = 0;dir2 < DIM;dir2++) { low[dir2]= 0; high[dir2] = m_N-1; } high[dir]=0; // int offset = Power(m_N+1,dir); DBox base(low,high); Point edir = getUnitv(dir); for (Point pt=base.getLowCorner();base.notDone(pt);base.increment(pt)) { //complex<double>* foo = &a_fHat.getPointer()[base.getIndex(pt)]; for (int l = 0 ; l < m_N;l++) { fHat1d[l] =a_fHat[pt + edir*l]; } // CH_START(t3); m_fft1dPtr->inverseFFTCC(f1d,fHat1d); // CH_STOP(t3); for (int l = 0 ; l < m_N;l++) { a_fHat[pt + edir*l] = f1d[l]; } } } }; const int& FFTMD::getN() const { return m_N; }; const int& FFTMD::getM() const { return m_M; }; void FFTMD::forwardCCcen(RectMDArray<complex<double> > & a_f) const { int low[DIM],high[DIM]; vector<complex<double> > f1d(m_N); vector<complex<double> > fHat1d(m_N); // CH_TIMERS("fftmdForward"); // CH_TIMER("fft1d",t1); for (int dir = 0;dir < DIM; dir++) { for (int dir2 = 0;dir2 < DIM;dir2++) { low[dir2]= -m_N/2; high[dir2] = m_N/2-1; } high[dir]=0; low[dir]=0; DBox base(low,high); Point edir = getUnitv(dir); for (Point pt=base.getLowCorner();base.notDone(pt);base.increment(pt)) { for (int l = 0 ; l < m_N/2;l++) { f1d[l] = a_f[pt + edir*l]; f1d[m_N - l-1] = a_f[pt-edir*(l+1)]; } // CH_START(t1); m_fft1dPtr->forwardFFTCC(fHat1d,f1d); // CH_STOP(t1); for (int l = 0 ; l < m_N/2;l++) { a_f[pt + edir*l] = fHat1d[l]; a_f[pt-edir*(l+1)] = fHat1d[m_N-l-1]; } } } }; void FFTMD::inverseCCcen(RectMDArray<complex<double> > & a_fHat) const {int low[DIM],high[DIM]; // CH_TIMERS("fftmdInverse"); // CH_TIMER("fft1drev",t3); vector<complex<double> > f1d(m_N); vector<complex<double> > fHat1d(m_N); for (int dir = 0;dir < DIM ; dir++) { for (int dir2 = 0;dir2 < DIM;dir2++) { low[dir2]= -m_N/2; high[dir2] = m_N/2-1; } high[dir]=0; low[dir]=0; // int offset = Power(m_N+1,dir); DBox base(low,high); Point edir = getUnitv(dir); for (Point pt=base.getLowCorner();base.notDone(pt);base.increment(pt)) { for (int l = 0 ; l < m_N/2;l++) { fHat1d[l] = a_fHat[pt + edir*l]; fHat1d[m_N - l-1] = a_fHat[pt-edir*(l+1)]; } // CH_START(t3); m_fft1dPtr->inverseFFTCC(f1d,fHat1d); // CH_STOP(t3); for (int l = 0 ; l < m_N/2;l++) { a_fHat[pt + edir*l] = f1d[l]; a_fHat[pt-edir*(l+1)] = f1d[m_N - l-1]; } } } };
26.663102
90
0.484557
[ "vector" ]
dcec663bfda18a08cb4b2028736643fcc0e7cc58
2,573
cpp
C++
Plugins/uk.ac.kcl.VesselMeshing/src/internal/MeshingUtils.cpp
carthurs/CRIMSONGUI
1464df9c4d04cf3ba131ca90b91988a06845c68e
[ "BSD-3-Clause" ]
10
2020-09-17T18:55:31.000Z
2022-02-23T02:52:38.000Z
Plugins/uk.ac.kcl.VesselMeshing/src/internal/MeshingUtils.cpp
carthurs/CRIMSONGUI
1464df9c4d04cf3ba131ca90b91988a06845c68e
[ "BSD-3-Clause" ]
null
null
null
Plugins/uk.ac.kcl.VesselMeshing/src/internal/MeshingUtils.cpp
carthurs/CRIMSONGUI
1464df9c4d04cf3ba131ca90b91988a06845c68e
[ "BSD-3-Clause" ]
3
2021-05-19T09:02:21.000Z
2021-07-26T17:39:57.000Z
#include "MeshingUtils.h" #include <HierarchyManager.h> #include <VascularModelingNodeTypes.h> #include <VesselMeshingNodeTypes.h> #include <boost/format.hpp> namespace crimson { MeshingParametersData* MeshingUtils::getMeshingParametersForSolid(mitk::DataNode* solidNode) { if (!solidNode) { return nullptr; } auto hm = crimson::HierarchyManager::getInstance(); crimson::HierarchyManager::NodeType ownerNodeType = crimson::VascularModelingNodeTypes::VesselPath(); mitk::DataNode::Pointer meshingParametersOwnerNode = hm->getAncestor(solidNode, crimson::VascularModelingNodeTypes::VesselPath()); if (meshingParametersOwnerNode.IsNull()) { // Put the meshing parameters under the vessel tree node if it's available ownerNodeType = crimson::VascularModelingNodeTypes::VesselTree(); meshingParametersOwnerNode = hm->getAncestor(solidNode, crimson::VascularModelingNodeTypes::VesselTree()); } if (meshingParametersOwnerNode.IsNull()) { // Alternatively, e.g. for imported models, put meshing parameters under the solid model itself // The drawback in this case is that the meshing parameters will be deleted along with the solid model // itself and cannot be reused MITK_WARN << "No suitable owner for meshing parameters data found. Using the solid itself"; ownerNodeType = crimson::VascularModelingNodeTypes::Solid(); meshingParametersOwnerNode = solidNode; } mitk::DataNode::Pointer currentMeshingParametersNode = hm->getFirstDescendant(meshingParametersOwnerNode, crimson::VesselMeshingNodeTypes::MeshingParameters(), true); if (!currentMeshingParametersNode) { // Create the meshing parameters node if it doesn't exist currentMeshingParametersNode = mitk::DataNode::New(); currentMeshingParametersNode->SetName(meshingParametersOwnerNode->GetName() + " Meshing Parameters"); currentMeshingParametersNode->SetBoolProperty("hidden object", true); currentMeshingParametersNode->SetData(crimson::MeshingParametersData::New()); hm->addNodeToHierarchy(meshingParametersOwnerNode, ownerNodeType, currentMeshingParametersNode, crimson::VesselMeshingNodeTypes::MeshingParameters()); } return static_cast<crimson::MeshingParametersData*>(currentMeshingParametersNode->GetData()); } crimson::AsyncTaskManager::TaskUID MeshingUtils::getMeshingTaskUID(mitk::DataNode* solidNode) { if (!solidNode) { return ""; } return (boost::format("Meshing %1%") % solidNode).str(); } }
42.180328
170
0.74349
[ "object", "model", "solid" ]
dcee58d4a7daa0060a4a5448b65cdf9cc6ee3b13
12,921
cpp
C++
test/op/CropAndResizeTest.cpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
1
2021-02-03T07:50:59.000Z
2021-02-03T07:50:59.000Z
test/op/CropAndResizeTest.cpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
null
null
null
test/op/CropAndResizeTest.cpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
null
null
null
// // CropAndResizeTest.cpp // MNNTests // // Created by MNN on 2019/01/15. // Copyright © 2018, Alibaba Group Holding Limited // #include "Interpreter.hpp" #include "MNNTestSuite.h" #include "MNN_generated.h" #include "Session.hpp" #include "TensorUtils.hpp" #include "TensorUtils.hpp" #include "TestUtils.h" using namespace MNN; static Interpreter *create(CropAndResizeMethod method, float e, int n, int b, int c, int h, int w, int ch, int cw) { flatbuffers::FlatBufferBuilder fbb; std::vector<flatbuffers::Offset<Op>> vec; std::vector<flatbuffers::Offset<flatbuffers::String>> ns; { auto dims = fbb.CreateVector(std::vector<int>({b, h, w, c})); InputBuilder ib(fbb); ib.add_dims(dims); ib.add_dtype(DataType_DT_FLOAT); auto input = ib.Finish(); auto name = fbb.CreateString("image"); auto iv = fbb.CreateVector(std::vector<int>({0})); auto ov = fbb.CreateVector(std::vector<int>({0})); OpBuilder builder(fbb); builder.add_type(OpType_Input); builder.add_name(name); builder.add_inputIndexes(iv); builder.add_outputIndexes(ov); builder.add_main_type(OpParameter_Input); builder.add_main(flatbuffers::Offset<void>(input.o)); vec.push_back(builder.Finish()); ns.push_back(name); } { auto dims = fbb.CreateVector(std::vector<int>({n, 4})); InputBuilder ib(fbb); ib.add_dims(dims); ib.add_dtype(DataType_DT_FLOAT); auto input = ib.Finish(); auto name = fbb.CreateString("boxes"); auto iv = fbb.CreateVector(std::vector<int>({1})); auto ov = fbb.CreateVector(std::vector<int>({1})); OpBuilder builder(fbb); builder.add_type(OpType_Input); builder.add_name(name); builder.add_inputIndexes(iv); builder.add_outputIndexes(ov); builder.add_main_type(OpParameter_Input); builder.add_main(flatbuffers::Offset<void>(input.o)); vec.push_back(builder.Finish()); ns.push_back(name); } { auto dims = fbb.CreateVector(std::vector<int>({n})); InputBuilder ib(fbb); ib.add_dims(dims); ib.add_dtype(DataType_DT_INT32); auto input = ib.Finish(); auto name = fbb.CreateString("indexes"); auto iv = fbb.CreateVector(std::vector<int>({2})); auto ov = fbb.CreateVector(std::vector<int>({2})); OpBuilder builder(fbb); builder.add_type(OpType_Input); builder.add_name(name); builder.add_inputIndexes(iv); builder.add_outputIndexes(ov); builder.add_main_type(OpParameter_Input); builder.add_main(flatbuffers::Offset<void>(input.o)); vec.push_back(builder.Finish()); ns.push_back(name); } { auto dims = fbb.CreateVector(std::vector<int>({2})); auto data = fbb.CreateVector(std::vector<int>({ch, cw})); BlobBuilder ib(fbb); ib.add_dims(dims); ib.add_dataType(DataType_DT_INT32); ib.add_dataFormat(MNN_DATA_FORMAT_NHWC); ib.add_int32s(data); auto input = ib.Finish(); auto name = fbb.CreateString("size"); auto iv = fbb.CreateVector(std::vector<int>({})); auto ov = fbb.CreateVector(std::vector<int>({3})); OpBuilder builder(fbb); builder.add_type(OpType_Const); builder.add_name(name); builder.add_inputIndexes(iv); builder.add_outputIndexes(ov); builder.add_main_type(OpParameter_Blob); builder.add_main(flatbuffers::Offset<void>(input.o)); vec.push_back(builder.Finish()); ns.push_back(name); } { auto name = fbb.CreateString("car"); auto carb = CropAndResizeBuilder(fbb); carb.add_extrapolationValue(e); carb.add_method(method); auto car = carb.Finish(); auto iv = fbb.CreateVector(std::vector<int>({0, 1, 2, 3})); auto ov = fbb.CreateVector(std::vector<int>({4})); OpBuilder builder(fbb); builder.add_type(OpType_CropAndResize); builder.add_name(name); builder.add_inputIndexes(iv); builder.add_outputIndexes(ov); builder.add_main_type(OpParameter_CropAndResize); builder.add_main(flatbuffers::Offset<void>(car.o)); vec.push_back(builder.Finish()); ns.push_back(name); } BlobBuilder fb(fbb); fb.add_dataType(DataType_DT_FLOAT); fb.add_dataFormat(MNN_DATA_FORMAT_NHWC); auto flt = fb.Finish(); BlobBuilder qb(fbb); qb.add_dataType(DataType_DT_INT32); qb.add_dataFormat(MNN_DATA_FORMAT_NHWC); auto qnt = qb.Finish(); std::vector<flatbuffers::Offset<TensorDescribe>> desc; { TensorDescribeBuilder tdb(fbb); tdb.add_index(0); tdb.add_blob(flatbuffers::Offset<Blob>(flt.o)); desc.push_back(tdb.Finish()); } { TensorDescribeBuilder tdb(fbb); tdb.add_index(1); tdb.add_blob(flatbuffers::Offset<Blob>(flt.o)); desc.push_back(tdb.Finish()); } { TensorDescribeBuilder tdb(fbb); tdb.add_index(2); tdb.add_blob(flatbuffers::Offset<Blob>(qnt.o)); desc.push_back(tdb.Finish()); } { TensorDescribeBuilder tdb(fbb); tdb.add_index(3); tdb.add_blob(flatbuffers::Offset<Blob>(qnt.o)); desc.push_back(tdb.Finish()); } { TensorDescribeBuilder tdb(fbb); tdb.add_index(4); tdb.add_blob(flatbuffers::Offset<Blob>(flt.o)); desc.push_back(tdb.Finish()); } auto ops = fbb.CreateVector(vec); auto names = fbb.CreateVector(ns); auto extras = fbb.CreateVector(desc); NetBuilder net(fbb); net.add_oplists(ops); net.add_tensorName(names); net.add_extraTensorDescribe(extras); net.add_sourceType(NetSource_TENSORFLOW); fbb.Finish(net.Finish()); return Interpreter::createFromBuffer((const char *)fbb.GetBufferPointer(), fbb.GetSize()); } static Tensor *infer(const Interpreter *net, Session *session) { net->runSession(session); return net->getSessionOutputAll(session).begin()->second; } class CropAndResizeTest : public MNNTestCase { public: virtual ~CropAndResizeTest() = default; virtual void run() { int methods[] = {CropAndResizeMethod_BILINEAR, CropAndResizeMethod_NEAREST}; for (int m = 0; m < sizeof(methods) / sizeof(int); m++) { CropAndResizeMethod method = (CropAndResizeMethod)m; for (int n = 1; n <= 4; n *= 2) { for (int b = 1; b <= 2; b++) { for (int c = 1; c <= 8; c *= 2) { for (int h = 1; h <= 8; h *= 2) { for (int w = 1; w <= 8; w *= 2) { dispatch([&](MNNForwardType backend) -> void { if (backend == MNN_FORWARD_CPU) return; float e = rand() % 255 / 255.f; int ch = rand() % 4 + 1; int cw = rand() % 4 + 1; // nets auto net = create(method, e, n, b, c, h, w, ch, cw); auto CPU = createSession(net, MNN_FORWARD_CPU); auto GPU = createSession(net, backend); if (!CPU || !GPU) { delete net; return; } // image auto image = new Tensor(4, Tensor::TENSORFLOW); { image->setType(DataType_DT_FLOAT); image->buffer().dim[0].extent = b; image->buffer().dim[1].extent = h; image->buffer().dim[2].extent = w; image->buffer().dim[3].extent = c; TensorUtils::setLinearLayout(image); image->buffer().host = (uint8_t *)malloc(image->size()); for (int i = 0; i < b * c * h * w; i++) { image->host<float>()[i] = i + 1; // rand() % 255 / 255.f; } auto host = net->getSessionInput(CPU, "image"); auto device = net->getSessionInput(GPU, "image"); net->getBackend(CPU, host)->onCopyBuffer(image, host); net->getBackend(GPU, device)->onCopyBuffer(image, device); } // boxes auto boxes = new Tensor(2, Tensor::TENSORFLOW); { boxes->setType(DataType_DT_FLOAT); boxes->buffer().dim[0].extent = n; boxes->buffer().dim[1].extent = 4; TensorUtils::setLinearLayout(boxes); boxes->buffer().host = (uint8_t *)malloc(boxes->size()); for (int i = 0; i < n; i++) { auto y1 = rand() % 255 / 255.f * (h - ch); auto y2 = rand() % 255 / 255.f * (h - ch); auto x1 = rand() % 255 / 255.f * (w - cw); auto x2 = rand() % 255 / 255.f * (w - cw); boxes->host<float>()[i * 4 + 0] = std::min(y1, y2); boxes->host<float>()[i * 4 + 1] = std::min(x1, x2); boxes->host<float>()[i * 4 + 2] = std::max(y1, y2); boxes->host<float>()[i * 4 + 3] = std::max(x1, x2); } auto host = net->getSessionInput(CPU, "boxes"); auto device = net->getSessionInput(GPU, "boxes"); net->getBackend(CPU, host)->onCopyBuffer(boxes, host); net->getBackend(GPU, device)->onCopyBuffer(boxes, device); } // indexes auto indexes = new Tensor(1, Tensor::TENSORFLOW); { indexes->setType(DataType_DT_INT32); indexes->buffer().dim[0].extent = n; TensorUtils::setLinearLayout(indexes); indexes->buffer().host = (uint8_t *)malloc(indexes->size()); for (int i = 0; i < n; i++) { indexes->host<int>()[i] = rand() % n; } auto host = net->getSessionInput(CPU, "indexes"); auto device = net->getSessionInput(GPU, "indexes"); net->getBackend(CPU, host)->onCopyBuffer(indexes, host); net->getBackend(GPU, device)->onCopyBuffer(indexes, device); } // infer assert(TensorUtils::compareTensors(infer(net, GPU), infer(net, CPU), 0.01)); // clean up free(image->buffer().host); free(boxes->buffer().host); free(indexes->buffer().host); delete image; delete boxes; delete indexes; delete net; }); } } } } } } } }; MNNTestSuiteRegister(CropAndResizeTest, "op/crop_and_resize");
44.25
116
0.460645
[ "vector" ]
fd60471e276a0b189c359030b25f9dbf9f3240e2
8,623
cpp
C++
src/core/exact_img.cpp
LeeZQiang/also
f343bb3f9031f1fa407bda668046ecf8bceeff1b
[ "MIT" ]
1
2019-09-17T10:55:55.000Z
2019-09-17T10:55:55.000Z
src/core/exact_img.cpp
LeeZQiang/also
f343bb3f9031f1fa407bda668046ecf8bceeff1b
[ "MIT" ]
null
null
null
src/core/exact_img.cpp
LeeZQiang/also
f343bb3f9031f1fa407bda668046ecf8bceeff1b
[ "MIT" ]
null
null
null
/* also: Advanced Logic Synthesis and Optimization tool * Copyright (C) 2019- Ningbo University, Ningbo, China * * 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 <percy/percy.hpp> #include <mockturtle/utils/stopwatch.hpp> #include "exact_img.hpp" #include "../networks/img/img.hpp" #include "../networks/img/img_rewrite.hpp" using namespace percy; using namespace mockturtle; namespace also { /****************************************************************************** * Types * ******************************************************************************/ /****************************************************************************** * Private functions * ******************************************************************************/ /****************************************************************************** * Public functions * ******************************************************************************/ /* AIG-based exact synthesis */ img_network img_from_aig_chain( chain& c ) { img_network img; int nr_in = c.get_nr_inputs(); std::vector<img_network::signal> sigs; sigs.push_back( img.get_constant( false ) ); for( int i = 0; i < nr_in; i++ ) { sigs.push_back( img.create_pi() ); } for( size_t i = 0; i < c.get_nr_steps(); i++ ) { const auto& step = c.get_step( i ); const auto idx = nr_in + i + 1; const auto op = c.get_operator( i ); auto ops = kitty::to_binary( op ); if( ops == "0010" ) { sigs.push_back( img.create_op1( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else if( ops == "1110" ) { sigs.push_back( img.create_op2( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else if( ops == "1000" ) { sigs.push_back( img.create_op3( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else if( ops == "0100" ) { sigs.push_back( img.create_op4( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else { assert( false && "UNKNOWN OPS" ); } } auto top = c.is_output_inverted( 0 ) ? !sigs[ sigs.size() - 1 ] : sigs[ sigs.size() - 1 ]; img.create_po( top ); return img; } void img_from_aig_syn( const kitty::dynamic_truth_table& tt, const bool& verbose ) { chain c; spec spec; spec.verbosity = 0; bsat_wrapper solver; ssv_encoder encoder( solver ); spec.fanin = 2; //each node has at most 2 fanins, while it equals 3 for MAJ synthesis spec.set_primitive( AIG ); spec[0] = tt; if( verbose ) { std::cout << "Synthesizing function " << kitty::to_hex( spec[0] ) << std::endl; } stopwatch<>::duration time{0}; int nr_solutions = 0; { stopwatch t( time ); //synthesis int min_num_gates = INT_MAX; img_network best_img; while (next_solution(spec, c, solver, encoder) == success) { //c.print_expression(); auto tts = c.simulate(); assert( tts[0] == spec[0] ); assert( c.is_aig() ); nr_solutions++; auto r = c; auto img = img_from_aig_chain( r ); //printf( "IMG size: %d\n", img.num_gates() ); auto img_new = img_rewriting( img ); if( img_new.num_gates() < min_num_gates ) { min_num_gates = img_new.num_gates(); best_img = img_new; } if( verbose ) { printf( "NEW IMG size: %d\n", img_new.num_gates() ); img_to_expression( std::cout, img_new); } } if( nr_solutions != 0 ) { printf( "[i]: found img_network with minimum number of gates: %d\n", min_num_gates ); img_to_expression( std::cout, best_img ); } } if( verbose ) { std::cout << fmt::format( "[i]: {:5.2f} seconds passed to enumerate {} solutions\n", to_seconds( time ), nr_solutions ); } } /* IIG-based exact synthesis */ /* img_network img_from_iig_chain( chain& c ) { img_network img; int nr_in = c.get_nr_inputs(); std::vector<img_network::signal> sigs; sigs.push_back( img.get_constant( false ) ); for( int i = 0; i < nr_in; i++ ) { sigs.push_back( img.create_pi() ); } for( size_t i = 0; i < c.get_nr_steps(); i++ ) { const auto& step = c.get_step( i ); const auto idx = nr_in + i + 1; const auto op = c.get_operator( i ); auto ops = kitty::to_binary( op ); if( ops == "0010" ) { sigs.push_back( img.create_imp( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else if( ops == "0001" ) { sigs.push_back( img.create_dir_or( sigs[ step[0] + 1 ], sigs[ step[1] + 1] ) ); } else if( ops == "1000" ) { sigs.push_back( img.create_imp( sigs[ step[0] + 1 ], img.create_dir_not( sigs[ step[1] + 1] ) ) ); } else if( ops == "0100" ) { sigs.push_back( img.create_imp( sigs[ step[1] + 1 ], sigs[ step[0] + 1] ) ); } else { assert( false && "UNKNOWN OPS" ); } } auto top = c.is_output_inverted( 0 ) ? !sigs[ sigs.size() - 1 ] : sigs[ sigs.size() - 1 ]; img.create_po( top ); return img; } void img_from_iig_syn( const kitty::dynamic_truth_table& tt, const bool& verbose ) { chain c; spec spec; spec.verbosity = 0; bsat_wrapper solver; ssv_encoder encoder( solver ); spec.fanin = 2; //each node has at most 2 fanins, while it equals 3 for MAJ synthesis spec.set_primitive( IIG ); spec[0] = tt; if( verbose ) { std::cout << "Synthesizing function " << kitty::to_hex( spec[0] ) << std::endl; } stopwatch<>::duration time{0}; int nr_solutions = 0; { stopwatch t( time ); //synthesis int min_num_gates = INT_MAX; img_network best_img; while (next_solution(spec, c, solver, encoder) == success) { //c.print_expression(); auto tts = c.simulate(); assert( tts[0] == spec[0] ); assert( c.is_iig() ); nr_solutions++; auto r = c; auto img = img_from_iig_chain( r ); //printf( "IMG size: %d\n", img.num_gates() ); auto img_new = img ; if( img_new.num_gates() < min_num_gates ) { min_num_gates = img_new.num_gates(); best_img = img_new; } if( verbose ) { printf( "NEW IMG size: %d\n", img_new.num_gates() ); img_to_expression( std::cout, img_new); } } if( nr_solutions != 0 ) { printf( "[i]: found img_network with minimum number of gates: %d\n", min_num_gates ); img_to_expression( std::cout, best_img ); } } if( verbose ) { std::cout << fmt::format( "[i]: {:5.2f} seconds passed to enumerate {} solutions\n", to_seconds( time ), nr_solutions ); } }*/ }
29.131757
94
0.499594
[ "vector" ]
fd64df54cb8a20fe53d19b36d8471787d3c64b89
5,115
cpp
C++
src/graph/planner/ngql/LookupPlanner.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-04-11T12:12:39.000Z
2020-04-11T12:12:39.000Z
src/graph/planner/ngql/LookupPlanner.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
24
2021-09-15T12:42:03.000Z
2021-09-16T04:59:19.000Z
src/graph/planner/ngql/LookupPlanner.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-08-03T10:19:39.000Z
2020-08-03T10:19:39.000Z
/* Copyright (c) 2021 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "graph/planner/ngql/LookupPlanner.h" #include <algorithm> #include <tuple> #include "common/base/Base.h" #include "common/base/Status.h" #include "common/expression/Expression.h" #include "common/expression/LabelAttributeExpression.h" #include "common/expression/PropertyExpression.h" #include "graph/context/ast/QueryAstContext.h" #include "graph/planner/Planner.h" #include "graph/planner/plan/Scan.h" #include "graph/visitor/FindVisitor.h" #include "parser/Clauses.h" #include "parser/TraverseSentences.h" namespace nebula { namespace graph { static std::tuple<const char*, const char*> kEdgeKeys[3] = { {kSrcVID, kSrc}, {kDstVID, kDst}, {kRanking, kRank}, }; std::unique_ptr<Planner> LookupPlanner::make() { return std::unique_ptr<LookupPlanner>(new LookupPlanner()); } bool LookupPlanner::match(AstContext* astCtx) { return astCtx->sentence->kind() == Sentence::Kind::kLookup; } StatusOr<SubPlan> LookupPlanner::transform(AstContext* astCtx) { auto lookupCtx = static_cast<LookupContext*>(astCtx); auto yieldCols = prepareReturnCols(lookupCtx); auto qctx = lookupCtx->qctx; auto from = static_cast<const LookupSentence*>(lookupCtx->sentence)->from(); SubPlan plan; if (lookupCtx->isEdge) { plan.tail = EdgeIndexFullScan::make(qctx, nullptr, from, lookupCtx->space.id, {}, returnCols_, lookupCtx->schemaId, lookupCtx->isEmptyResultSet); } else { plan.tail = TagIndexFullScan::make(qctx, nullptr, from, lookupCtx->space.id, {}, returnCols_, lookupCtx->schemaId, lookupCtx->isEmptyResultSet); } plan.tail->setColNames(colNames_); plan.root = plan.tail; if (lookupCtx->filter) { plan.root = Filter::make(qctx, plan.root, lookupCtx->filter); } plan.root = Project::make(qctx, plan.root, yieldCols); return plan; } YieldColumns* LookupPlanner::prepareReturnCols(LookupContext* lookupCtx) { auto pool = lookupCtx->qctx->objPool(); auto columns = pool->makeAndAdd<YieldColumns>(); auto addColumn = [this, pool, columns](const auto& tup) { std::string name(std::get<0>(tup)); auto expr = InputPropertyExpression::make(pool, name); columns->addColumn(new YieldColumn(expr, name)); addLookupColumns(std::get<1>(tup), name); }; if (lookupCtx->isEdge) { for (auto& key : kEdgeKeys) { addColumn(key); } } else { addColumn(std::make_tuple(kVertexID, kVid)); } extractUsedColumns(lookupCtx->filter); appendColumns(lookupCtx, columns); return columns; } void LookupPlanner::appendColumns(LookupContext* lookupCtx, YieldColumns* columns) { auto sentence = static_cast<LookupSentence*>(lookupCtx->sentence); auto yieldClause = sentence->yieldClause(); if (yieldClause == nullptr) return; auto pool = lookupCtx->qctx->objPool(); for (auto col : yieldClause->columns()) { auto expr = col->expr(); DCHECK(expr->kind() == Expression::Kind::kLabelAttribute); auto laExpr = static_cast<LabelAttributeExpression*>(expr); const auto& schemaName = laExpr->left()->name(); const auto& colName = laExpr->right()->value().getStr(); Expression* propExpr = nullptr; if (lookupCtx->isEdge) { propExpr = EdgePropertyExpression::make(pool, schemaName, colName); } else { propExpr = TagPropertyExpression::make(pool, schemaName, colName); } columns->addColumn(new YieldColumn(propExpr, col->alias())); addLookupColumns(colName, propExpr->toString()); } } void LookupPlanner::extractUsedColumns(Expression* filter) { if (filter == nullptr) return; auto finder = [](Expression* expr) { return expr->kind() == Expression::Kind::kTagProperty || expr->kind() == Expression::Kind::kEdgeProperty; }; FindVisitor visitor(finder, true); filter->accept(&visitor); for (auto expr : std::move(visitor).results()) { auto propExpr = static_cast<const PropertyExpression*>(expr); addLookupColumns(propExpr->prop(), propExpr->toString()); } } void LookupPlanner::addLookupColumns(const std::string& retCol, const std::string& outCol) { auto iter = std::find(returnCols_.begin(), returnCols_.end(), retCol); if (iter == returnCols_.end()) { returnCols_.emplace_back(retCol); } iter = std::find(colNames_.begin(), colNames_.end(), outCol); if (iter == colNames_.end()) { colNames_.emplace_back(outCol); } } } // namespace graph } // namespace nebula
34.328859
92
0.628543
[ "transform" ]
fd6bde192189d61617e2500b9a9caf4a097733fa
14,016
cpp
C++
BoundedTypes/GoogleTests/PositiveTests/PositiveTests.cpp
RomanoViolet/C-
95fdb40e57875d68ddb8ea69c2caf9c86df7ab48
[ "MIT" ]
null
null
null
BoundedTypes/GoogleTests/PositiveTests/PositiveTests.cpp
RomanoViolet/C-
95fdb40e57875d68ddb8ea69c2caf9c86df7ab48
[ "MIT" ]
null
null
null
BoundedTypes/GoogleTests/PositiveTests/PositiveTests.cpp
RomanoViolet/C-
95fdb40e57875d68ddb8ea69c2caf9c86df7ab48
[ "MIT" ]
null
null
null
#include "gmock/gmock.h" #include "gtest/gtest.h" #include <CustomTypes.hpp> #include <SafeTypes.hpp> #include <limits> #include <random> /** * @brief Units tests for each requirement associated to Component B. * */ /* TEST( InstantationTest, T1 ) { RomanoViolet::SafeType< 1, 4 > minWithIntegerBounds; EXPECT_TRUE( true ); } TEST( InstantationTest, T2 ) { RomanoViolet::SafeType< 1, 4, 2, 4 > minWithFloatBounds; EXPECT_FLOAT_EQ( minWithFloatBounds.getMinValue( ), 0.25F ); } TEST( InstantationTest, T3 ) { RomanoViolet::SafeType< Fraction( 1, 4 ), 2, 4 > minWithFloatBounds; EXPECT_TRUE( true ); } TEST( InstantationTest, T4 ) { VelocityType v; EXPECT_FLOAT_EQ( v.getMinValue( ), 0.5F ); } */ TEST( InstantationTest, OverflowCheck ) { // check whether min <= max assertion test will cause an overflow. // Tests: // 1 2 // ------------- <= ---------------- // MAX_INT_VALUE MAX_INT_VALUE // Or // (2 * MAX_INT_VALUE) <= MAX_INT_VALUE // | // |______(overflow may happen in this expression) // const int MaxValueOfInt = std::numeric_limits< int >::max( ); using customType = RomanoViolet::SafeType< Fraction( 1, MaxValueOfInt ), Fraction( 2, MaxValueOfInt ) >; customType c{ 1.0F / MaxValueOfInt }; EXPECT_FLOAT_EQ( c, 1.0F / MaxValueOfInt ); } TEST( InstantationTest, OverflowCheck_2 ) { // check whether min <= max assertion test will cause an overflow. // Tests: // (MAX_INT_VALUE-1) MAX_INT_VALUE // ------------------ <= ---------------- // MAX_INT_VALUE 1 // Or // (MAX_INT_VALUE - 1) <= (MAX_INT_VALUE * MAX_INT_VALUE) // | // | // (overflow may happen in this expression) // const int MaxValueOfInt = std::numeric_limits< int >::max( ); using customType = RomanoViolet::SafeType< Fraction( MaxValueOfInt - 1, MaxValueOfInt ), Fraction( MaxValueOfInt, 1 ) >; customType c{ ( float( MaxValueOfInt ) - 1.0F ) / MaxValueOfInt }; EXPECT_FLOAT_EQ( c, ( float( MaxValueOfInt ) - 1.0F ) / MaxValueOfInt ); } TEST( InstantationTest, CheckForSignRobustness ) { // A negative value for fraction by putting negative sign in the denominator must be evaluated as // having negative sign in the numerator. Tests: // (MAX_INT_VALUE-1) MAX_INT_VALUE // ------------------ <= ---------------- // -MAX_INT_VALUE 1 // Or // (MAX_INT_VALUE - 1) <= (-MAX_INT_VALUE * MAX_INT_VALUE) (INCORRECT. Equality has been // reversed.) // //********************************************************************* // EXPECTATION //********************************************************************* // (MAX_INT_VALUE-1) MAX_INT_VALUE // ------------------ <= ---------------- // -MAX_INT_VALUE 1 // // transformed to: // -(MAX_INT_VALUE-1) MAX_INT_VALUE // ------------------ <= ---------------- // MAX_INT_VALUE 1 // // Or // -(MAX_INT_VALUE - 1) <= (MAX_INT_VALUE * MAX_INT_VALUE) (INCORRECT.) // | // | // (overflow may happen in this expression) // const int MaxValueOfInt = std::numeric_limits< int >::max( ); using customType = RomanoViolet::SafeType< Fraction( MaxValueOfInt - 1, -MaxValueOfInt ), Fraction( MaxValueOfInt, 1 ) >; customType c{ ( MaxValueOfInt * 1.0F - MaxValueOfInt ) / MaxValueOfInt }; EXPECT_FLOAT_EQ( c, ( MaxValueOfInt * 1.0F - MaxValueOfInt ) / -MaxValueOfInt ); } TEST( InstantationTest, CheckForAllNegativeBounds_1 ) { // Test when bound lower and upper bounds are negative. // https://gcc.godbolt.org/z/NEm_DK const int MinValueOfInt = std::numeric_limits< int >::min( ) + 1; using customType = RomanoViolet::SafeType< Fraction( 2, MinValueOfInt ), Fraction( 1, MinValueOfInt ) >; customType c{ 1.5F / MinValueOfInt }; EXPECT_FLOAT_EQ( c, 1.5F / MinValueOfInt ); } TEST( InstantationTest, CheckForAllNegativeBounds_2 ) { // Test when lower and upper bounds are negative. // https://gcc.godbolt.org/z/NEm_DK const int MaxValueOfInt = std::numeric_limits< int >::max( ); using customType = RomanoViolet::SafeType< Fraction( -2, MaxValueOfInt ), Fraction( -1, MaxValueOfInt ) >; customType c{ -1.5F / MaxValueOfInt }; EXPECT_FLOAT_EQ( c, -1.5F / MaxValueOfInt ); } TEST( InstantationTest, CheckForNegativeAndPositiveBounds ) { // Test when bound lower and upper bounds are negative. // https://gcc.godbolt.org/z/NEm_DK const int MinValueOfInt = std::numeric_limits< int >::min( ) + 1; const int MaxValueOfInt = std::numeric_limits< int >::max( ); const int range_from = MinValueOfInt; const int range_to = MaxValueOfInt; std::random_device rand_dev; std::mt19937 generator( rand_dev( ) ); std::uniform_int_distribution< int > distr( range_from, range_to ); float value = float( distr( generator ) ) / distr( generator ); // note: A denominator of 1 will automatically match against integer specialization of safetype. // That is, a float value cannot be stored inside. // Setting the denominator to 1.0F will not work since all numerators and denominators are // exepected to be of type int using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; customType c{ value }; EXPECT_FLOAT_EQ( c, value ); } TEST( InstantationTest, CheckForResolution ) { // Test when lower and upper bounds are very close to each other const int MinValueOfInt = std::numeric_limits< int >::min( ) + 1; const int MaxValueOfInt = std::numeric_limits< int >::max( ); const int range_from = -100; const int range_to = 100; std::random_device rand_dev; std::mt19937 generator( rand_dev( ) ); std::uniform_int_distribution< int > distr( range_from, range_to ); float value = ( float( distr( generator ) ) / distr( generator ) ) * ( ( ( 1.0F / MaxValueOfInt ) - ( 1.0F / MinValueOfInt ) ) / ( range_from - range_to ) ); using customType = RomanoViolet::SafeType< Fraction( 1, MinValueOfInt ), Fraction( 1, MaxValueOfInt ) >; customType c{ value }; EXPECT_FLOAT_EQ( c, value ); } TEST( InstantationTest, CheckForFlooring ) { // Test when lower and upper bounds are very close to each other const int MinValueOfInt = -3; const int MaxValueOfInt = 5; float value = -3.1F; // note: A denominator of 1 will automatically match against integer // specialization of safetype. // That is, a float value cannot be stored inside. // Setting the denominator to 1.0F will not work since all numerators and // denominators are exepected to be of type int using customType = RomanoViolet::SafeType< Fraction( 1, MinValueOfInt ), Fraction( 1, MaxValueOfInt ) >; customType c{ value }; // Stored value will be floored to the lower bound. EXPECT_FLOAT_EQ( c, -1.0F / 3.F ); } TEST( InstantationTest, CheckForCeiling_FloatSpecialization ) { // Test when value to be assigned is higher than upper bound, and is therefore expected to be // ceiled to the upper bound. const int MinValueOfInt = 3; const int MaxValueOfInt = 5; float value = 10.F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 2 ), Fraction( MaxValueOfInt, 2 ) >; customType c{ value }; // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( c, 5.0 / 2.0F ); } TEST( InstantationTest, CheckForCeiling_IntegerSpecialization ) { // Test when value to be assigned is higher than upper bound, and is therefore expected to be // ceiled to the upper bound. const int MinValueOfInt = 3; const int MaxValueOfInt = 5; float value = 10.F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; customType c{ value }; // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( c, 5.0F ); } // The following test is disabled because operator float() is removed. // This operator allowed addition (and other operations) on unrelated types // since it will first extract the float value embedded in the object and pass it to the // operator such as +, which accepts a float. // // TEST( InstantationTest, AssignmentToFloat ) // { // // Tests whether the value stored in the class can be assigned to a float (the type value is // // stored in the class) // // // // customType c = <some value> // // float x = c; // // |_________ Test this. // // // const int MinValueOfInt = -2; // const int MaxValueOfInt = 1; // float value = -0.73F; // using customType // = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; // customType c = value; // float cNew = c; // this assignment is being tested. // // Stored value will be ceiled to the upper bound // EXPECT_FLOAT_EQ( c, cNew ); // } TEST( InstantationTest, CopyConstructor ) { // Test the copy constructor const int MinValueOfInt = -2; const int MaxValueOfInt = 1; float value = -0.73F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; customType c{ value }; customType newObject = c; // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( c, newObject ); } TEST( InstantationTest, AssignmentOperator ) { // Test the copy constructor const int MinValueOfInt = -2; const int MaxValueOfInt = 1; float value = -0.73F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; customType c{ value }; customType c_other{ 0.995 }; // as long as it is within the bounds of the customType c_other = c; // This is being tested. // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( c, c_other ); } TEST( InstantationTest, AdditionWithAnotherFloat ) { // Binary arithmetic with other floats should work out of the box due to operator float() being // implemented. const int MinValueOfInt = -2; const int MaxValueOfInt = 1; float value = -0.73F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 1 ), Fraction( MaxValueOfInt, 1 ) >; customType c{ value }; // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( c + 1.3F, value + 1.3F ); } TEST( InstantationTest, AdditionOperator ) { // Test addition. const int MinValueOfInt = 3; const int MaxValueOfInt = 8; float value = 1.5F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 2 ), Fraction( MaxValueOfInt, 2 ) >; customType c{ value }; customType d = c; customType e = d + c; EXPECT_FLOAT_EQ( e, 3.0 ); } TEST( InstantationTest, AdditionOperatorWithCeiling ) { // Test when value to be assigned after addition exceeds the upper bound. // Expect that the value is ceiled to the upper bound. const int MinValueOfInt = 3; const int MaxValueOfInt = 5; float value = 10.F; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 2 ), Fraction( MaxValueOfInt, 2 ) >; customType c{ value }; customType d = c; customType e = d + c; // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( e, 2.5 ); } TEST( InstantationTest, SubtractionOperator ) { const int MinValueOfInt = 1; const int MaxValueOfInt = 5; float value = 2.5; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 2 ), Fraction( MaxValueOfInt, 2 ) >; customType d{ value }; // 2.5 customType e{ 1.5F }; customType f = d - e; // 1.0 // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( f, 1.0F ); } TEST( InstantationTest, SubtractionOperatorWithFlooring ) { // the result of subtraction falls below the lower bound, and needs to be floored. const int MinValueOfInt = 1; const int MaxValueOfInt = 5; float value = 2.5; using customType = RomanoViolet::SafeType< Fraction( MinValueOfInt, 2 ), Fraction( MaxValueOfInt, 2 ) >; customType d{ value }; // 2.5 customType e{ 4.5F }; // e = 4.5F; customType f = d - e; // 1.0 // Stored value will be ceiled to the upper bound EXPECT_FLOAT_EQ( f, 0.5F ); } TEST( InstantationTest, Demo ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.5F }; VelocityType w{ v + 0.20F }; EXPECT_FLOAT_EQ( w, 0.70F ); } TEST( ErrorCodes, Underflow ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.4F }; EXPECT_FLOAT_EQ( v, 0.5F ); EXPECT_EQ( v.getErrorCode( ), RomanoViolet::SafeTypeErrorCode::UNDERFLOW ); } TEST( ErrorCodes, Overflow ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.8F }; EXPECT_FLOAT_EQ( v, 0.75F ); EXPECT_EQ( v.getErrorCode( ), RomanoViolet::SafeTypeErrorCode::OVERFLOW ); } TEST( InstantationTest, OverflowCausedByOperation ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.5F }; VelocityType w{ v + 0.30F }; EXPECT_FLOAT_EQ( w, 0.75F ); EXPECT_EQ( w.getErrorCode( ), RomanoViolet::SafeTypeErrorCode::OVERFLOW ); } TEST( InstantationTest, UnderflowCausedByOperation ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.5F }; VelocityType w{ v - 0.30F }; EXPECT_FLOAT_EQ( w, 0.50F ); EXPECT_EQ( w.getErrorCode( ), RomanoViolet::SafeTypeErrorCode::UNDERFLOW ); } TEST( InstantationTest, UnderflowCausedByOperationUsingFloatOperator ) { // Lower bound: 1/2 = 0.5F. Upper bound: 3/4 = 0.75F VelocityType v{ 0.5F }; VelocityType w{ v - 0.30F }; EXPECT_FLOAT_EQ( w, 0.50F ); float _v = w; EXPECT_FLOAT_EQ( _v, 0.50F ); EXPECT_EQ( w.getErrorCode( ), RomanoViolet::SafeTypeErrorCode::UNDERFLOW ); }
30.469565
99
0.643836
[ "object" ]
fd74052ddf72eef36c31ddb2f8920a7271e586ff
2,234
cc
C++
src/cores/scene.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
20
2020-06-28T03:55:40.000Z
2022-03-08T06:00:31.000Z
src/cores/scene.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
null
null
null
src/cores/scene.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
1
2020-06-29T08:47:21.000Z
2020-06-29T08:47:21.000Z
#include <cores/scene.h> #include <renderer/renderer.h> using namespace DR; observer_ptr<Transform> IMPL::TransTable::get_tf(const Matrix4 &mat) const { value_type trans = std::make_unique<const Transform>(mat); // cost a Matrix::Inverse if (tf_table_.find(*trans) != tf_table_.end()) { return tf_table_[*trans].get(); } else { value_type trans_inv = std::make_unique<const Transform>(Transform(*trans, true)); auto res_ptr = trans.get(); // get the value before the unique_ptr is moved tf_table_[*trans] = std::move(trans); tf_table_[*trans_inv] = std::move(trans_inv); return res_ptr; } } observer_ptr<Transform> IMPL::TransTable::get_tf(const Transform &trans) const { if (tf_table_.find(trans) != tf_table_.end()) { return tf_table_[trans].get(); } else { // if trans is a mat4(1.0), there will be only one entry in the table value_type trans_inv = std::make_unique<const Transform>(Transform(trans, true)); value_type trans_ptr = std::make_unique<const Transform>(trans); tf_table_[trans] = std::move(trans_ptr); tf_table_[*trans_inv] = std::move(trans_inv); return tf_table_[trans].get(); } } IMPL::TransTable::const_tf_pair IMPL::TransTable::get_tf_and_inv(const Matrix4 &mat) const { auto trans = Transform(mat); auto res = std::pair(get_tf(trans), get_tf(trans.inverse())); assert_msg((res.first->m_ * res.second->m_).is_identity(), "got" << (res.first->m_ * res.second->m_)); assert_msg((res.first->mInv_ * res.second->mInv_).is_identity(), "got" << res.first->mInv_ * res.second->mInv_); return res; } IMPL::TransTable::const_tf_pair IMPL::TransTable::get_tf_and_inv(const Transform &trans) const { auto res = std::pair{get_tf(trans), get_tf(trans.inverse())}; assert_msg((res.first->m_ * res.second->m_).is_identity(), "got" << (res.first->m_ * res.second->m_)); assert_msg((res.first->mInv_ * res.second->mInv_).is_identity(), "got" << res.first->mInv_ * res.second->mInv_); return res; } void Scene::render() const { if (!renderer_) { std::cerr << "renderer is not parsed correctly!" << std::endl; std::abort(); } this->renderer_->render(*this); }
39.192982
80
0.664279
[ "render", "transform" ]
fd8499e889755b90665bbac575e2724c5d41255c
17,496
cpp
C++
inference-engine/tests/functional/shared_test_classes/src/single_layer/non_max_suppression.cpp
hanchengyao/openvino
81c8cd711bb9f8dc48e5f288e77dc0d80cedebd8
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/functional/shared_test_classes/src/single_layer/non_max_suppression.cpp
hanchengyao/openvino
81c8cd711bb9f8dc48e5f288e77dc0d80cedebd8
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
inference-engine/tests/functional/shared_test_classes/src/single_layer/non_max_suppression.cpp
tsocha/openvino
3081fac7581933568b496a3c4e744d1cee481619
[ "Apache-2.0" ]
2
2020-09-08T17:12:23.000Z
2021-12-21T07:58:09.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <algorithm> #include "shared_test_classes/single_layer/non_max_suppression.hpp" namespace LayerTestsDefinitions { using namespace ngraph; using namespace InferenceEngine; using namespace FuncTestUtils::PrecisionUtils; std::string NmsLayerTest::getTestCaseName(testing::TestParamInfo<NmsParams> obj) { InputShapeParams inShapeParams; InputPrecisions inPrecisions; int32_t maxOutBoxesPerClass; float iouThr, scoreThr, softNmsSigma; op::v5::NonMaxSuppression::BoxEncodingType boxEncoding; bool sortResDescend; element::Type outType; std::string targetDevice; std::tie(inShapeParams, inPrecisions, maxOutBoxesPerClass, iouThr, scoreThr, softNmsSigma, boxEncoding, sortResDescend, outType, targetDevice) = obj.param; size_t numBatches, numBoxes, numClasses; std::tie(numBatches, numBoxes, numClasses) = inShapeParams; Precision paramsPrec, maxBoxPrec, thrPrec; std::tie(paramsPrec, maxBoxPrec, thrPrec) = inPrecisions; std::ostringstream result; result << "numBatches=" << numBatches << "_numBoxes=" << numBoxes << "_numClasses=" << numClasses << "_"; result << "paramsPrec=" << paramsPrec << "_maxBoxPrec=" << maxBoxPrec << "_thrPrec=" << thrPrec << "_"; result << "maxOutBoxesPerClass=" << maxOutBoxesPerClass << "_"; result << "iouThr=" << iouThr << "_scoreThr=" << scoreThr << "_softNmsSigma=" << softNmsSigma << "_"; result << "boxEncoding=" << boxEncoding << "_sortResDescend=" << sortResDescend << "_outType=" << outType << "_"; result << "TargetDevice=" << targetDevice; return result.str(); } void NmsLayerTest::GenerateInputs() { size_t it = 0; for (const auto &input : cnnNetwork.getInputsInfo()) { const auto &info = input.second; Blob::Ptr blob; if (it == 1) { blob = make_blob_with_precision(info->getTensorDesc()); blob->allocate(); CommonTestUtils::fill_data_random_float<Precision::FP32>(blob, 1, 0, 1000); } else { blob = GenerateInput(*info); } inputs.push_back(blob); it++; } } void NmsLayerTest::Compare(const std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> &expectedOutputs, const std::vector<InferenceEngine::Blob::Ptr> &actualOutputs) { CompareBBoxes(expectedOutputs, actualOutputs); } void NmsLayerTest::CompareBuffer(const std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> &expectedOutputs, const std::vector<InferenceEngine::Blob::Ptr> &actualOutputs) { for (int outputIndex = static_cast<int>(expectedOutputs.size()) - 1; outputIndex >= 0 ; outputIndex--) { const auto& expected = expectedOutputs[outputIndex]; const auto& actual = actualOutputs[outputIndex]; const auto &expectedBuffer = expected.second.data(); auto memory = InferenceEngine::as<InferenceEngine::MemoryBlob>(actual); IE_ASSERT(memory); const auto lockedMemory = memory->wmap(); const auto actualBuffer = lockedMemory.as<const uint8_t *>(); auto k = static_cast<float>(expected.first.size()) / actual->getTensorDesc().getPrecision().size(); // W/A for int4, uint4 if (expected.first == ngraph::element::Type_t::u4 || expected.first == ngraph::element::Type_t::i4) { k /= 2; } if (outputIndex == 2) { if (expected.second.size() != k * actual->byteSize()) throw std::runtime_error("Expected and actual size 3rd output have different size"); } const auto &precision = actual->getTensorDesc().getPrecision(); size_t size = expected.second.size() / (k * actual->getTensorDesc().getPrecision().size()); switch (precision) { case InferenceEngine::Precision::FP32: { switch (expected.first) { case ngraph::element::Type_t::f32: LayerTestsUtils::LayerTestsCommon::Compare( reinterpret_cast<const float *>(expectedBuffer), reinterpret_cast<const float *>(actualBuffer), size, 0); break; case ngraph::element::Type_t::f64: LayerTestsUtils::LayerTestsCommon::Compare( reinterpret_cast<const double *>(expectedBuffer), reinterpret_cast<const float *>(actualBuffer), size, 0); break; default: break; } const auto fBuffer = lockedMemory.as<const float *>(); for (int i = size; i < actual->size(); i++) { ASSERT_TRUE(fBuffer[i] == -1.f) << "Invalid default value: " << fBuffer[i] << " at index: " << i; } break; } case InferenceEngine::Precision::I32: { switch (expected.first) { case ngraph::element::Type_t::i32: LayerTestsUtils::LayerTestsCommon::Compare( reinterpret_cast<const int32_t *>(expectedBuffer), reinterpret_cast<const int32_t *>(actualBuffer), size, 0); break; case ngraph::element::Type_t::i64: LayerTestsUtils::LayerTestsCommon::Compare( reinterpret_cast<const int64_t *>(expectedBuffer), reinterpret_cast<const int32_t *>(actualBuffer), size, 0); break; default: break; } const auto iBuffer = lockedMemory.as<const int *>(); for (int i = size; i < actual->size(); i++) { ASSERT_TRUE(iBuffer[i] == -1) << "Invalid default value: " << iBuffer[i] << " at index: " << i; } break; } default: FAIL() << "Comparator for " << precision << " precision isn't supported"; } } } typedef struct Rect { int32_t x1; int32_t y1; int32_t x2; int32_t y2; } Rect; class Box { public: Box() = default; Box(int32_t batchId, int32_t classId, int32_t boxId, Rect rect, float score) { this->batchId = batchId; this->classId = classId; this->boxId = boxId; this->rect = rect; this->score = score; } int32_t batchId; int32_t classId; int32_t boxId; Rect rect; float score; }; /* * 1: selected_indices - tensor of type T_IND and shape [number of selected boxes, 3] containing information about selected boxes as triplets * [batch_index, class_index, box_index]. * 2: selected_scores - tensor of type T_THRESHOLDS and shape [number of selected boxes, 3] containing information about scores for each selected box as triplets * [batch_index, class_index, box_score]. * 3: valid_outputs - 1D tensor with 1 element of type T_IND representing the total number of selected boxes. */ void NmsLayerTest::CompareBBoxes(const std::vector<std::pair<ngraph::element::Type, std::vector<std::uint8_t>>> &expectedOutputs, const std::vector<InferenceEngine::Blob::Ptr> &actualOutputs) { size_t numBatches, numBoxes, numClasses; std::tie(numBatches, numBoxes, numClasses) = inShapeParams; auto iouFunc = [](const Box& boxI, const Box& boxJ) { const Rect& rectI = boxI.rect; const Rect& rectJ = boxJ.rect; float areaI = (rectI.y2 - rectI.y1) * (rectI.x2 - rectI.x1); float areaJ = (rectJ.y2 - rectJ.y1) * (rectJ.x2 - rectJ.x1); if (areaI <= 0.0f || areaJ <= 0.0f) { return 0.0f; } float intersection_ymin = std::max(rectI.y1, rectJ.y1); float intersection_xmin = std::max(rectI.x1, rectJ.x1); float intersection_ymax = std::min(rectI.y2, rectJ.y2); float intersection_xmax = std::min(rectI.x2, rectJ.x2); float intersection_area = std::max(intersection_ymax - intersection_ymin, 0.0f) * std::max(intersection_xmax - intersection_xmin, 0.0f); return intersection_area / (areaI + areaJ - intersection_area); }; // Get input bboxes' coords std::vector<std::vector<Rect>> coordList(numBatches, std::vector<Rect>(numBoxes)); { const auto &input = inputs[0]; auto memory = InferenceEngine::as<InferenceEngine::MemoryBlob>(input); IE_ASSERT(memory); const auto lockedMemory = memory->rmap(); const auto buffer = lockedMemory.as<const float *>(); for (size_t i = 0; i < numBatches; ++i) { for (size_t j = 0; j < numBoxes; ++j) { const int32_t y1 = static_cast<int32_t>(buffer[(i*numBoxes+j)*4+0]); const int32_t x1 = static_cast<int32_t>(buffer[(i*numBoxes+j)*4+1]); const int32_t y2 = static_cast<int32_t>(buffer[(i*numBoxes+j)*4+2]); const int32_t x2 = static_cast<int32_t>(buffer[(i*numBoxes+j)*4+3]); coordList[i][j] = { std::min(y1, y2), std::min(x1, x2), std::max(y1, y2), std::max(x1, x2) }; } } } auto compareBox = [](const Box& boxA, const Box& boxB) { return (boxA.batchId < boxB.batchId) || (boxA.batchId == boxB.batchId && boxA.classId < boxB.classId) || (boxA.batchId == boxB.batchId && boxA.classId == boxB.classId && boxA.boxId < boxB.boxId); }; // Get expected bboxes' index/score std::vector<Box> expectedList; { size_t selected_indices_size = expectedOutputs[0].second.size() / expectedOutputs[0].first.size(); size_t selected_scores_size = expectedOutputs[1].second.size() / expectedOutputs[1].first.size(); ASSERT_TRUE(selected_indices_size == selected_scores_size); expectedList.resize(selected_indices_size); if (expectedOutputs[0].first.size() == 4) { auto selected_indices_data = reinterpret_cast<const int32_t *>(expectedOutputs[0].second.data()); for (size_t i = 0; i < selected_indices_size; i += 3) { expectedList[i/3].batchId = selected_indices_data[i+0]; expectedList[i/3].classId = selected_indices_data[i+1]; expectedList[i/3].boxId = selected_indices_data[i+2]; expectedList[i/3].rect = coordList[expectedList[i/3].batchId][expectedList[i/3].boxId]; } } else { auto selected_indices_data = reinterpret_cast<const int64_t *>(expectedOutputs[0].second.data()); for (size_t i = 0; i < selected_indices_size; i += 3) { expectedList[i/3].batchId = static_cast<int32_t>(selected_indices_data[i+0]); expectedList[i/3].classId = static_cast<int32_t>(selected_indices_data[i+1]); expectedList[i/3].boxId = static_cast<int32_t>(selected_indices_data[i+2]); expectedList[i/3].rect = coordList[expectedList[i/3].batchId][expectedList[i/3].boxId]; } } if (expectedOutputs[1].first.size() == 4) { auto selected_scores_data = reinterpret_cast<const float *>(expectedOutputs[0].second.data()); for (size_t i = 0; i < selected_scores_size; i += 3) { expectedList[i/3].score = selected_scores_data[i+2]; } } else { auto selected_scores_data = reinterpret_cast<const double *>(expectedOutputs[0].second.data()); for (size_t i = 0; i < selected_scores_size; i += 3) { expectedList[i/3].score = static_cast<float>(selected_scores_data[i+2]); } } std::sort(expectedList.begin(), expectedList.end(), compareBox); } // Get actual bboxes' index/score std::vector<Box> actualList; { size_t selected_indices_size = actualOutputs[0]->byteSize() / sizeof(float); auto selected_indices_memory = as<MemoryBlob>(actualOutputs[0]); IE_ASSERT(selected_indices_memory); const auto selected_indices_lockedMemory = selected_indices_memory->rmap(); const auto selected_indices_data = selected_indices_lockedMemory.as<const int32_t *>(); auto selected_scores_memory = as<MemoryBlob>(actualOutputs[1]); IE_ASSERT(selected_scores_memory); const auto selected_scores_lockedMemory = selected_scores_memory->rmap(); const auto selected_scores_data = selected_scores_lockedMemory.as<const float *>(); for (size_t i = 0; i < selected_indices_size; i += 3) { const int32_t batchId = selected_indices_data[i+0]; const int32_t classId = selected_indices_data[i+1]; const int32_t boxId = selected_indices_data[i+2]; const float score = selected_scores_data[i+2]; if (batchId == -1 || classId == -1 || boxId == -1) break; actualList.emplace_back(batchId, classId, boxId, coordList[batchId][boxId], score); } std::sort(actualList.begin(), actualList.end(), compareBox); } std::vector<Box> intersectionList; std::vector<Box> differenceList; { std::list<Box> tempExpectedList(expectedList.size()), tempActualList(actualList.size()); std::copy(expectedList.begin(), expectedList.end(), tempExpectedList.begin()); std::copy(actualList.begin(), actualList.end(), tempActualList.begin()); auto sameBox = [](const Box& boxA, const Box& boxB) { return (boxA.batchId == boxB.batchId) && (boxA.classId == boxB.classId) && (boxA.boxId == boxB.boxId); }; for (auto itA = tempActualList.begin(); itA != tempActualList.end(); ++itA) { bool found = false; for (auto itB = tempExpectedList.begin(); itB != tempExpectedList.end(); ++itB) { if (sameBox(*itA, *itB)) { intersectionList.emplace_back(*itB); tempExpectedList.erase(itB); found = true; break; } } if (!found) { differenceList.emplace_back(*itA); } } differenceList.insert(differenceList.end(), tempExpectedList.begin(), tempExpectedList.end()); for (auto& item : differenceList) { if ((item.rect.x1 == item.rect.x2) || (item.rect.y1 == item.rect.y2)) continue; float maxIou = 0.f; for (auto& refItem : intersectionList) { maxIou = std::max(maxIou, iouFunc(item, refItem)); if (maxIou > 0.3f) break; } ASSERT_TRUE(maxIou > 0.3f) << "MaxIOU: " << maxIou << ", expectedList.size(): " << expectedList.size() << ", actualList.size(): " << actualList.size() << ", intersectionList.size(): " << intersectionList.size() << ", diffList.size(): " << differenceList.size() << ", batchId: " << item.batchId << ", classId: " << item.classId << ", boxId: " << item.boxId << ", score: " << item.score << ", coord: " << item.rect.x1 << ", " << item.rect.y1 << ", " << item.rect.x2 << ", " << item.rect.y2; } } } void NmsLayerTest::SetUp() { InputPrecisions inPrecisions; size_t maxOutBoxesPerClass; float iouThr, scoreThr, softNmsSigma; op::v5::NonMaxSuppression::BoxEncodingType boxEncoding; bool sortResDescend; element::Type outType; std::tie(inShapeParams, inPrecisions, maxOutBoxesPerClass, iouThr, scoreThr, softNmsSigma, boxEncoding, sortResDescend, outType, targetDevice) = this->GetParam(); size_t numBatches, numBoxes, numClasses; std::tie(numBatches, numBoxes, numClasses) = inShapeParams; Precision paramsPrec, maxBoxPrec, thrPrec; std::tie(paramsPrec, maxBoxPrec, thrPrec) = inPrecisions; numOfSelectedBoxes = std::min(numBoxes, maxOutBoxesPerClass) * numBatches * numClasses; const std::vector<size_t> boxesShape{numBatches, numBoxes, 4}, scoresShape{numBatches, numClasses, numBoxes}; auto ngPrc = convertIE2nGraphPrc(paramsPrec); auto params = builder::makeParams(ngPrc, {boxesShape, scoresShape}); auto paramOuts = helpers::convert2OutputVector(helpers::castOps2Nodes<op::Parameter>(params)); auto nms = builder::makeNms(paramOuts[0], paramOuts[1], convertIE2nGraphPrc(maxBoxPrec), convertIE2nGraphPrc(thrPrec), maxOutBoxesPerClass, iouThr, scoreThr, softNmsSigma, boxEncoding, sortResDescend, outType); auto nms_0_identity = std::make_shared<opset5::Multiply>(nms->output(0), opset5::Constant::create(outType, Shape{1}, {1})); auto nms_1_identity = std::make_shared<opset5::Multiply>(nms->output(1), opset5::Constant::create(ngPrc, Shape{1}, {1})); auto nms_2_identity = std::make_shared<opset5::Multiply>(nms->output(2), opset5::Constant::create(outType, Shape{1}, {1})); function = std::make_shared<Function>(OutputVector{nms_0_identity, nms_1_identity, nms_2_identity}, params, "NMS"); } } // namespace LayerTestsDefinitions
46.285714
161
0.599966
[ "shape", "vector" ]
fd855d841df38db33ff95dc52279e03b2cc338ca
4,163
inl
C++
src/common/q3Geometry.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
791
2015-01-04T02:26:39.000Z
2022-03-30T12:31:36.000Z
src/common/q3Geometry.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
48
2015-02-17T19:29:51.000Z
2021-12-21T01:08:28.000Z
src/common/q3Geometry.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
108
2015-02-16T08:20:04.000Z
2022-03-01T09:39:47.000Z
//-------------------------------------------------------------------------------------------------- // q3Geometry.inl // // Copyright (c) 2014 Randy Gaul http://www.randygaul.net // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // Common //-------------------------------------------------------------------------------------------------- // http://box2d.org/2014/02/computing-a-basis/ inline void q3ComputeBasis( const q3Vec3& a, q3Vec3* __restrict b, q3Vec3* __restrict c ) { // Suppose vector a has all equal components and is a unit vector: a = (s, s, s) // Then 3*s*s = 1, s = sqrt(1/3) = 0.57735027. This means that at least one component of a // unit vector must be greater or equal to 0.57735027. Can use SIMD select operation. if ( q3Abs( a.x ) >= r32( 0.57735027 ) ) b->Set( a.y, -a.x, r32( 0.0 ) ); else b->Set( r32( 0.0 ), a.z, -a.y ); *b = q3Normalize( *b ); *c = q3Cross( a, *b ); } //-------------------------------------------------------------------------------------------------- // q3AABB //-------------------------------------------------------------------------------------------------- inline bool q3AABBtoAABB( const q3AABB& a, const q3AABB& b ) { if ( a.max.x < b.min.x || a.min.x > b.max.x ) return false; if ( a.max.y < b.min.y || a.min.y > b.max.y ) return false; if ( a.max.z < b.min.z || a.min.z > b.max.z ) return false; return true; } //-------------------------------------------------------------------------------------------------- inline bool q3AABB::Contains( const q3AABB& other ) const { return min.x <= other.min.x && min.y <= other.min.y && min.z <= other.min.z && max.x >= other.max.x && max.y >= other.max.y && max.z >= other.max.z; } //-------------------------------------------------------------------------------------------------- inline bool q3AABB::Contains( const q3Vec3& point ) const { return min.x <= point.x && min.y <= point.y && min.z <= point.z && max.x >= point.x && max.y >= point.y && max.z >= point.z; } //-------------------------------------------------------------------------------------------------- inline r32 q3AABB::SurfaceArea( ) const { r32 x = max.x - min.x; r32 y = max.y - min.y; r32 z = max.z - min.z; return r32( 2.0 ) * (x * y + x * z + y * z); } //-------------------------------------------------------------------------------------------------- inline const q3AABB q3Combine( const q3AABB& a, const q3AABB& b ) { q3AABB c; c.min = q3Min( a.min, b.min ); c.max = q3Max( a.max, b.max ); return c; } //-------------------------------------------------------------------------------------------------- // q3RaycastData //-------------------------------------------------------------------------------------------------- inline void q3RaycastData::Set( const q3Vec3& startPoint, const q3Vec3& direction, r32 endPointTime ) { start = startPoint; dir = direction; t = endPointTime; } //-------------------------------------------------------------------------------------------------- inline const q3Vec3 q3RaycastData::GetImpactPoint( ) const { return q3Vec3( start + dir * toi ); }
35.279661
101
0.446793
[ "vector" ]
fd88353127a31d8f8e8d8cde27c2a5e72f98bc8d
13,950
cpp
C++
src/linear/gabor.cpp
DIPlib/diplib
eaf03372264f050bcda2d49bdf443702308ba303
[ "Apache-2.0" ]
140
2017-04-04T23:10:16.000Z
2022-03-24T18:21:34.000Z
src/linear/gabor.cpp
DIPlib/diplib
eaf03372264f050bcda2d49bdf443702308ba303
[ "Apache-2.0" ]
98
2018-01-13T23:16:00.000Z
2022-03-14T14:45:37.000Z
src/linear/gabor.cpp
DIPlib/diplib
eaf03372264f050bcda2d49bdf443702308ba303
[ "Apache-2.0" ]
40
2017-04-11T20:41:58.000Z
2022-03-24T18:21:36.000Z
/* * DIPlib 3.0 * This file contains definitions of functions that implement the FIR Gabor filter. * * (c)2018-2021, Cris Luengo. * * 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 "diplib.h" #include "diplib/linear.h" #include "diplib/math.h" #include "diplib/generation.h" #include "diplib/transform.h" #include "diplib/framework.h" #include "diplib/overload.h" #include "diplib/iterators.h" namespace dip { namespace { inline dip::uint HalfGaborSize( dfloat sigma, dfloat truncation, DataType dt // either DT_SFLOAT or DT_DFLOAT, not tested for ) { if( truncation <= 0 ) { truncation = 3; // The default value } double max_trunc = dt == DT_DFLOAT ? maximum_gauss_truncation< dfloat >() : maximum_gauss_truncation< sfloat >(); truncation = std::min( truncation, max_trunc ); return clamp_cast< dip::uint >( std::ceil( truncation * sigma )); } // Creates half of a complex-valued Gabor kernel, with the x=0 at the right end (last element) of the output array. // `out[0] + i*out[1]` is the first element, etc. As expected by `OneDimensionalFilter`. std::vector< dfloat > MakeHalfGabor( dfloat sigma, dfloat frequency, dfloat truncation, DataType dt // either DT_SFLOAT or DT_DFLOAT, not tested for ) { dip::uint halfFilterSize = 1 + HalfGaborSize( sigma, truncation, dt ); std::vector< dfloat > filter( 2 * halfFilterSize ); auto ptr = reinterpret_cast< dcomplex* >( filter.data() ); dip::uint r0 = halfFilterSize - 1; dfloat factor = -1.0 / ( 2.0 * sigma * sigma ); dfloat norm = 1.0 / ( std::sqrt( 2.0 * pi ) * sigma ); frequency *= 2 * pi; ptr[ r0 ] = norm; for( dip::uint rr = 1; rr < halfFilterSize; rr++ ) { dfloat rad = static_cast< dfloat >( rr ); dfloat g = std::exp( factor * ( rad * rad )) * norm; dfloat phi = rad * frequency; ptr[ r0 - rr ] = g * dcomplex{ std::cos( phi ), -std::sin( phi ) }; } return filter; } // Create 1D full Gabor filter std::vector< dfloat > MakeGabor( dfloat sigma, dfloat frequency, dfloat truncation, DataType dt ) { // Handle sigma == 0.0 if( sigma == 0.0 ) { return { 1.0 }; } // Create half Gabor std::vector< dfloat > gabor; DIP_STACK_TRACE_THIS( gabor = MakeHalfGabor( sigma, frequency, truncation, dt )); dip::uint halfFilterSize = gabor.size() / 2 - 1; // Complete the Gabor gabor.resize( 2 * ( halfFilterSize * 2 + 1 )); auto ptr = reinterpret_cast< dcomplex* >( gabor.data() ); for( dip::uint ii = 1; ii <= halfFilterSize; ++ii ) { ptr[ halfFilterSize + ii ] = std::conj( ptr[ halfFilterSize - ii ] ); } return gabor; } } // namespace void CreateGabor( Image& out, FloatArray const& sigmas, FloatArray const& frequencies, dfloat truncation ) { // Verify dimensionality dip::uint nDims = sigmas.size(); DIP_THROW_IF( frequencies.size() != nDims, E::ARRAY_PARAMETER_WRONG_LENGTH ); // Adjust truncation to default if needed if( truncation <= 0.0 ) { truncation = 3.0; } truncation = std::min( truncation, maximum_gauss_truncation< sfloat >() ); // Create 1D gaussian for each dimension std::vector< std::vector< dfloat >> gabors( nDims ); std::vector< dcomplex const* > ptrs( nDims ); UnsignedArray outSizes( nDims ); for( dip::uint ii = 0; ii < nDims; ++ii ) { DIP_STACK_TRACE_THIS( gabors[ ii ] = MakeGabor( sigmas[ ii ], frequencies[ ii ], truncation, DT_DFLOAT )); outSizes[ ii ] = gabors[ ii ].size() / 2; ptrs[ ii ] = reinterpret_cast< dcomplex* >( gabors[ ii ].data() ); } // Create output image std::cout << "[CreateGabor] sigmas = " << sigmas << '\n'; std::cout << "[CreateGabor] outSizes = " << outSizes << '\n'; out.ReForge( outSizes, 1, DT_DCOMPLEX ); std::cout << "[CreateGabor] out = " << out << '\n'; ImageIterator< dcomplex > itOut( out ); do { UnsignedArray const& coords = itOut.Coordinates(); // Multiply 1D Kernels dcomplex value = 1.0; for( dip::uint ii = 0; ii < nDims; ++ii ) { value *= ptrs[ ii ][ coords[ ii ]]; } *itOut = value; } while( ++itOut ); } void GaborFIR( Image const& in, Image& out, FloatArray sigmas, FloatArray const& frequencies, StringArray const& boundaryCondition, BooleanArray process, dfloat truncation ) { DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); dip::uint nDims = in.Dimensionality(); DIP_START_STACK_TRACE ArrayUseParameter( sigmas, nDims, 1.0 ); ArrayUseParameter( process, nDims, true ); DIP_END_STACK_TRACE OneDimensionalFilterArray filter( nDims ); DataType computeType = in.DataType().IsA( DataType::Class_DFloat + DataType::Class_DComplex ) ? DT_DFLOAT : DT_SFLOAT; for( dip::uint ii = 0; ii < nDims; ++ii ) { if(( sigmas[ ii ] > 0.0 ) && ( in.Size( ii ) > 1 )) { bool found = false; for( dip::uint jj = 0; jj < ii; ++jj ) { if( process[ jj ] && ( sigmas[ jj ] == sigmas[ ii ] ) && ( frequencies[ jj ] == frequencies[ ii ] )) { filter[ ii ] = filter[ jj ]; found = true; break; } } if( !found ) { filter[ ii ].symmetry = S::CONJ; filter[ ii ].isComplex = true; filter[ ii ].filter = MakeHalfGabor( sigmas[ ii ], frequencies[ ii ], truncation, computeType ); // NOTE: origin defaults to the middle of the filter, so we don't need to set it explicitly here. } } else { process[ ii ] = false; } } SeparableConvolution( in, out, filter, boundaryCondition, process ); } namespace { void ApplyScaleFilters( Image const& ftIn, Image& radius, ImageArray& outar, FloatArray const& wavelengths, dfloat bandwidth ) { dfloat expScaling = std::log( bandwidth ); expScaling = 1.0 / ( 2.0 * expScaling * expScaling ); UnsignedArray center = radius.Sizes(); center /= 2; radius.At( center ) = 1; // TODO: Kovesi also makes a low-pass filter to remove the frequency components "in the corners". Is this important? dip::uint nFrequencyScales = wavelengths.size(); outar.resize( nFrequencyScales ); for( dip::uint scale = 0; scale < nFrequencyScales; ++scale ) { Image tmp; if( !ftIn.IsForged() ) { outar[ scale ].ReForge( radius.Sizes(), 1, DT_SFLOAT ); tmp = outar[ scale ]; tmp.Protect(); } dfloat wavelength = wavelengths[ scale ]; auto lineFilter = Framework::NewMonadicScanLineFilter< sfloat >( [ wavelength, expScaling ]( auto its ){ return static_cast< sfloat >( std::exp( -std::pow( std::log( *its[ 0 ] * wavelength ), 2 ) * expScaling )); }, 50 ); Framework::ScanMonadic( radius, tmp, DT_SFLOAT, DT_SFLOAT, 1, *lineFilter ); if( ftIn.IsForged() ) { Multiply( tmp, ftIn, outar[ scale ] ); // output is complex-valued } outar[ scale ].At( center ) = 0; } } } // namespace void LogGaborFilterBank( Image const& in, Image& out, FloatArray const& wavelengths, dfloat bandwidth, dip::uint nOrientations, String const& inRepresentation, String const& outRepresentation ) { DIP_THROW_IF( !in.IsScalar(), E::IMAGE_NOT_SCALAR ); DIP_THROW_IF( !in.Sizes().all(), "Raw image sizes not valid" ); // must test valid sizes in case it's not forged dip::uint nFrequencyScales = wavelengths.size(); DIP_THROW_IF( nFrequencyScales < 1, E::ARRAY_PARAMETER_EMPTY ); DIP_THROW_IF( nOrientations < 1, E::INVALID_PARAMETER ); DIP_THROW_IF( bandwidth <= 0, E::INVALID_PARAMETER ); bool onlyScale = nOrientations == 1; dip::uint nDims = in.Dimensionality(); DIP_THROW_IF( !onlyScale && ( nDims != 2 ), E::DIMENSIONALITY_NOT_SUPPORTED ); bool spatialDomainOutput; DIP_STACK_TRACE_THIS( spatialDomainOutput = BooleanFromString( outRepresentation, S::SPATIAL, S::FREQUENCY )); bool inputIsReal = true; // if no input image is given, it's like we're given a delta pulse image -- it's real. Image ftIn; if( in.IsForged() ) { // Get Fourier-domain representation of input image bool spatialDomainInput; DIP_STACK_TRACE_THIS( spatialDomainInput = BooleanFromString( inRepresentation, S::SPATIAL, S::FREQUENCY )); if( spatialDomainInput ) { inputIsReal = !in.DataType().IsComplex(); ftIn = FourierTransform( in ); } else { inputIsReal = false; ftIn = in; if( ftIn.Aliases( out )) { out.Strip(); // cannot work in-place } } } else { ftIn.SetSizes( in.Sizes() ); // Copy over the sizes array. } // Options: // - !in.IsForged() // - inputIsReal // - onlyScale // - FD output => real // - SD output => real // - !onlyScale // - FD output => real // - SD output => complex // - !inputIsReal // - does not happen! // - in.IsForged() // - inputIsReal // - onlyScale // - FD output => complex // - SD output => real // - !onlyScale // - FD output => complex // - SD output => complex // - !inputIsReal // - onlyScale // - FD output => complex // - SD output => complex // - !onlyScale // - FD output => complex // - SD output => complex bool ouputIsReal = ( !in.IsForged() && ( onlyScale || !spatialDomainOutput )) || ( in.IsForged() && inputIsReal && onlyScale && spatialDomainOutput ); // Options for inverse transform StringSet options = { S::INVERSE }; if( spatialDomainOutput && ouputIsReal ) { options.insert( S::REAL ); } // Forge output tensor image DataType outDataType = ouputIsReal ? DT_SFLOAT : DT_SCOMPLEX; out.ReForge( ftIn.Sizes(), nOrientations * nFrequencyScales, outDataType, Option::AcceptDataTypeChange::DONT_ALLOW ); out.ReshapeTensor( nOrientations, nFrequencyScales ); // Create coordinates image Image coord = CreateCoordinates( ftIn.Sizes(), { "frequency" } ); Image radius = Norm( coord ); UnsignedArray center = ftIn.Sizes(); center /= 2; radius.At( center ) = 1; // Value at origin should not be 0, so we can take the log later on DIP_ASSERT( radius.DataType() == DT_SFLOAT ); if( onlyScale ) { // Create scale filtered images // ApplyScaleFilters produces a SCOMPLEX output if ftIn.IsForged(), otherwise it is SFLOAT // If the type matches the output type's, write directly to output ImageArray outar( nFrequencyScales ); if( ftIn.IsForged() ^ ouputIsReal ) { for( dip::uint scale = 0; scale < nFrequencyScales; ++scale ) { outar[ scale ] = out[ scale ]; outar[ scale ].Protect(); } } ApplyScaleFilters( ftIn, radius, outar, wavelengths, bandwidth ); if( spatialDomainOutput ) { // Apply inverse Fourier transform for( dip::uint scale = 0; scale < nFrequencyScales; ++scale ) { Image tmp = out[ scale ]; tmp.Protect(); FourierTransform( outar[ scale ], tmp, options ); } } return; // We're done! } // If we're here, we're dealing with a 2D image, and want 2 or more orientations. // Apply scale filters to the input ImageArray scaleFilter; ApplyScaleFilters( ftIn, radius, scaleFilter, wavelengths, bandwidth ); coord /= radius; DIP_ASSERT( coord.DataType() == DT_SFLOAT ); // Construct and apply angle filters to the previous result dfloat sigmaTheta = pi / static_cast< dfloat >( nOrientations ) / 1.3; // magic constant, see Kovesi. dfloat expScaling = 1.0 / ( 2.0 * sigmaTheta * sigmaTheta ); for( dip::uint orientation = 0; orientation < nOrientations; ++orientation ) { // Construct angle selection filter dfloat angle = static_cast< dfloat >( orientation ) * pi / static_cast< dfloat >( nOrientations ); Image::Pixel rotMatrix{ sfloat( std::cos( angle )), sfloat( std::sin( angle )), -sfloat( std::sin( angle )), sfloat( std::cos( angle )) }; rotMatrix.ReshapeTensor( 2, 2 ); Image radialFilter = rotMatrix * coord; Angle( radialFilter, radialFilter ); auto lineFilter = Framework::NewMonadicScanLineFilter< sfloat >( [ expScaling ]( auto its ){ return static_cast< sfloat >( std::exp( static_cast< dfloat >( *its[ 0 ] ) * static_cast< dfloat >( *its[ 0 ] ) * -expScaling )); }, 30 ); Framework::ScanMonadic( radialFilter, radialFilter, DT_SFLOAT, DT_SFLOAT, 1, *lineFilter ); // Filter each scale with this angle selection filter for( dip::uint scale = 0; scale < nFrequencyScales; ++scale ) { Image destination = out[ UnsignedArray{ orientation, scale } ]; destination.Protect(); // ensure it will not be reforged Image tempStorage; Image& ftDestination = ( spatialDomainOutput && ouputIsReal ) ? tempStorage : destination; Multiply( radialFilter, scaleFilter[ scale ], ftDestination ); if( spatialDomainOutput ) { FourierTransform( ftDestination, destination, options ); } } } } } // namespace dip
37.5
144
0.613548
[ "vector", "transform" ]
fd8b0edf9f8df07e063a8f12de4999bc153f46eb
20,768
hpp
C++
src/frovedis/ml/glm/sgd_parallelizer.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
src/frovedis/ml/glm/sgd_parallelizer.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
src/frovedis/ml/glm/sgd_parallelizer.hpp
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#ifndef _SGD_PARALLELIZER_HPP_ #define _SGD_PARALLELIZER_HPP_ #include "common.hpp" namespace frovedis { template <class T> struct sgd_dtrain { sgd_dtrain(): iterCount(1), alpha(0.01), isIntercept(false) {} sgd_dtrain(size_t i, double al, bool intercept): iterCount(i), alpha(al), isIntercept(intercept) {} template <class DATA_MATRIX, class MODEL, class GRADIENT> MODEL operator()(std::vector<DATA_MATRIX>& data, std::vector<std::vector<T>>& label, std::vector<std::vector<T>>& sample_weight, MODEL& gModel, GRADIENT& grad, double& loss) { // --- One time check --- if(iterCount == 1 && data.size() != label.size()) REPORT_FATAL(INTERNAL_ERROR, "Report bug: Problem in internal minibatch creation.\n"); MODEL lModel = gModel; gradient_descent gd(alpha, isIntercept); gd.optimize<T>(data,label,sample_weight,lModel,grad,iterCount,loss); return lModel; } size_t iterCount; double alpha; bool isIntercept; SERIALIZE(iterCount, alpha, isIntercept) }; template <class T> struct sgd_dtrain_with_trans { sgd_dtrain_with_trans(): iterCount(1), alpha(0.01), isIntercept(false) {} sgd_dtrain_with_trans(size_t i, double al, bool intercept): iterCount(i), alpha(al), isIntercept(intercept) {} template <class DATA_MATRIX, class TRANS_MATRIX, class MODEL, class GRADIENT> MODEL operator()(std::vector<DATA_MATRIX>& data, std::vector<TRANS_MATRIX>& trans, std::vector<std::vector<T>>& label, std::vector<std::vector<T>>& sample_weight, MODEL& gModel, GRADIENT& grad, double& loss) { // --- One time check --- if(iterCount == 1 && data.size() != label.size()) REPORT_FATAL(INTERNAL_ERROR, "Report bug: Problem in internal minibatch creation.\n"); MODEL lModel = gModel; gradient_descent gd(alpha, isIntercept); gd.optimize<T>(data,trans,label,sample_weight,lModel,grad,iterCount,loss); return lModel; } size_t iterCount; double alpha; bool isIntercept; SERIALIZE(iterCount, alpha, isIntercept) }; struct sgd_parallelizer { sgd_parallelizer(): miniBatchFraction(1.0) {} sgd_parallelizer(double frac): miniBatchFraction(frac) { checkAssumption(miniBatchFraction > 0.0 && miniBatchFraction <= 1.0); } template <class T, class I, class O, class MODEL, class GRADIENT, class REGULARIZER> MODEL parallelize(crs_matrix<T,I,O>& data, dvector<T>& label, MODEL& initModel, GRADIENT& grad, REGULARIZER& rType, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, bool isIntercept, double convergenceTol, MatType mType, bool inputMovable); template <class T, class MODEL, class GRADIENT, class REGULARIZER> MODEL parallelize(colmajor_matrix<T>& data, dvector<T>& label, MODEL& initModel, GRADIENT& grad, REGULARIZER& rType, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, bool isIntercept, double convergenceTol); double miniBatchFraction; SERIALIZE(miniBatchFraction) }; // -- to improve vectorization... template <class T> void copy_weight(T* dst, T* src, size_t size) { for(size_t i = 0; i < size; i++) dst[i] = src[i]; } template <class T> void add_weight(T* dst, T* src, size_t size) { for(size_t i = 0; i < size; i++) dst[i] += src[i]; } template <class T> T local_diff_square_sum(T* prev_model_weightp, T* model_weightp, size_t weight_size) { T sum = 0; auto self = get_selfid(); auto each = ceil_div(weight_size, size_t(get_nodesize())); auto start = each * self; auto end = std::min(each * (self + 1), weight_size); for(size_t i = start; i < end; i++) { auto diff = prev_model_weightp[i] - model_weightp[i]; sum += diff * diff; } return sum; } // ---- template <class T, class DATA_MATRIX, class TRANS_MATRIX, class MODEL, class GRADIENT, class REGULARIZER> void do_train_with_trans(std::vector<DATA_MATRIX>& data, std::vector<TRANS_MATRIX>& transData, std::vector<std::vector<T>>& label, MODEL& model, std::vector<std::vector<T>>& sample_weight, size_t& n_iter, sgd_config<GRADIENT, REGULARIZER>& config) { frovedis::time_spent trace(TRACE), trace_iter(DEBUG), reduce_lap(DEBUG), dtrain_lap(DEBUG), update_lap(DEBUG), conv_lap(DEBUG); // --- extract hyper-parameters --- auto numIteration = config.numIteration; auto alpha = config.alpha; auto convergenceTol = config.convergenceTol; auto isIntercept = config.isIntercept; auto nsamples = config.numSamples; auto grad = config.grad; auto rType = config.rType; auto self = get_selfid(); size_t weight_size = model.weight.size(); std::vector<T> weight_intercept(weight_size + 1); auto weight_interceptp = weight_intercept.data(); std::vector<T> totaldiffvec(weight_size + 1); auto totaldiffvecp = totaldiffvec.data(); double l_loss = 0.0, sumloss = 0.0; #ifdef _LOSS_CHECK_ double best_loss = std::numeric_limits<double>::infinity(); int no_improvement_count = 0; #endif // -------- main loop -------- size_t i; for(i = 1; i <= numIteration; i++) { dtrain_lap.lap_start(); auto updated_model = sgd_dtrain_with_trans<T>(i,alpha,isIntercept) (data,transData,label,sample_weight,model,grad,l_loss); dtrain_lap.lap_stop(); if(self == 0) trace.show("dtrain: "); reduce_lap.lap_start(); #ifdef _RMSE_CONV_RATE_CHECK_ auto prev_model = model; #endif // updated_model = updated_model - model calc_diff_inplace<MODEL>(updated_model, model); auto updated_model_weightp = updated_model.weight.data(); copy_weight(weight_interceptp, updated_model_weightp, weight_size); weight_interceptp[weight_size] = updated_model.intercept; // assume weight_size can be represented as int typed_allreduce(weight_interceptp, totaldiffvecp, weight_size + 1, MPI_SUM, frovedis_comm_rpc); typed_allreduce(&l_loss, &sumloss, 1, MPI_SUM, frovedis_comm_rpc); reduce_lap.lap_stop(); if(self == 0) trace.show("allreduce: "); update_lap.lap_start(); auto model_weightp = model.weight.data(); add_weight(model_weightp, totaldiffvecp, weight_size); model.intercept += totaldiffvecp[weight_size]; rType.regularize(model.weight, alpha / std::sqrt(i)); update_lap.lap_stop(); if(self == 0) trace.show("update and regularize: "); #ifdef _CONV_RATE_CHECK_ conv_lap.lap_start(); #ifdef _RMSE_CONV_RATE_CHECK_ auto prev_model_weightp = prev_model.weight.data(); T sum = local_diff_square_sum(prev_model_weightp, model_weightp, weight_size); T reduced_sum; typed_allreduce(&sum, &reduced_sum, 1, MPI_SUM, frovedis_comm_rpc); reduced_sum += (prev_model.intercept - model.intercept) * (prev_model.intercept - model.intercept); T RMSE = sqrt(reduced_sum/(weight_size + 1)); if(self == 0) trace.show("RMS error: " + std::to_string(RMSE) + ": "); if(RMSE < convergenceTol) { if(self == 0) { RLOG(INFO) << "Convergence achieved in " << ITOS(i) << " iterations.\n"; } break; } //#elif _LOSS_CHECK_ #else if (i > 1) { if (sumloss > best_loss - convergenceTol * nsamples) no_improvement_count++; else no_improvement_count = 0; if (sumloss < best_loss) best_loss = sumloss; if (no_improvement_count >= NITER_NO_CHANGE) { if(self == 0) { RLOG(INFO) << "Convergence achieved in " << ITOS(i) << " iterations.\n"; } break; } } #endif conv_lap.lap_stop(); #endif if(self == 0) { auto msg = " --- Epoch: " + std::to_string(i) + " ---\n"; msg += " -> norm(w): " + std::to_string(nrm2<T>(model.weight)); msg += ", bias: " + std::to_string(model.intercept); msg += ", avg. loss: " + std::to_string(sumloss / nsamples); msg += ", elapsed-time: "; trace_iter.show(msg); } } if(self == 0) { n_iter = (i == numIteration + 1) ? numIteration : i; reduce_lap.show_lap("allreduce time: "); dtrain_lap.show_lap("dtrain time: "); update_lap.show_lap("update time: "); #ifdef _CONV_RATE_CHECK_ conv_lap.show_lap("check convergence time: "); #endif } } template <class T, class DATA_MATRIX, class MODEL, class GRADIENT, class REGULARIZER> void do_train_notrans(std::vector<DATA_MATRIX>& data, std::vector<std::vector<T>>& label, MODEL& model, std::vector<std::vector<T>>& sample_weight, size_t& n_iter, sgd_config<GRADIENT, REGULARIZER>& config) { frovedis::time_spent trace(TRACE), trace_iter(DEBUG), reduce_lap(DEBUG), dtrain_lap(DEBUG), update_lap(DEBUG), conv_lap(DEBUG); // --- extract hyper-parameters --- auto numIteration = config.numIteration; auto alpha = config.alpha; auto convergenceTol = config.convergenceTol; auto isIntercept = config.isIntercept; auto nsamples = config.numSamples; auto grad = config.grad; auto rType = config.rType; auto self = get_selfid(); size_t weight_size = model.weight.size(); std::vector<T> weight_intercept(weight_size + 1); auto weight_interceptp = weight_intercept.data(); std::vector<T> totaldiffvec(weight_size + 1); auto totaldiffvecp = totaldiffvec.data(); double l_loss = 0.0, sumloss = 0.0; #ifdef _LOSS_CHECK_ double best_loss = std::numeric_limits<double>::infinity(); int no_improvement_count = 0; #endif // -------- main loop -------- size_t i; for(i = 1; i <= numIteration; i++) { dtrain_lap.lap_start(); auto updated_model = sgd_dtrain<T>(i,alpha,isIntercept)(data,label,sample_weight,model,grad,l_loss); dtrain_lap.lap_stop(); if(self == 0) trace.show("dtrain: "); reduce_lap.lap_start(); #ifdef _RMSE_CONV_RATE_CHECK_ auto prev_model = model; #endif // updated_model = updated_model - model calc_diff_inplace<MODEL>(updated_model, model); auto updated_model_weightp = updated_model.weight.data(); copy_weight(weight_interceptp, updated_model_weightp, weight_size); weight_interceptp[weight_size] = updated_model.intercept; // assume weight_size can be represented as int typed_allreduce(weight_interceptp, totaldiffvecp, weight_size + 1, MPI_SUM, frovedis_comm_rpc); typed_allreduce(&l_loss, &sumloss, 1, MPI_SUM, frovedis_comm_rpc); reduce_lap.lap_stop(); if(self == 0) trace.show("allreduce: "); update_lap.lap_start(); auto model_weightp = model.weight.data(); add_weight(model_weightp, totaldiffvecp, weight_size); model.intercept += totaldiffvecp[weight_size]; rType.regularize(model.weight, alpha / std::sqrt(i)); update_lap.lap_stop(); if(self == 0) trace.show("update and regularize: "); #ifdef _CONV_RATE_CHECK_ conv_lap.lap_start(); #ifdef _RMSE_CONV_RATE_CHECK_ auto prev_model_weightp = prev_model.weight.data(); T sum = local_diff_square_sum(prev_model_weightp, model_weightp, weight_size); T reduced_sum; typed_allreduce(&sum, &reduced_sum, 1, MPI_SUM, frovedis_comm_rpc); reduced_sum += (prev_model.intercept - model.intercept) * (prev_model.intercept - model.intercept); T RMSE = sqrt(reduced_sum/(weight_size + 1)); if(self == 0) trace.show("RMS error: " + std::to_string(RMSE) + ": "); if(RMSE < convergenceTol) { if(self == 0) { RLOG(INFO) << "Convergence achieved in " << ITOS(i) << " iterations.\n"; } break; } //#elif _LOSS_CHECK_ #else if (i > 1) { if (sumloss > best_loss - convergenceTol * nsamples) no_improvement_count++; else no_improvement_count = 0; if (sumloss < best_loss) best_loss = sumloss; if (no_improvement_count >= NITER_NO_CHANGE) { if(self == 0) { RLOG(INFO) << "Convergence achieved in " << ITOS(i) << " iterations.\n"; } break; } } #endif conv_lap.lap_stop(); #endif if(self == 0) { auto msg = " --- Epoch: " + std::to_string(i) + " ---\n"; msg += " -> norm(w): " + std::to_string(nrm2<T>(model.weight)); msg += ", bias: " + std::to_string(model.intercept); msg += ", avg. loss: " + std::to_string(sumloss / nsamples); msg += ", elapsed-time: "; trace_iter.show(msg); } } if(self == 0) { n_iter = (i == numIteration + 1) ? numIteration : i; reduce_lap.show_lap("allreduce time: "); dtrain_lap.show_lap("dtrain time: "); update_lap.show_lap("update time: "); #ifdef _CONV_RATE_CHECK_ conv_lap.show_lap("check convergence time: "); #endif } } // --- dense support --- template <class T, class MODEL, class GRADIENT, class REGULARIZER> MODEL sgd_parallelizer::parallelize(colmajor_matrix<T>& data, dvector<T>& label, MODEL& initModel, GRADIENT& grad, REGULARIZER& rType, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, bool isIntercept, double convergenceTol) { checkAssumption (numIteration > 0 && alpha > 0 && rType.regParam >= 0 && convergenceTol >= 0); size_t numFeatures = data.num_col; size_t numSamples = data.num_row; if(!numFeatures || !numSamples) REPORT_ERROR(USER_ERROR,"Empty training data\n"); if(numFeatures != initModel.get_num_features()) REPORT_ERROR (USER_ERROR,"Incompatible Test Vector with Provided Initial Model\n"); if(numSamples != label.size()) REPORT_ERROR (USER_ERROR,"Number of label and data are different\n"); time_spent t0(DEBUG); auto sizes = data.get_local_num_rows(); label.align_as(sizes); auto nloc_label = label.viewas_node_local(); t0.show("label resize & nloc: "); auto nsample_weight = make_dvector_scatter(sample_weight, sizes).moveto_node_local(); // just being sliced, no copy auto div_data = data.data.map(divide_data_to_minibatch_colmajor<T>, broadcast(miniBatchFraction)); auto div_label = nloc_label.map(divide_label_to_minibatch<T>, broadcast(miniBatchFraction)); auto div_sample_weight = nsample_weight.map(divide_sample_weight_to_minibatch<T>, broadcast(miniBatchFraction)); t0.show("divide minibatch: "); auto trainedModel = broadcast(initModel); sgd_config<GRADIENT, REGULARIZER> config(numIteration, alpha, convergenceTol, isIntercept, numSamples, grad, rType); auto nIter = make_node_local_allocate<size_t>(); div_data.mapv(do_train_notrans<T,sliced_colmajor_matrix_local<T>, MODEL,GRADIENT,REGULARIZER>, div_label, trainedModel, div_sample_weight, nIter, broadcast(config)); n_iter = nIter.get(0); return trainedModel.get(0); } template <class T, class I, class O, class MODEL, class GRADIENT, class REGULARIZER> MODEL sgd_parallelizer::parallelize(crs_matrix<T,I,O>& data, dvector<T>& label, MODEL& initModel, GRADIENT& grad, REGULARIZER& rType, std::vector<T>& sample_weight, size_t& n_iter, size_t numIteration, double alpha, bool isIntercept, double convergenceTol, MatType mType, bool inputMovable) { checkAssumption (numIteration > 0 && alpha > 0 && rType.regParam >= 0 && convergenceTol >= 0); size_t numFeatures = data.num_col; size_t numSamples = data.num_row; if(!numFeatures || !numSamples) REPORT_ERROR(USER_ERROR,"Empty training data\n"); if(numFeatures != initModel.get_num_features()) REPORT_ERROR (USER_ERROR,"Incompatible Test Vector with Provided Initial Model\n"); if(numSamples != label.size()) REPORT_ERROR (USER_ERROR,"Number of label and data are different\n"); time_spent t0(DEBUG); auto sizes = data.get_local_num_rows(); label.align_as(sizes); auto nloc_label = label.viewas_node_local(); t0.show("label resize & nloc: "); auto nsample_weight = make_dvector_scatter(sample_weight, sizes).moveto_node_local(); auto div_data = data.data.map(divide_data_to_minibatch_crs<T,I,O>, broadcast(miniBatchFraction)); auto div_label = nloc_label.map(divide_label_to_minibatch<T>, broadcast(miniBatchFraction)); auto div_sample_weight = nsample_weight.map(divide_sample_weight_to_minibatch<T>, broadcast(miniBatchFraction)); t0.show("divide minibatch: "); if(inputMovable) { // to free memory data.clear(); t0.show("clear input contents: "); } auto nIter = make_node_local_allocate<size_t>(); auto trainedModel = broadcast(initModel); sgd_config<GRADIENT, REGULARIZER> config(numIteration, alpha, convergenceTol, isIntercept, numSamples, grad, rType); // -------- selection of input matrix structure -------- if (mType == CRS) { auto trans_crs_vec = div_data.map(to_trans_crs_vec<T,I,O>); t0.show("to trans crs: "); div_data.mapv(do_train_with_trans<T,crs_matrix_local<T,I,O>, crs_matrix_local<T,I,O>,MODEL,GRADIENT,REGULARIZER>, trans_crs_vec, div_label, trainedModel, div_sample_weight, nIter, broadcast(config)); t0.show("training loop: "); } else if (mType == HYBRID) { auto jds_crs_vec = div_data.map(to_jds_crs_vec<T,I,O>); t0.show("to jds_crs: "); auto trans_jds_crs_vec = div_data.map(to_trans_jds_crs_vec<T,I,O>); t0.show("to trans jds_crs: "); div_data.mapv(clear_data_vector<T,I,O>); t0.show("clear div_data: "); jds_crs_vec.mapv(do_train_with_trans<T,jds_crs_hybrid_local<T,I,O>, jds_crs_hybrid_local<T,I,O>,MODEL,GRADIENT,REGULARIZER>, trans_jds_crs_vec, div_label, trainedModel, div_sample_weight, nIter, broadcast(config)); t0.show("training loop: "); } else if (mType == JDS) { auto jds_vec = div_data.map(to_jds_vec<T,I,O>); t0.show("to jds: "); auto trans_jds_vec = div_data.map(to_trans_jds_vec<T,I,O>); t0.show("to trans jds: "); div_data.mapv(clear_data_vector<T,I,O>); t0.show("clear div_data: "); jds_vec.mapv(do_train_with_trans<T,jds_matrix_local<T,I,O>, jds_matrix_local<T,I,O>,MODEL,GRADIENT,REGULARIZER>, trans_jds_vec, div_label, trainedModel, div_sample_weight, nIter, broadcast(config)); t0.show("training loop: "); } else if (mType == ELL) { auto ell_vec = div_data.map(to_ell_vec<T,I,O>); t0.show("to ell: "); div_data.mapv(clear_data_vector<T,I,O>); t0.show("clear div_data: "); ell_vec.mapv(do_train_notrans<T,ell_matrix_local<T,I>, MODEL,GRADIENT,REGULARIZER>, div_label, trainedModel, div_sample_weight, nIter, broadcast(config)); t0.show("training loop: "); } else REPORT_ERROR(USER_ERROR,"Unsupported input matrix type!!\n"); n_iter = nIter.get(0); return trainedModel.get(0); } } #endif
37.41982
87
0.607666
[ "vector", "model" ]
fd8ba0be87cd9a8356cb3b319d745530928314d8
5,227
cpp
C++
test/test_utils_diff.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
5
2015-03-02T22:29:00.000Z
2020-06-28T08:52:00.000Z
test/test_utils_diff.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
5
2019-05-10T02:28:00.000Z
2021-07-17T00:53:18.000Z
test/test_utils_diff.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
5
2016-05-25T07:31:16.000Z
2021-08-29T04:25:18.000Z
#include "../source/h2_unit.cpp" SUITE(similarity) { Case(edit distance) { OK(0, h2::h2_similarity::levenshtein("a", "a", 1, 1, false)); OK(1, h2::h2_similarity::levenshtein("a", "b", 1, 1, false)); OK(2, h2::h2_similarity::levenshtein("a", "bc", 1, 2, false)); OK(3, h2::h2_similarity::levenshtein("abc", "xyz", 3, 3, false)); } Case(absolute match) { OK(1, h2::h2_similarity::estimate("", "", false)); OK(1, h2::h2_similarity::estimate("a", "a", false)); OK(1, h2::h2_similarity::estimate("ab", "ab", false)); OK(1, h2::h2_similarity::estimate("abc", "abc", false)); } Case(absolute not match) { OK(0, h2::h2_similarity::estimate("a", "b", false)); OK(0, h2::h2_similarity::estimate("abc", "xyz", false)); } Case(not match) { OK(0.75, h2::h2_similarity::estimate("abcd", "abc1", false)); OK(0.75, h2::h2_similarity::estimate("abcd", "abce", false)); OK(0.5, h2::h2_similarity::estimate("abcd", "ab12", false)); OK(0.25, h2::h2_similarity::estimate("abcd", "a123", false)); OK(0.75, h2::h2_similarity::estimate("abcd", "1bcd", false)); OK(0.5, h2::h2_similarity::estimate("abcd", "12cd", false)); } } CASE(vector reserve initialize) { struct matrix { unsigned e : 1, p : 1, d : 6, c : 24; matrix() : e(1), p(1), d(5), c(55) {} }; h2::h2_vector<h2::h2_vector<matrix>> m; m.push_back(h2::h2_vector<matrix>(3)); for (int j = 0; j < 3; j++) { OK(1, m[0][j].e); OK(1, m[0][j].p); OK(5, m[0][j].d); OK(55, m[0][j].c); } } void __LCS_print(h2::h2_LCS& a, const char* t) { #define W3 " " for (size_t i = 0; i < a.s2.size() + 2; i++) { printf("%2s" W3, i < 2 ? "" : a.s2[i - 2].c_str()); } printf("\n"); for (size_t i = 0; i < a.m.size(); i++) { printf("%2s" W3, i == 0 ? "" : a.s1[i - 1].c_str()); for (size_t j = 0; j < a.m[i].size(); j++) { if ('c' == t[0]) { if (i == 0 || j == 0) printf("\033[90m%2d\033[0m" W3, (int)a.m[i][j].c); else printf("%2d" W3, (int)a.m[i][j].c); } else if ('d' == t[0]) { if (a.m[i][j].d == 9) { if (a.m[i][j].p || !strchr(t, 'p')) printf(" \033[32m←\033[0m" W3); else printf(" \033[36m←\033[0m" W3); } else if (a.m[i][j].d == 10) { if (a.m[i][j].p || !strchr(t, 'p')) printf(" \033[32m⬉\033[0m" W3); else printf(" \033[36m⬉\033[0m" W3); } else if (a.m[i][j].d == 12) { if (a.m[i][j].p || !strchr(t, 'p')) printf(" \033[32m↑\033[0m" W3); else printf(" \033[36m↑\033[0m" W3); } else { printf(" \033[90m‧\033[0m" W3); } } else if ('p' == t[0]) { if (a.m[i][j].p) printf(" \033[32m*\033[0m" W3); else printf(" \033[90m‧\033[0m" W3); } } printf("\n"); } printf("\n"); } void LCS_print(h2::h2_LCS& a) { __LCS_print(a, "c"); __LCS_print(a, "dp"); __LCS_print(a, "p"); } SUITE(LCS) { Case(same) { h2::h2_LCS a(h2::h2_string("abc").disperse(), h2::h2_string("abc").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 1, 1), ListOf(1, 1, 1)), ret); } Case(caseless) { h2::h2_LCS a(h2::h2_string("abc").disperse(), h2::h2_string("aBC").disperse(), true); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 1, 1), ListOf(1, 1, 1)), ret); } Case(utf8 中文) { h2::h2_LCS a(h2::h2_string("你好!").disperse(), h2::h2_string("您好!").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(0, 1, 1), ListOf(0, 1, 1)), ret); } Case(change char) { h2::h2_LCS a(h2::h2_string("abc").disperse(), h2::h2_string("a5c").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 0, 1), ListOf(1, 0, 1)), ret); } Case(add char) { h2::h2_LCS a(h2::h2_string("abc").disperse(), h2::h2_string("abxc").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 1, 1), ListOf(1, 1, 0, 1)), ret); } Case(insert word) { h2::h2_LCS a(h2::h2_string("hello world").disperse(), h2::h2_string("hello twe world").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ListOf(1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)), ret); } Case(hello/hel1o) { h2::h2_LCS a(h2::h2_string("hello").disperse(), h2::h2_string("hel1o").disperse()); auto ret = a.lcs(); // LCS_print(a); OK(Pair(ListOf(1, 1, 1, 0, 1), ListOf(1, 1, 1, 0, 1)), ret); } Case(inside table) { h2::h2_LCS a(h2::h2_string("he1lo wor1d!").disperse(), h2::h2_string("hello the world").disperse()); auto ret = a.lcs(); LCS_print(a); OK(Pair(ListOf(1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0), ListOf(1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1)), ret); } }
28.407609
117
0.47159
[ "vector" ]
fd8f97c59cabcf3aac9bcad579637e9e98f67e40
4,859
cpp
C++
src/loadedobject.cpp
QAston/opengl-engine-uni-2014
c951baf1a0fc08ece2c5ed22534c144d081217bc
[ "MIT" ]
null
null
null
src/loadedobject.cpp
QAston/opengl-engine-uni-2014
c951baf1a0fc08ece2c5ed22534c144d081217bc
[ "MIT" ]
null
null
null
src/loadedobject.cpp
QAston/opengl-engine-uni-2014
c951baf1a0fc08ece2c5ed22534c144d081217bc
[ "MIT" ]
null
null
null
#include "loadedobject.h" #include "objloader.h" #include "rwconfig.h" #include "tiny_obj_loader.h" #include <algorithm> #include <glm/glm.hpp> #include <iostream> #include <string> using namespace std; LoadedObject::LoadedObject(const vector<array<double, 3>> &vertici, const vector<array<int, 4>> &faces, const vector<array<double, 3>> &normals, tinyobj::material_t material, const vector<array<double, 2>> &texCoords, bool smooth) { vector<array<int, 4>>::const_iterator fit; _vertici = vertici; for (fit = faces.begin(); fit != faces.end(); ++fit) { array<GLubyte, 4> tmp; tmp[0] = (GLubyte)(*fit)[0]; tmp[1] = (GLubyte)(*fit)[1]; tmp[2] = (GLubyte)(*fit)[2]; tmp[3] = (GLubyte)(*fit)[3]; _faces.push_back(tmp); } _normals = normals; _material = material; _texCoords = texCoords; if (_material.diffuse_texname != "") { std::string s = resourcePath("/png/" + _material.diffuse_texname); _textureImage = loadPngImage(s.c_str(), _texWidth, _texHeight); if (_textureImage == nullptr) { cerr << "Unable to load png file :" << s << endl; } else { cout << "Image loaded. Width: " << _texWidth << " Height: " << _texHeight << endl; } } _smooth = smooth; } LoadedObject::~LoadedObject() { // dtor } BoundInfo LoadedObject::getBounds(glm::mat4 trans) { std::array<double, 6> ret{{0, 0, 0, 0, 0, 0}}; BoundInfo retObj; if (!_normals.empty()) { retObj.hasBounds = true; // init with first point { auto it = _vertici.begin(); glm::vec4 pos = glm::vec4(glm::vec3((*it)[0], (*it)[1], (*it)[2]), 1.0f); glm::vec4 point = trans * pos; ret[0] = point[0]; ret[1] = point[1]; ret[2] = point[2]; ret[3] = point[0]; ret[4] = point[1]; ret[5] = point[2]; } for (auto &it : _vertici) { glm::vec4 pos = glm::vec4(glm::vec3(it[0], it[1], it[2]), 1.0f); glm::vec4 point = trans * pos; if (point[0] <= ret[0]) { ret[0] = point[0]; } if (point[1] <= ret[1]) { ret[1] = point[1]; } if (point[2] <= ret[2]) { ret[2] = point[2]; } if (point[0] >= ret[3]) { ret[3] = point[0]; } if (point[1] >= ret[4]) { ret[4] = point[1]; } if (point[2] >= ret[5]) { ret[5] = point[2]; } } } else { retObj.hasBounds = false; } retObj.bounds = ret; return retObj; } void LoadedObject::draw() { if (!_normals.empty()) { glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_DOUBLE, 0, _normals.data()); } // glEnable(GL_LIGHTING); // glEnable(GL_LIGHT0); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_DOUBLE, 0, (double *)_vertici.data()); //} else // glEnableClientState (GL_COLOR_ARRAY); // glColorPointer (3, GL_FLOAT, 0, _colors.data()); glPolygonMode(GL_FRONT, GL_FILL); glPolygonMode(GL_BACK, GL_LINE); glFrontFace(GL_CCW); // glLoadIdentity (); // glTranslatef(_posX, _posY, _posZ); // glRotatef(rotateX, 0,1,0); // glRotatef(rotateY, 1,0,0); glShadeModel(GL_SMOOTH); glMaterialfv(GL_FRONT, GL_AMBIENT, _material.ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, _material.diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, _material.specular); glMaterialfv(GL_FRONT, GL_EMISSION, _material.emission); glMaterialf(GL_FRONT, GL_SHININESS, _material.shininess); glColor3fv(_material.diffuse); if (_textureImage != nullptr) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_DOUBLE, 0, _texCoords.data()); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 3, _texWidth, _texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, _textureImage); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glEnable(GL_TEXTURE_2D); } for (auto &_face : _faces) { glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, _face.data()); } // glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); if (!_normals.empty()) { glDisableClientState(GL_NORMAL_ARRAY); } // set GL state for non-textured objects if (_textureImage != nullptr) { glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } // glDisable(GL_LIGHTING); // glDisable(GL_LIGHT0); }
29.809816
80
0.594978
[ "vector" ]
fd90921ea29afcb72a6200f39bc25b08d0a82d59
6,885
cpp
C++
gmw_impl/circuit/socialnet.cpp
rlaishra/Privacy-Aware-Friends-Recommendation
a5757ef0b409bbcdebdb4e43b510a8d4d9070230
[ "MIT" ]
null
null
null
gmw_impl/circuit/socialnet.cpp
rlaishra/Privacy-Aware-Friends-Recommendation
a5757ef0b409bbcdebdb4e43b510a8d4d9070230
[ "MIT" ]
null
null
null
gmw_impl/circuit/socialnet.cpp
rlaishra/Privacy-Aware-Friends-Recommendation
a5757ef0b409bbcdebdb4e43b510a8d4d9070230
[ "MIT" ]
null
null
null
// socialnet.cpp #include "socialnet.h" #include <cassert> #include <cmath> using namespace std; BOOL CSNetCircuit::Create(int nParties, const vector<int>& vParams) { m_nNumParties = nParties; // parse params // params: width, depth, rep if( vParams.size() < (unsigned) 2 ) { cout << "Error! This circuit needs " << 2 << "parameter: type bits-in-integer" << endl << "type=0 for find-all-close-matches" << endl << "type=1 for find-closest-match" <<endl << "type=2 for find-best-resource" << endl; return FALSE; } m_nType = vParams[0]; m_nRep = vParams[1]; m_vNumVBits.resize(m_nNumParties, m_nRep); m_nTotItems = (nParties-1); m_nIdxRep = (int) ceil(log((double)m_nTotItems)/log(2.0)); m_nCntRep = (int) ceil(log(double(m_nRep))/log(2.0)); m_nCntRange = 1 << m_nCntRep; // gates for inputs: m_vInputStart.resize(nParties); m_vInputEnd.resize(nParties); m_nFrontier = 2; for(int i=0; i<nParties-1; i++) { m_vInputStart[i] = m_nFrontier; m_nFrontier += m_nRep*3; m_vInputEnd[i] = m_nFrontier - 1; } m_vInputStart[nParties-1] = m_nFrontier; m_nFrontier += m_nRep*4; m_vInputEnd[nParties-1] = m_nFrontier - 1; //=========================================================================== // computes roughly the number of gates beforehand --- need this for allocating space int gates_ge = 4*m_nRep+1; int gates_mux = 3*m_nRep; int gates_add = 6*m_nRep; int gates_sub = 6*m_nRep; int gates_dst = 2*gates_ge + 4*gates_mux + 2*m_nRep + 2*gates_sub + gates_add; int gates_cnt = 2*gates_add; int gates_cap = m_nRep; int gates_in = m_nRep; int gates_elm = 3*m_nRep + gates_cap + gates_cnt + gates_in; int gates_idx_mux = 3*m_nIdxRep; int gates_tournament = gates_ge + gates_mux + gates_idx_mux; int gates_noninput = m_nTotItems*( m_nIdxRep + gates_dst + gates_elm + gates_tournament ); m_othStartGate = m_nFrontier; m_nNumGates = m_nFrontier + gates_noninput; m_pGates = new GATE[m_nNumGates]; m_nNumXORs = 0; //============================================================================ // Now construct the circuit SetupInputGates(); if( m_nType == e_AllCloseMatches ) { CreateFindAllCloseMatches(); } else { m_vELMs.resize(m_nTotItems); for(int i=0; i<m_nTotItems; i++) { m_vELMs[i] = PutELMGate(i); } m_vIdxs.resize(m_nTotItems); for(int i=0; i<m_nTotItems; i++) { m_vELMs[i] = PutIdxGate(i); } PutLayerB(); PutOutputLayer(); } PatchParentFields(); return TRUE; } void CSNetCircuit::CreateFindAllCloseMatches() { vector<int> comp(m_nTotItems), in(m_nTotItems); int delta = m_vInputStart[m_nNumParties-1] + 3*m_nRep; int dst; for(int i=0; i<m_nTotItems; i++) { dst = PutDSTGate(i); comp[i] = PutGEGate(delta, dst, m_nRep); in[i] = PutINGate(i); } int out = m_nFrontier++; for(int i=0; i<m_nTotItems; i++) { PutANDGate(comp[i], in[i]); } m_vOutputStart.resize(m_nNumParties, 1); m_vOutputEnd.resize(m_nNumParties, 0); m_vOutputStart[m_nNumParties-1] = out; m_vOutputEnd[m_nNumParties-1] = out + m_nTotItems -1; m_nNumGates = m_nFrontier; } void CSNetCircuit::SetupInputGates() { GATE* gate; for(int i=0; i<m_othStartGate; i++) { gate = m_pGates + i; gate->p_ids = 0; gate->p_num = 0; gate->left = -1; gate->right = -1; gate->type = 0; gate->val = 0; } // constant 1 m_pGates[1].val = 1; } int CSNetCircuit::PutIdxGate(int r) { int start = m_nFrontier; int digit; for(int j=0; j<m_nIdxRep; j++) { digit = (r >> j) & 1; PutXORGate(digit,0); } return start; } int CSNetCircuit::PutDSTGate(int r) { int lr1 = 2+m_nRep*3*r; int lr2 = lr1+m_nRep; int hr = lr2+m_nRep; int l1 = m_vInputStart[m_nNumParties-1]; int l2 = l1 + m_nRep; int h = l2+m_nRep; int d = h+m_nRep; int c1 = PutGEGate(lr1, l1, m_nRep); int c2 = PutGEGate(lr2, l2, m_nRep); int a1 = PutMUXGate(lr1, l1, c1, m_nRep); int a2 = PutMUXGate(lr2, l2, c2, m_nRep); int b1 = PutMUXGate(lr1, l1, PutXORGate(1,c1), m_nRep); int b2 = PutMUXGate(lr2, l2, PutXORGate(1,c2), m_nRep); int dst = PutAddGate( PutSubGate(a1,b1,m_nRep), PutSubGate(a2,b2,m_nRep), m_nRep ); return 1; } int CSNetCircuit::PutCAPGate(int r) { int hr = 2 + 3*m_nRep*r + 2*m_nRep; int h = m_vInputStart[m_nNumParties-1] + 2*m_nRep; int out = m_nFrontier; for(int i=0; i<m_nRep; i++) PutANDGate(hr+i, h+i); return out; } int CSNetCircuit::PutCNTGate(int a) { vector<int> ins(m_nCntRange); for(int i=0; i<m_nRep; i++) ins[i] = a+i; for(int i=m_nRep; i<m_nCntRange; i++) ins[i] = 0; int out = PutCNTGate(ins, 1); return out; } int CSNetCircuit::PutCNTGate(const vector<int>& ins, int rep) { if( ins.size() == 1 ) return ins[0]; assert( ins.size() %2 == 0 ); vector<int> ins2((ins.size()+1)/2); for(unsigned i=0, j=0; i<ins.size(); ) { ins2[j++] = PutAddGate(ins[i], ins[i+1], rep, TRUE); i+=2; } return PutCNTGate(ins2, rep+1); } int CSNetCircuit::PutINGate(int r) { int h = m_vInputStart[m_nNumParties-1] + 2*m_nRep; int hr = 2 + 3*m_nRep*r + 2*m_nRep; int b1, aNb1; vector<int> s(m_nRep); for(int i=0; i<m_nRep; i++) { b1 = PutXORGate(hr+i, 1); aNb1 = PutANDGate(h+i, b1); s[i] = PutXORGate(1, aNb1); } return PutWideGate(G_AND, s); } void CSNetCircuit::PutLayerB() { // build a balanced binary tree int cmp; while( m_vELMs.size() > 1 ) { unsigned j=0; for(unsigned i=0; i<m_vELMs.size(); ) { if( i+1 >= m_vELMs.size() ) { m_vELMs[j] = m_vELMs[i]; m_vIdxs[j] = m_vIdxs[i]; i++; j++; } else { if( m_nType == e_ClosetMatch ) { cmp = PutGEGate(m_vELMs[i+1], m_vELMs[i], m_nRep); // elm[i] <= elm[i+1] ? m_vELMs[j] = PutMUXGate(m_vELMs[i], m_vELMs[i+1], cmp, m_nRep); m_vIdxs[j] = PutMUXGate(m_vIdxs[i], m_vIdxs[i+1], cmp, m_nIdxRep); } else // best resource { cmp = PutGEGate(m_vELMs[i], m_vELMs[i+1], m_nCntRep); // elm[i] >= elm[i+1] ? m_vELMs[j] = PutMUXGate(m_vELMs[i], m_vELMs[i+1], cmp, m_nCntRep); m_vIdxs[j] = PutMUXGate(m_vIdxs[i], m_vIdxs[i+1], cmp, m_nIdxRep); } i+=2; j++; } } m_vELMs.resize(j); m_vIdxs.resize(j); } } void CSNetCircuit::PutOutputLayer() { m_vOutputStart.resize(m_nNumParties, 1); m_vOutputEnd.resize(m_nNumParties, 0); m_vOutputStart[m_nNumParties-1] = m_vIdxs[0]; m_vOutputEnd[m_nNumParties-1] = m_vIdxs[0]+m_nIdxRep-1; m_nNumGates = m_nFrontier; } int CSNetCircuit::PutELMGate(int r) { if( m_nType == e_ClosetMatch ) { // find-closest-match int dst = PutDSTGate(r); int in = PutINGate(r); return PutELM1Gate(dst,in,m_nRep); } else { // find-best-resource int dst = PutDSTGate(r); int delta = m_vInputStart[m_nNumParties-1] + 3*m_nRep; int d = PutGEGate(delta, dst, m_nRep); int cap = PutCAPGate(r); int cnt = PutCNTGate(cap); return PutELM0Gate(cnt, d, m_nCntRep); } }
21.315789
91
0.630792
[ "vector" ]
fd95b3f303812e70395daa821510e75eac1a016b
4,206
hpp
C++
include/libtorrent/aux_/storage_utils.hpp
zhangzhui/libtorrent
b6642e2f70b9c0994c25154df91ece89df30a35e
[ "BSL-1.0", "BSD-3-Clause" ]
1
2019-05-23T12:23:40.000Z
2019-05-23T12:23:40.000Z
include/libtorrent/aux_/storage_utils.hpp
zhangzhui/libtorrent
b6642e2f70b9c0994c25154df91ece89df30a35e
[ "BSL-1.0", "BSD-3-Clause" ]
1
2017-09-19T08:52:30.000Z
2017-09-19T08:52:30.000Z
include/libtorrent/aux_/storage_utils.hpp
zhangzhui/libtorrent
b6642e2f70b9c0994c25154df91ece89df30a35e
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2003-2016, Arvid Norberg 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 author 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 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. */ #ifndef TORRENT_STORAGE_UTILS_HPP_INCLUDE #define TORRENT_STORAGE_UTILS_HPP_INCLUDE #include <cstdint> #include <string> #include "libtorrent/config.hpp" #include "libtorrent/fwd.hpp" #include "libtorrent/span.hpp" #include "libtorrent/span.hpp" #include "libtorrent/units.hpp" #include "libtorrent/storage_defs.hpp" // for status_t #include "libtorrent/session_types.hpp" namespace libtorrent { struct part_file; struct stat_cache; // TODO: 3 remove this typedef, and use span<char const> for disk write // operations using iovec_t = span<char>; namespace aux { TORRENT_EXTRA_EXPORT int copy_bufs(span<iovec_t const> bufs , int bytes, span<iovec_t> target); TORRENT_EXTRA_EXPORT span<iovec_t> advance_bufs(span<iovec_t> bufs, int bytes); TORRENT_EXTRA_EXPORT void clear_bufs(span<iovec_t const> bufs); // this is a read or write operation so that readwritev() knows // what to do when it's actually touching the file using fileop = std::function<int(file_index_t, std::int64_t, span<iovec_t const>, storage_error&)>; // this function is responsible for turning read and write operations in the // torrent space (pieces) into read and write operations in the filesystem // space (files on disk). TORRENT_EXTRA_EXPORT int readwritev(file_storage const& files , span<iovec_t const> bufs, piece_index_t piece, int offset , storage_error& ec, fileop op); // moves the files in file_storage f from ``save_path`` to // ``destination_save_path`` according to the rules defined by ``flags``. // returns the status code and the new save_path. TORRENT_EXTRA_EXPORT std::pair<status_t, std::string> move_storage(file_storage const& f , std::string save_path , std::string const& destination_save_path , part_file* pf , move_flags_t flags, storage_error& ec); // deletes the files on fs from save_path according to options. Options may // opt to only delete the partfile TORRENT_EXTRA_EXPORT void delete_files(file_storage const& fs, std::string const& save_path , std::string const& part_file_name, remove_flags_t options, storage_error& ec); TORRENT_EXTRA_EXPORT bool verify_resume_data(add_torrent_params const& rd , aux::vector<std::string, file_index_t> const& links , file_storage const& fs , aux::vector<download_priority_t, file_index_t> const& file_priority , stat_cache& stat , std::string const& save_path , storage_error& ec); // given the save_path, stat all files on file_storage until one exists. If a // file exists, return true, otherwise return false. TORRENT_EXTRA_EXPORT bool has_any_file( file_storage const& fs , std::string const& save_path , stat_cache& stat , storage_error& ec); }} #endif
38.587156
100
0.773657
[ "vector" ]
fd963e4772fd432ff150aee8e12e017888798c0b
10,538
cpp
C++
Tests/TestsRosicAndRapt/Source/rapt_tests/UnitTests/Math/NumberTheoryTests.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Tests/TestsRosicAndRapt/Source/rapt_tests/UnitTests/Math/NumberTheoryTests.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Tests/TestsRosicAndRapt/Source/rapt_tests/UnitTests/Math/NumberTheoryTests.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
bool testPrimeTableGeneration(std::string &reportString) { std::string testName = "PrimeTableGeneration"; bool testResult = true; // create table of primes up to 1000 and check against this target-table: static const rsUint32 np = 168; rsUint32 tp[np] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101, 103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197, 199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311, 313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431, 433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557, 563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661, 673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809, 811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937, 941,947,953,967,971,977,983,991,997}; rsUint32 i; std::vector<rsUint32> pa; rsFindPrimesUpTo(pa, (rsUint32)1000); testResult &= pa.size() == (rsInt32)np; for(i = 0; i < np; i++) testResult &= pa[i] == tp[i]; /* // commented because doesn't compile with gcc on windows - will cause this test to fail - // uncomment and fix underlying compilation problem rsUint32 p[np]; rsFillPrimeTable(p, np, (rsUint32)29); //rsFillPrimeTable(p, np, 32); for(i = 0; i < np; i++) testResult &= p[i] == tp[i]; // assume rsFindPrimesUpTo is correct - check alternative version against it: rsUint32 maxPrime = 1000000; rsFindPrimesUpTo(pa, maxPrime); rsUint32 numPrimes = pa.getNumElements(); rsUint32 *p2 = new rsUint32[numPrimes]; rsFillPrimeTable(p2, numPrimes, 1024); for(i = 0; i < numPrimes; i++) { testResult &= p2[i] == pa[i]; rsAssert(testResult == true); } delete[] p2; */ // suppose, we want to find all primes between 20000 and 21000 // the table with number, multiples of which should be crossed out should have its largest // element >= 21000-20000 = 1000 // 131 * 157 = 20567 // or 41*43 = 1763 -> find all primes between 1700 and 1800 // just for fun: //rsFindPrimesUpTo(pa, (rsUint32)1000000); //rsFindPrimesUpTo(pa, (rsUint32)10000000); //rsFindPrimesUpTo(pa, (rsUint32)4294967295); //for(int i = 0; i < pa.getNumElements(); i++) // printf("%d %s", pa[i], " "); appendTestResultToReport(reportString, testName, testResult); return testResult; } // reconstructs a numkber from its prime factorization (which can be obtained by rsPrimeFactors) // ...maybe move to RAPT library: rsUint32 rsPrimeProduct(std::vector<rsUint32>& factors, std::vector<rsUint32>& exponents) { rsAssert(factors.size() == exponents.size()); rsUint32 r = 1; for(size_t i = 0; i < factors.size(); i++) r *= rsPowInt(factors[i], exponents[i]); // todo: switch algo for rsPowInt...see implementation comment return r; } bool testPrimeFactorization(std::string &reportString) { std::string testName = "PrimeFactorization"; bool testResult = true; // factor all numbers from 0 to N and reconstruct them (todo: include negative numbers, too): std::vector<rsUint32> p, f, e; rsUint32 N = 100; for(rsUint32 i = 0; i <= N; i++) { rsPrimeFactors(i, f, e); rsUint32 j = rsPrimeProduct(f, e); // crashes for i == 5 testResult &= j == i; } /* // code below is factored out because it takes an unreasonably long time. i think, it doesn't // hang but legitimately takes a long time to factor these larger primes since i fixed the bug // with taking the integer square-root twice in rsPrimeFactors ...figure out... // factor some larger example numbers: rsUint32 x = 507996720; // = 2^4 * 3^2 * 5^1 * 7^3 * 11^2 * 17^1 rsPrimeFactors(x, f, e); testResult &= f.size() == 6; testResult &= f[0] == 2 && e[0] == 4; testResult &= f[1] == 3 && e[1] == 2; testResult &= f[2] == 5 && e[2] == 1; testResult &= f[3] == 7 && e[3] == 3; testResult &= f[4] == 11 && e[4] == 2; testResult &= f[5] == 17 && e[5] == 1; x = 431985125; // = 5^3 * 11^2 * 13^4 rsPrimeFactors(x, f, e); testResult &= f.size() == 3; testResult &= f[0] == 5 && e[0] == 3; testResult &= f[1] == 11 && e[1] == 2; testResult &= f[2] == 13 && e[2] == 4; */ appendTestResultToReport(reportString, testName, testResult); return testResult; } // template instantiation-wrappers to make the template-functions usable via function-pointers: rsInt32 modularInverseInst(rsInt32 x, rsInt32 m) { return rsModularInverse(x, m); } rsInt32 primeModularInverseInst(rsInt32 x, rsInt32 m) { return rsPrimeModularInverse(x, m); } rsInt32 primeModularInverseInst2(rsInt32 x, rsInt32 m) { return rsPrimeModularInverse2(x, m); } // test-function for different implementations of the modular inverse: bool testModularInverse(rsInt32 (*pModularInverse)(rsInt32, rsInt32), bool testNonPrimeModuli) { // values coprime to modulus m should have an inverse, otherwise the function should return 0 bool testResult = true; rsInt32 m, x, y; m = 7; x = 1; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 2; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 3; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 4; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 5; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 6; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; m = 3; x = 35; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; if( testNonPrimeModuli == true ) { m = 12; x = 0; y = pModularInverse(x, m); testResult &= y == 0; x = 1; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 2; y = pModularInverse(x, m); testResult &= y == 0; x = 3; y = pModularInverse(x, m); testResult &= y == 0; x = 4; y = pModularInverse(x, m); testResult &= y == 0; x = 5; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 6; y = pModularInverse(x, m); testResult &= y == 0; x = 7; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 8; y = pModularInverse(x, m); testResult &= y == 0; x = 9; y = pModularInverse(x, m); testResult &= y == 0; x = 10; y = pModularInverse(x, m); testResult &= y == 0; x = 11; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 12; y = pModularInverse(x, m); testResult &= y == 0; x = 13; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 14; y = pModularInverse(x, m); testResult &= y == 0; x = 15; y = pModularInverse(x, m); testResult &= y == 0; x = 16; y = pModularInverse(x, m); testResult &= y == 0; x = 17; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 18; y = pModularInverse(x, m); testResult &= y == 0; x = 19; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 20; y = pModularInverse(x, m); testResult &= y == 0; x = 21; y = pModularInverse(x, m); testResult &= y == 0; x = 22; y = pModularInverse(x, m); testResult &= y == 0; x = 23; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; // todo: test x <= 0 - in this case, the inversion function should add m to x unti it's // >= 0 m = 15; x = 1; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 2; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 3; y = pModularInverse(x, m); testResult &= y == 0; x = 4; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 5; y = pModularInverse(x, m); testResult &= y == 0; x = 6; y = pModularInverse(x, m); testResult &= y == 0; x = 7; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 8; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 9; y = pModularInverse(x, m); testResult &= y == 0; x = 10; y = pModularInverse(x, m); testResult &= y == 0; x = 11; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 12; y = pModularInverse(x, m); testResult &= y == 0; x = 13; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; x = 14; y = pModularInverse(x, m); testResult &= (x * y) % m == 1; } return testResult; } bool testNumberTheoryMisc(std::string &reportString) { std::string testName = "NumberTheoryMisc"; bool testResult = true; rsInt32 a, b, g, x, y; // extended Euclid algorithm: x = 42; y = 30; rsEGCD(x, y, a, b, g); // -2*42 + 3*30 = -84 + 90 = 6 = gcd(42, 30) testResult &= a == -2 && b == 3 && g == 6; x = 30; y = 42; rsEGCD(x, y, a, b, g); // 3*30 - 2*42 = 90 - 84 = 6 = gcd(30, 42) testResult &= a == 3 && b == -2 && g == 6; x = 1; y = 0; rsEGCD(x, y, a, b, g); // 1*1 + 0*0 = 1 + 0 = 1 = gcd(1, 0) testResult &= a == 1 && b == 0 && g == 1; x = 3; y = 0; rsEGCD(x, y, a, b, g); // 1*3 + 0*0 = 3 + 0 = 3 = gcd(3, 0) testResult &= a == 1 && b == 0 && g == 3; // modular power: testResult &= rsModularPow(3, 10, 0) == 1; testResult &= rsModularPow(3, 10, 1) == 3; testResult &= rsModularPow(3, 10, 2) == 9; testResult &= rsModularPow(3, 10, 3) == 7; testResult &= rsModularPow(3, 10, 4) == 1; testResult &= rsModularPow(3, 10, 5) == 3; testResult &= rsModularPow(3, 10, 6) == 9; testResult &= rsModularPow(3, 10, 7) == 7; // modular inversion: testResult &= testModularInverse(&modularInverseInst, true); testResult &= testModularInverse(&primeModularInverseInst, false); testResult &= testModularInverse(&primeModularInverseInst2, false); // chinese remainder theorem: rsInt32 remainders[3] = {2, 2, 6}; rsInt32 moduli[3] = {3, 5, 7}; rsInt32 R = rsChineseRemainderTheorem(remainders, moduli, 3); testResult &= R == 62; moduli[0] = 25; moduli[1] = 27; moduli[2] = 28; remainders[0] = 9; remainders[1] = 21; remainders[2] = 2; R = rsChineseRemainderTheorem(remainders, moduli, 3); testResult &= R == 534; appendTestResultToReport(reportString, testName, testResult); return testResult; } bool testNumberTheory() { std::string testName = "NumberTheory"; std::string dummy; bool testResult = true; testResult &= testPrimeTableGeneration(dummy); testResult &= testPrimeFactorization( dummy); testResult &= testNumberTheoryMisc( dummy); //appendTestResultToReport(reportString, testName, testResult); return testResult; }
40.375479
107
0.597172
[ "vector" ]
fd9702752d4ce2e78333f18b108e1de664490912
16,090
cpp
C++
Src/C_BaseLib/Box.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/C_BaseLib/Box.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
null
null
null
Src/C_BaseLib/Box.cpp
Voskrese/BoxLib-old-msvc
da83349af10ef8f951b7a5b3182fc7cd710abeec
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <iostream> #include <limits> #include <BLassert.H> #include <BoxLib.H> #include <Box.H> const Box& Box::TheUnitBox () { static const Box Unit(IntVect::TheZeroVector(), IntVect::TheZeroVector()); return Unit; } Box::Box () : smallend(IntVect::TheUnitVector()), bigend(IntVect::TheZeroVector()), btype() {} Box::Box (const IntVect& small, const int* vec_len) : smallend(small), bigend(D_DECL(small[0]+vec_len[0]-1, small[1]+vec_len[1]-1, small[2]+vec_len[2]-1)) {} Box::Box (const IntVect& small, const IntVect& big, IndexType t) : smallend(small), bigend(big), btype(t) {} Box::Box (const IntVect& small, const IntVect& big) : smallend(small), bigend(big) {} Box::Box (const IntVect& small, const IntVect& big, const IntVect& typ) : smallend(small), bigend(big), btype(typ) { BL_ASSERT(typ >= IntVect::TheZeroVector() && typ <= IntVect::TheUnitVector()); } Box& Box::convert (const IntVect& typ) { BL_ASSERT(typ >= IntVect::TheZeroVector() && typ <= IntVect::TheUnitVector()); IntVect shft(typ - btype.ixType()); bigend += shft; btype = IndexType(typ); return *this; } Box& Box::convert (IndexType t) { for (int dir = 0; dir < BL_SPACEDIM; dir++) { const unsigned int typ = t[dir]; const unsigned int bitval = btype[dir]; const int off = typ - bitval; bigend.shift(dir,off); btype.setType(dir, (IndexType::CellIndex) typ); } return *this; } Box BoxLib::convert (const Box& b, const IntVect& typ) { Box bx(b); bx.convert(typ); return bx; } Box BoxLib::convert (const Box& b, const IndexType& t) { Box bx(b); bx.convert(t); return bx; } Box BoxLib::surroundingNodes (const Box& b, int dir) { Box bx(b); bx.surroundingNodes(dir); return bx; } Box& Box::surroundingNodes (int dir) { if (!(btype[dir])) { bigend.shift(dir,1); // // Set dir'th bit to 1 = IndexType::NODE. // btype.set(dir); } return *this; } Box BoxLib::surroundingNodes (const Box& b) { Box bx(b); bx.surroundingNodes(); return bx; } Box& Box::surroundingNodes () { for (int i = 0; i < BL_SPACEDIM; ++i) if ((btype[i] == 0)) bigend.shift(i,1); btype.setall(); return *this; } Box BoxLib::enclosedCells (const Box& b, int dir) { Box bx(b); bx.enclosedCells(dir); return bx; } Box& Box::enclosedCells (int dir) { if (btype[dir]) { bigend.shift(dir,-1); // // Set dir'th bit to 0 = IndexType::CELL. // btype.unset(dir); } return *this; } Box BoxLib::enclosedCells (const Box& b) { Box bx(b); bx.enclosedCells(); return bx; } Box& Box::enclosedCells () { for (int i = 0 ; i < BL_SPACEDIM; ++i) if (btype[i]) bigend.shift(i,-1); btype.clear(); return *this; } Box BoxLib::grow (const Box& b, int i) { Box result = b; result.grow(i); return result; } Box BoxLib::grow (const Box& b, const IntVect& v) { Box result = b; result.grow(v); return result; } Box& Box::grow (Orientation face, int n_cell) { int idir = face.coordDir(); if (face.isLow()) smallend.shift(idir, -n_cell); else bigend.shift(idir,n_cell); return *this; } bool Box::numPtsOK (long& N) const { BL_ASSERT(ok()); N = length(0); for (int i = 1; i < BL_SPACEDIM; i++) { if (length(i) == 0) { N = 0; return true; } else if (N <= std::numeric_limits<long>::max()/length(i)) { N *= length(i); } else { // // The return value N will be undefined. // return false; } } return true; } long Box::numPts () const { long result; if (!numPtsOK(result)) { std::cout << "Bad box: " << *this << std::endl; BoxLib::Error("Arithmetic overflow in Box::numPts()"); } return result; } bool Box::numPtsOK () const { long ignore; return numPtsOK(ignore); } double Box::d_numPts () const { BL_ASSERT(ok()); return D_TERM(double(length(0)), *double(length(1)), *double(length(2))); } bool Box::volumeOK (long& N) const { BL_ASSERT(ok()); N = length(0)-btype[0]; for (int i = 1; i < BL_SPACEDIM; i++) { long diff = (length(i)-btype[i]); if (diff == 0) { N = 0; return true; } else if (N <= std::numeric_limits<long>::max()/diff) { N *= diff; } else { // // The return value of N will be undefined. // return false; } } return true; } long Box::volume () const { long result; if (!volumeOK(result)) BoxLib::Error("Arithmetic overflow in Box::volume()"); return result; } bool Box::volumeOK () const { long ignore; return volumeOK(ignore); } Box& Box::shiftHalf (int dir, int nzones) { const int nbit = (nzones<0 ? -nzones : nzones)%2; int nshift = nzones/2; // // Toggle btyp bit if nzones is odd. // const unsigned int bit_dir = btype[dir]; if (nbit) btype.flip(dir); if (nzones < 0) nshift -= (bit_dir ? nbit : 0); else nshift += (bit_dir ? 0 : nbit); smallend.shift(dir,nshift); bigend.shift(dir,nshift); return *this; } Box& Box::shiftHalf (const IntVect& nz) { for (int i = 0; i < BL_SPACEDIM; i++) shiftHalf(i,nz[i]); return *this; } void Box::next (IntVect& p) const { BL_ASSERT(contains(p)); p.shift(0,1); #if BL_SPACEDIM==2 if (!(p <= bigend)) { p.setVal(0,smallend[0]); p.shift(1,1); } #elif BL_SPACEDIM==3 if (!(p <= bigend)) { p.setVal(0,smallend[0]); p.shift(1,1); if (!(p <= bigend)) { p.setVal(1,smallend[1]); p.shift(2,1); } } #endif } // // Scan point over region of object Box with a vector incrment // point incrments by 0 direction portion of vector. When end of // Box is reached, an increment is made with the 1 direction portion // of the vector, and the 0 direction scan is resumed. // effectively, we are scanning a Box, whose length vector is the argument // vector over the object Box. // when scan is over, the argument point is over edge of object Box // this is the signal that we can go no further. // void Box::next (IntVect& p, const int* shv) const { BL_ASSERT(contains(p)); #if BL_SPACEDIM==1 p.shift(0,shv[0]); #elif BL_SPACEDIM==2 p.shift(0,shv[0]); if (!(p <= bigend)) { // // Reset 1 coord is on edge, and 2 coord is incremented. // p.setVal(0,smallend[0]); p.shift(1,shv[1]); } #elif BL_SPACEDIM==3 p.shift(0,shv[0]); if (!(p <= bigend)) { // // Reset 1 coord is on edge, and 2 coord is incremented. // p.setVal(0,smallend[0]); p.shift(1,shv[1]); if(!(p <= bigend)) { p.setVal(1,smallend[1]); p.shift(2,shv[2]); } } #endif } Box BoxLib::refine (const Box& b, int ref_ratio) { Box result = b; result.refine(IntVect(D_DECL(ref_ratio,ref_ratio,ref_ratio))); return result; } Box& Box::refine (int ref_ratio) { return this->refine(IntVect(D_DECL(ref_ratio,ref_ratio,ref_ratio))); } Box BoxLib::refine (const Box& b, const IntVect& ref_ratio) { Box result = b; result.refine(ref_ratio); return result; } Box& Box::refine (const IntVect& ref_ratio) { IntVect shft(IntVect::TheUnitVector()); shft -= btype.ixType(); smallend *= ref_ratio; bigend += shft; bigend *= ref_ratio; bigend -= shft; return *this; } // // Define a macro which will compute an object's length vector from // the smallend and bigend. Do several versions according to dimension // requires you to be in a member functions. int Box::longside () const { int ignore = 0; return longside(ignore); } int Box::longside (int& dir) const { int maxlen = length(0); dir = 0; for (int i = 1; i < BL_SPACEDIM; i++) { if (length(i) > maxlen) { maxlen = length(i); dir = i; } } return maxlen; } int Box::shortside () const { int ignore = 0; return shortside(ignore); } int Box::shortside (int& dir) const { int minlen = length(0); dir = 0; for (int i = 1; i < BL_SPACEDIM; i++) { if (length(i) < minlen) { minlen = length(i); dir = i; } } return minlen; } // // Modified Box is low end, returned Box is high end. // If CELL: chop_pnt included in high end. // If NODE: chop_pnt included in both Boxes. // Box Box::chop (int dir, int chop_pnt) { // // Define new high end Box including chop_pnt. // IntVect sm(smallend); IntVect bg(bigend); sm.setVal(dir,chop_pnt); if (btype[dir]) { // // NODE centered Box. // BL_ASSERT(chop_pnt > smallend[dir] && chop_pnt < bigend[dir]); // // Shrink original Box to just contain chop_pnt. // bigend.setVal(dir,chop_pnt); } else { // // CELL centered Box. // BL_ASSERT(chop_pnt > smallend[dir] && chop_pnt <= bigend[dir]); // // Shrink origional Box to one below chop_pnt. // bigend.setVal(dir,chop_pnt-1); } return Box(sm,bg,btype); } Box BoxLib::coarsen (const Box& b, int ref_ratio) { Box result = b; result.coarsen(IntVect(D_DECL(ref_ratio,ref_ratio,ref_ratio))); return result; } Box& Box::coarsen (int ref_ratio) { return this->coarsen(IntVect(D_DECL(ref_ratio,ref_ratio,ref_ratio))); } Box BoxLib::coarsen (const Box& b, const IntVect& ref_ratio) { Box result = b; result.coarsen(ref_ratio); return result; } Box& Box::coarsen (const IntVect& ref_ratio) { smallend.coarsen(ref_ratio); if (btype.any()) { IntVect off(IntVect::TheZeroVector()); for (int dir = 0; dir < BL_SPACEDIM; dir++) { if (btype[dir]) if (bigend[dir]%ref_ratio[dir]) off.setVal(dir,1); } bigend.coarsen(ref_ratio); bigend += off; } else { bigend.coarsen(ref_ratio); } return *this; } // // I/O functions. // std::ostream& operator<< (std::ostream& os, const Box& b) { os << '(' << b.smallEnd() << ' ' << b.bigEnd() << ' ' << b.type() << ')'; if (os.fail()) BoxLib::Error("operator<<(ostream&,Box&) failed"); return os; } // // Moved out of Utility.H // #define BL_IGNORE_MAX 100000 std::istream& operator>> (std::istream& is, Box& b) { IntVect lo, hi, typ; is >> std::ws; char c; is >> c; if (c == '(') { is >> lo >> hi; is >> c; // Read an optional IndexType is.putback(c); if ( c == '(' ) { is >> typ; } is.ignore(BL_IGNORE_MAX,')'); } else if (c == '<') { is.putback(c); is >> lo >> hi; is >> c; // Read an optional IndexType is.putback(c); if ( c == '<' ) { is >> typ; } //is.ignore(BL_IGNORE_MAX,'>'); } else { BoxLib::Error("operator>>(istream&,Box&): expected \'(\'"); } b = Box(lo,hi,typ); if (is.fail()) BoxLib::Error("operator>>(istream&,Box&) failed"); return is; } Box BoxLib::minBox (const Box& b, const Box& o) { Box result = b; result.minBox(o); return result; } Box& Box::minBox (const Box &b) { BL_ASSERT(b.ok() && ok()); BL_ASSERT(sameType(b)); smallend.min(b.smallend); bigend.max(b.bigend); return *this; } Box BoxLib::bdryLo (const Box& b, int dir, int len) { IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); int sm = low[dir]; hi.setVal(dir,sm+len-1); // // set dir'th bit to 1 = IndexType::NODE. // IndexType typ(b.ixType()); typ.set(dir); return Box(low,hi,typ); } Box BoxLib::bdryHi (const Box& b, int dir, int len) { IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); unsigned int bitval = b.type()[dir]; int bg = hi[dir] + 1 - bitval%2; low.setVal(dir,bg); hi.setVal(dir,bg+len-1); // // Set dir'th bit to 1 = IndexType::NODE. // IndexType typ(b.ixType()); typ.set(dir); return Box(low,hi,typ); } Box BoxLib::bdryNode (const Box& b, Orientation face, int len) { int dir = face.coordDir(); IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); if (face.isLow()) { int sm = low[dir]; hi.setVal(dir,sm+len-1); } else { unsigned int bitval = b.type()[dir]; int bg = hi[dir] + 1 - bitval%2; low.setVal(dir,bg); hi.setVal(dir,bg+len-1); } // // Set dir'th bit to 1 = IndexType::NODE. // IndexType typ(b.ixType()); typ.set(dir); return Box(low,hi,typ); } Box BoxLib::adjCellLo (const Box& b, int dir, int len) { BL_ASSERT(len > 0); IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); int sm = low[dir]; low.setVal(dir,sm - len); hi.setVal(dir,sm - 1); // // Set dir'th bit to 0 = IndexType::CELL. // IndexType typ(b.ixType()); typ.unset(dir); return Box(low,hi,typ); } Box BoxLib::adjCellHi (const Box& b, int dir, int len) { BL_ASSERT(len > 0); IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); unsigned int bitval = b.type()[dir]; int bg = hi[dir] + 1 - bitval%2; low.setVal(dir,bg); hi.setVal(dir,bg + len - 1); // // Set dir'th bit to 0 = IndexType::CELL. // IndexType typ(b.ixType()); typ.unset(dir); return Box(low,hi,typ); } Box BoxLib::adjCell (const Box& b, Orientation face, int len) { BL_ASSERT(len > 0); IntVect low(b.smallEnd()); IntVect hi(b.bigEnd()); int dir = face.coordDir(); if (face.isLow()) { int sm = low[dir]; low.setVal(dir,sm - len); hi.setVal(dir,sm - 1); } else { unsigned int bitval = b.type()[dir]; int bg = hi[dir] + 1 - bitval%2; low.setVal(dir,bg); hi.setVal(dir,bg + len - 1); } // // Set dir'th bit to 0 = IndexType::CELL. // IndexType typ(b.ixType()); typ.unset(dir); return Box(low,hi,typ); } bool Box::sameSize (const Box& b) const { BL_ASSERT(sameType(b)); return D_TERM(length(0) == b.length(0), && length(1)==b.length(1), && length(2)==b.length(2)); } int Box::operator[] (Orientation face) const { const int dir = face.coordDir(); return face.isLow() ? smallend[dir] : bigend[dir]; } Box& Box::setRange (int dir, int sm_index, int n_cells) { smallend.setVal(dir,sm_index); bigend.setVal(dir,sm_index+n_cells-1); return *this; } bool Box::isSquare () const { const IntVect size = this->size(); #if BL_SPACEDIM==2 return (size[0] == size[1]); #elif BL_SPACEDIM==3 return (size[0] == size[1] && (size[1] == size[2])); #endif }
18.796729
82
0.519826
[ "object", "vector" ]
fd99381af6795e5bd9ad89fe21a4a62f7730456c
4,966
cpp
C++
roomedit/owl-6.34/source/monthcal.cpp
Darkman-M59/Meridian59_115
671b7ebe9fa2b1f40c8bd453652d596042291b90
[ "FSFAP" ]
null
null
null
roomedit/owl-6.34/source/monthcal.cpp
Darkman-M59/Meridian59_115
671b7ebe9fa2b1f40c8bd453652d596042291b90
[ "FSFAP" ]
null
null
null
roomedit/owl-6.34/source/monthcal.cpp
Darkman-M59/Meridian59_115
671b7ebe9fa2b1f40c8bd453652d596042291b90
[ "FSFAP" ]
null
null
null
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1998 by Bidus Yura, All Rights Reserved // /// \file /// Implementation of the TMonthCalendar class //---------------------------------------------------------------------------- #include <owl/pch.h> #include <owl/monthcal.h> namespace owl { OWL_DIAGINFO; DIAG_DECLARE_GROUP(OwlCommCtrl); // CommonCtrl Diagnostic group // // // TMonthCalendar::TMonthCalendar(TWindow* parent, int id, int x, int y, int w, int h, TModule* module) : TControl(parent,id,_T(""),x,y,w,h,module) { // Does this apply to extended common controls? if (!TCommCtrl::IsAvailable() && TCommCtrl::Dll()->GetCtrlVersion() > ComCtlVersionIE4) TXCommCtrl::Raise(); TCommCtrl::Dll()->CheckCommonControl(ICC_DATE_CLASSES); } // // // TMonthCalendar::TMonthCalendar(TWindow* parent, int resourceId, TModule* module) : TControl(parent, resourceId, module) { // Does this apply to extended common controls? if (!TCommCtrl::IsAvailable() && TCommCtrl::Dll()->GetCtrlVersion() > ComCtlVersionIE4) TXCommCtrl::Raise(); TCommCtrl::Dll()->CheckCommonControl(ICC_DATE_CLASSES); } // /// Constructs a month calendar object to encapsulate (alias) an existing control. // TMonthCalendar::TMonthCalendar(THandle hWnd, TModule* module) : TControl(hWnd, module) { // Does this apply to extended common controls? if (!TCommCtrl::IsAvailable() && TCommCtrl::Dll()->GetCtrlVersion() > ComCtlVersionIE4) TXCommCtrl::Raise(); TCommCtrl::Dll()->CheckCommonControl(ICC_DATE_CLASSES); } // // // TMonthCalendar::~TMonthCalendar() { } // Return the proper class name. // Windows class: MONTHCAL_CLASS is defined in commctrl.h TWindow::TGetClassNameReturnType TMonthCalendar::GetClassName() { return MONTHCAL_CLASS; } // // // int TMonthCalendar::GetMonthRange(TSystemTime& minm, TSystemTime& maxm, uint32 flags) const { PRECONDITION(GetHandle()); SYSTEMTIME sysTimes[2]; memset(sysTimes, 0, sizeof(sysTimes)); int count = (int)((TMonthCalendar*)this)->SendMessage(MCM_GETMONTHRANGE, TParam1(flags), TParam2(sysTimes)); minm = sysTimes[0]; maxm = sysTimes[1]; return count; } // // // uint32 TMonthCalendar::GetRange(TSystemTime& minm, TSystemTime& maxm) const { PRECONDITION(GetHandle()); SYSTEMTIME sysTimes[2]; memset(sysTimes, 0, sizeof(sysTimes)); uint32 ranges = (uint32)((TMonthCalendar*)this)->SendMessage(MCM_GETRANGE, 0, TParam2(sysTimes)); minm = TSystemTime(0,0,0); maxm = TSystemTime(0,0,0); if (ranges & GDTR_MIN) minm = sysTimes[0]; if (ranges & GDTR_MAX) maxm = sysTimes[1]; return ranges; } // // // bool TMonthCalendar::SetRange(const TSystemTime& minm, const TSystemTime& maxm) { PRECONDITION(GetHandle()); SYSTEMTIME sysTimes[2]; sysTimes[0] = minm; sysTimes[1] = maxm; return ToBool(SendMessage(MCM_SETRANGE, GDTR_MAX|GDTR_MIN, TParam2(sysTimes))); } // // // bool TMonthCalendar::SetMinDate(const TSystemTime& minm) { PRECONDITION(GetHandle()); SYSTEMTIME sysTimes[2]; sysTimes[0] = minm; return ToBool(SendMessage(MCM_SETRANGE, GDTR_MIN, TParam2(sysTimes))); } // // // bool TMonthCalendar::SetMaxDate(const TSystemTime& maxm) { PRECONDITION(GetHandle()); SYSTEMTIME sysTimes[2]; sysTimes[1] = maxm; return ToBool(SendMessage(MCM_SETRANGE, GDTR_MAX, TParam2(sysTimes))); } // // // bool TMonthCalendar::GetSelRange(TSystemTime& minm, TSystemTime& maxm) const { PRECONDITION(GetHandle()); PRECONDITION(GetStyle() & MCS_MULTISELECT); SYSTEMTIME sysTimes[2]; bool retval = ToBool(((TMonthCalendar*)this)->SendMessage(MCM_GETSELRANGE, 0, TParam2(sysTimes))); if (retval){ minm = sysTimes[0]; maxm = sysTimes[1]; } return retval; } bool TMonthCalendar::SetSelRange(const TSystemTime& minm, const TSystemTime& maxm) { PRECONDITION(GetHandle()); PRECONDITION(GetStyle() & MCS_MULTISELECT); SYSTEMTIME sysTimes[2]; sysTimes[0] = minm; sysTimes[1] = maxm; return ToBool(SendMessage(MCM_SETSELRANGE,0, TParam2(sysTimes))); } // // // uint TMonthCalendar::Transfer(void* buffer, TTransferDirection direction) { TMonthCalendarData* mcData = (TMonthCalendarData*)buffer; if (direction == tdGetData) { if(mcData->MultiSel) GetSelRange(mcData->Date1, mcData->Date2); else GetCurSel(mcData->Date1); } else if (direction == tdSetData) { if(mcData->MultiSel) SetSelRange(mcData->Date1, mcData->Date2); else SetCurSel(mcData->Date1); } return sizeof(TMonthCalendarData); } } // OWL namespace /* ========================================================================== */
23.205607
101
0.62948
[ "object" ]
fd9f038eff1bdacc0a327bfec3e00b76fa3c82a9
5,984
hpp
C++
benchmarks/dmitry_mpsc.hpp
Donald-Rupin/mpsc_zib
451328815a5cc3977750d61e1b7cd85ffd7108ae
[ "MIT" ]
1
2021-09-30T07:29:24.000Z
2021-09-30T07:29:24.000Z
benchmarks/dmitry_mpsc.hpp
Donald-Rupin/mpsc_zib
451328815a5cc3977750d61e1b7cd85ffd7108ae
[ "MIT" ]
null
null
null
benchmarks/dmitry_mpsc.hpp
Donald-Rupin/mpsc_zib
451328815a5cc3977750d61e1b7cd85ffd7108ae
[ "MIT" ]
null
null
null
/* * [....... [..[..[.. [.. * [.. [..[. [.. * [.. [..[. [.. * [.. [..[... [. * [.. [..[. [.. * [.. [..[. [. * [...........[..[.... [.. * * * MIT License * * Copyright (c) 2021 Donald-Rupin * * 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. * * * @file dmitry_mpsc.hpp * * This is an implementation of Dmitry Vyukov's Non-intrusive mpsc queue. * * Whilst I have re-written the code in c++, I will include his license here too since it is his design. * * Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * * of conditions and the following disclaimer in the documentation and/or other materials * * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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. * * The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Dmitry Vyukov. * * * */ #ifndef ZIB_DMITRY_MPSC_HPP_ #define ZIB_DMITRY_MPSC_HPP_ #include <atomic> #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <vector> namespace zib { namespace dmitry_details { /* Shamelssly takend from * https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size * as in some c++ libraries it doesn't exists */ #ifdef __cpp_lib_hardware_interference_size using std::hardware_constructive_interference_size; using std::hardware_destructive_interference_size; #else // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ // ... constexpr std::size_t hardware_constructive_interference_size = 2 * sizeof(std::max_align_t); constexpr std::size_t hardware_destructive_interference_size = 2 * sizeof(std::max_align_t); #endif } // namespace dmitry_details template <typename T> class dmitry_mpsc { static constexpr auto kEmpty = std::numeric_limits<std::size_t>::max(); static constexpr auto kAlignment = dmitry_details::hardware_destructive_interference_size; struct alignas(kAlignment) node { node() : next_(nullptr) { } node(T _value) : next_(nullptr), data_(_value) { } std::atomic<node*> next_ alignas(kAlignment); T data_; }; public: using value_type = T; dmitry_mpsc(std::uint16_t) : head_(new node), tail_(head_) { } ~dmitry_mpsc() { while (head_.load()) { auto tmp = head_.load(); head_.store(tmp->next_.load()); delete tmp; } } void enqueue(T _data, std::uint16_t) noexcept { auto p = new node(_data); auto old = head_.exchange(p, std::memory_order_acq_rel); old->next_.store(p, std::memory_order_release); } std::optional<T> dequeue() noexcept { auto next = tail_->next_.load(std::memory_order_acquire); if (next) { auto tmp = tail_; tail_ = next; auto data = next->data_; delete tmp; return data; } else { return std::nullopt; } } private: std::atomic<node*> head_ alignas(kAlignment); node* tail_ alignas(kAlignment); char padding_[kAlignment - sizeof(tail_)]; }; }; // namespace zib #endif
33.244444
100
0.621992
[ "vector" ]
fda46a0bb4370873e9bbf0fd9c39578ca1f1a964
4,980
cc
C++
chrome/browser/profiles/reporting_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/profiles/reporting_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/profiles/reporting_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 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/profiles/reporting_util.h" #include <string> #include <vector> #include "base/callback.h" #include "base/values.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/account_id/account_id.h" #include "components/embedder_support/user_agent_utils.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/login/users/affiliation.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { // Returns policy for the given |profile|. If failed to get policy returns // nullptr. const enterprise_management::PolicyData* GetPolicyData(Profile* profile) { if (!profile) return nullptr; auto* manager = #if BUILDFLAG(IS_CHROMEOS_ASH) profile->GetUserCloudPolicyManagerChromeOS(); #else profile->GetUserCloudPolicyManager(); #endif if (!manager) return nullptr; policy::CloudPolicyStore* store = manager->core()->store(); if (!store || !store->has_policy()) return nullptr; return store->policy(); } // Returns User DMToken for a given |profile| if: // * |profile| is NOT incognito profile. // * |profile| is NOT sign-in screen profile // * user corresponding to a |profile| is managed. // Otherwise returns empty string. More about DMToken: // go/dmserver-domain-model#dmtoken. std::string GetUserDmToken(Profile* profile) { if (!profile) return std::string(); const enterprise_management::PolicyData* policy = GetPolicyData(profile); if (!policy || !policy->has_request_token()) return std::string(); return policy->request_token(); } #if BUILDFLAG(IS_CHROMEOS_ASH) // A callback which fetches device dm_token based on user affiliation. using DeviceDMTokenCallback = base::RepeatingCallback<std::string( const std::vector<std::string>& user_affiliation_ids)>; // Returns the Device DMToken for the given |profile| if: // * |profile| is NOT incognito profile // * user corresponding to a given |profile| is affiliated. // Otherwise returns empty string. More about DMToken: // go/dmserver-domain-model#dmtoken. std::string GetDeviceDmToken(Profile* profile) { if (!profile) return std::string(); const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); if (!user) return std::string(); DeviceDMTokenCallback device_dm_token_callback = ash::GetDeviceDMTokenForUserPolicyGetter(user->GetAccountId()); if (!device_dm_token_callback) return std::string(); const enterprise_management::PolicyData* policy = GetPolicyData(profile); if (!policy) return std::string(); std::vector<std::string> user_affiliation_ids( policy->user_affiliation_ids().begin(), policy->user_affiliation_ids().end()); return device_dm_token_callback.Run(user_affiliation_ids); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) } // namespace namespace reporting { base::Value GetContext(Profile* profile) { base::Value context(base::Value::Type::DICTIONARY); context.SetStringPath("browser.userAgent", embedder_support::GetUserAgent()); if (!profile) return context; ProfileAttributesStorage& storage = g_browser_process->profile_manager()->GetProfileAttributesStorage(); ProfileAttributesEntry* entry = storage.GetProfileAttributesWithPath(profile->GetPath()); if (entry) { context.SetStringPath("profile.profileName", entry->GetName()); context.SetStringPath("profile.gaiaEmail", entry->GetUserName()); } context.SetStringPath("profile.profilePath", profile->GetPath().AsUTF8Unsafe()); const enterprise_management::PolicyData* policy = GetPolicyData(profile); if (policy) { if (policy->has_device_id()) context.SetStringPath("profile.clientId", policy->device_id()); #if BUILDFLAG(IS_CHROMEOS_ASH) std::string device_dm_token = GetDeviceDmToken(profile); if (!device_dm_token.empty()) context.SetStringPath("device.dmToken", device_dm_token); #endif std::string user_dm_token = GetUserDmToken(profile); if (!user_dm_token.empty()) context.SetStringPath("profile.dmToken", user_dm_token); } return context; } } // namespace reporting
32.54902
79
0.746185
[ "vector", "model" ]
fdb47dec15088963fa9f59c7d8362a99beb3b673
1,052
cpp
C++
opencv-2.4.11/samples/android/tutorial-4-cuda/jni/jni_part.cpp
durai-chellamuthu/node-opencv
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
[ "MIT" ]
13
2015-03-01T07:03:17.000Z
2021-11-03T06:33:31.000Z
opencv-2.4.11/samples/android/tutorial-4-cuda/jni/jni_part.cpp
durai-chellamuthu/node-opencv
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
[ "MIT" ]
1
2019-08-14T02:56:04.000Z
2019-08-14T03:53:21.000Z
opencv-2.4.11/samples/android/tutorial-4-cuda/jni/jni_part.cpp
durai-chellamuthu/node-opencv
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
[ "MIT" ]
32
2015-06-08T08:59:51.000Z
2021-08-05T09:54:16.000Z
#include <jni.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/gpu/gpu.hpp> #include <vector> using namespace std; using namespace cv; using namespace cv::gpu; #include <android/log.h> #define LOG_TAG "Cuda" #define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) extern "C" { JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial4_Tutorial4Activity_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba); JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial4_Tutorial4Activity_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba) { Mat& mGr = *(Mat*)addrGray; Mat& mRgb = *(Mat*)addrRgba; vector<KeyPoint> keypoints; GpuMat grGpu(mGr); FAST_GPU fast(50); fast(grGpu, GpuMat(), keypoints); for( unsigned int i = 0; i < keypoints.size(); i++ ) { const KeyPoint& kp = keypoints[i]; circle(mRgb, Point(kp.pt.x, kp.pt.y), 10, Scalar(255,0,0,255)); } } }
29.222222
138
0.717681
[ "vector" ]
fdb4afbfecaac08174c3d467758235a8cf218327
8,108
cc
C++
chrome/chrome_cleaner/test/test_pup_data.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/chrome_cleaner/test/test_pup_data.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/chrome_cleaner/test/test_pup_data.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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/chrome_cleaner/test/test_pup_data.h" #include "base/logging.h" #include "chrome/chrome_cleaner/proto/shared_pup_enums.pb.h" #include "chrome/chrome_cleaner/pup_data/uws_catalog.h" namespace chrome_cleaner { namespace { const PUPData::UwSSignature kEmptyPUP = {PUPData::kInvalidUwSId, PUPData::FLAGS_NONE, nullptr, 0, kNoDisk, kNoRegistry, kNoCustomMatcher}; } // namespace TestPUPData* TestPUPData::current_test_ = nullptr; TestPUPData* TestPUPData::previous_test_ = nullptr; SimpleTestPUP::SimpleTestPUP() : PUPData::PUP(&kEmptyPUP) {} TestPUPData::TestPUPData() : previous_catalogs_(PUPData::GetUwSCatalogs()) { // Make sure tests don't step on each other. previous_test_ = current_test_; current_test_ = this; // Assume there will be no additional UwSCatalogs used during the test. If // not, the caller can call Reset again with an explicit list of catalogs. Reset({}); } TestPUPData::~TestPUPData() { // Reset the global PUP data to the non-test version. PUPData::InitializePUPData(previous_catalogs_); CHECK_EQ(this, current_test_); current_test_ = previous_test_; } void TestPUPData::Reset(const PUPData::UwSCatalogs& additional_uws_catalogs) { CHECK_EQ(this, current_test_); cpp_pup_footprints_.clear(); mirror_pup_footprints_.clear(); PUPData::UwSCatalogs uws_catalogs = additional_uws_catalogs; uws_catalogs.push_back(this); PUPData::InitializePUPData(uws_catalogs); } void TestPUPData::AddPUP(UwSId pup_id, PUPData::Flags flags, const char* name, size_t max_files_to_remove) { CHECK_EQ(this, current_test_); size_t mirror_index = EnsurePUP(pup_id); mirror_pup_footprints_[mirror_index].flags = flags; mirror_pup_footprints_[mirror_index].max_files_to_remove = max_files_to_remove; // We keep a C++ version of the strings to control lifespan of the pointer // put in the C array. if (name) { cpp_pup_footprints_[pup_id].name = name; mirror_pup_footprints_[mirror_index].name = cpp_pup_footprints_[pup_id].name.c_str(); } else { cpp_pup_footprints_[pup_id].name.clear(); mirror_pup_footprints_[mirror_index].name = nullptr; } } void TestPUPData::AddDiskFootprint(UwSId pup_id, int csidl, const wchar_t* path, PUPData::DiskMatchRule rule) { CHECK_EQ(this, current_test_); size_t mirror_index = EnsurePUP(pup_id); PUPData::StaticDiskFootprint footprint; footprint.csidl = csidl; footprint.path = path; footprint.rule = rule; // Insert before the null terminating entry. cpp_pup_footprints_[pup_id].disk_footprints.insert( cpp_pup_footprints_[pup_id].disk_footprints.end() - 1, footprint); mirror_pup_footprints_[mirror_index].disk_footprints = cpp_pup_footprints_[pup_id].disk_footprints.data(); } void TestPUPData::AddRegistryFootprint(UwSId pup_id, RegistryRoot registry_root, const wchar_t* key_path, const wchar_t* value_name, const wchar_t* value_substring, RegistryMatchRule rule) { CHECK_EQ(this, current_test_); size_t mirror_index = EnsurePUP(pup_id); // Sanity checks to avoid making silly mistakes in unittests. CHECK(key_path); if (rule == REGISTRY_VALUE_MATCH_KEY) { CHECK(!value_name); CHECK(!value_substring); } else if (rule == REGISTRY_VALUE_MATCH_VALUE_NAME) { CHECK(value_name); CHECK(!value_substring); } else { CHECK(value_name); CHECK(value_substring); } PUPData::StaticRegistryFootprint footprint; footprint.registry_root = registry_root; footprint.key_path = key_path; footprint.value_name = value_name; footprint.value_substring = value_substring; footprint.rule = rule; // Insert before the null terminating entry. cpp_pup_footprints_[pup_id].registry_footprints.insert( cpp_pup_footprints_[pup_id].registry_footprints.end() - 1, footprint); mirror_pup_footprints_[mirror_index].registry_footprints = cpp_pup_footprints_[pup_id].registry_footprints.data(); } TestPUPData::CPPPUP::CPPPUP() = default; TestPUPData::CPPPUP::~CPPPUP() = default; void TestPUPData::AddCustomMatcher(UwSId pup_id, PUPData::CustomMatcher matcher) { CHECK_EQ(this, current_test_); size_t mirror_index = EnsurePUP(pup_id); // Insert before the null terminating entry. cpp_pup_footprints_[pup_id].custom_matchers.insert( cpp_pup_footprints_[pup_id].custom_matchers.end() - 1, matcher); mirror_pup_footprints_[mirror_index].custom_matchers = cpp_pup_footprints_[pup_id].custom_matchers.data(); } size_t TestPUPData::EnsurePUP(UwSId pup_id) { if (mirror_pup_footprints_.empty()) { // If we are adding the first entry, we need an initial one for the null // terminating entry. mirror_pup_footprints_.push_back(kEmptyPUP); } else { for (size_t i = 0; i < mirror_pup_footprints_.size(); ++i) { if (mirror_pup_footprints_[i].id == pup_id) return i; } } // Make sure the last entry is a null terminating entry. size_t index = mirror_pup_footprints_.size() - 1; DCHECK_EQ(PUPData::kInvalidUwSId, mirror_pup_footprints_[index].id); // Set up the new value to be inserted before the null terminating entry. PUPData::UwSSignature new_pup; new_pup.id = pup_id; new_pup.flags = PUPData::FLAGS_ACTION_REMOVE; // Initialize all C++ arrays with a null terminating entry, and use their data // pointers in the C array mirror. cpp_pup_footprints_[pup_id].disk_footprints.push_back({}); new_pup.disk_footprints = cpp_pup_footprints_[pup_id].disk_footprints.data(); cpp_pup_footprints_[pup_id].registry_footprints.push_back({}); new_pup.registry_footprints = cpp_pup_footprints_[pup_id].registry_footprints.data(); cpp_pup_footprints_[pup_id].custom_matchers.push_back({}); new_pup.custom_matchers = cpp_pup_footprints_[pup_id].custom_matchers.data(); mirror_pup_footprints_.insert(mirror_pup_footprints_.end() - 1, new_pup); // Add any newly-created UwS to the cache. Don't touch anything that already // existed, since this is often called during tests that have pointers to // that UwS. PUPData::UpdateCachedUwSForTesting(); return index; } std::vector<UwSId> TestPUPData::GetUwSIds() const { std::vector<UwSId> ids; ids.reserve(mirror_pup_footprints_.size()); for (const PUPData::UwSSignature& signature : mirror_pup_footprints_) { if (signature.id != PUPData::kInvalidUwSId) ids.push_back(signature.id); } return ids; } bool TestPUPData::IsEnabledForScanning(UwSId id) const { DCHECK_NE(id, PUPData::kInvalidUwSId); for (const PUPData::UwSSignature& signature : mirror_pup_footprints_) { if (signature.id == id) return true; } return false; } bool TestPUPData::IsEnabledForCleaning(UwSId id) const { DCHECK_NE(id, PUPData::kInvalidUwSId); for (const PUPData::UwSSignature& signature : mirror_pup_footprints_) { if (signature.id == id && signature.flags & PUPData::FLAGS_ACTION_REMOVE) return true; } return false; } std::unique_ptr<PUPData::PUP> TestPUPData::CreatePUPForId(UwSId id) const { DCHECK_NE(id, PUPData::kInvalidUwSId); for (const PUPData::UwSSignature& signature : mirror_pup_footprints_) { if (signature.id == id) return std::make_unique<PUPData::PUP>(&signature); } NOTREACHED() << id << " not in TestPUPData"; return nullptr; } } // namespace chrome_cleaner
35.252174
80
0.690429
[ "vector" ]