text
stringlengths
54
60.6k
<commit_before>// // IMUOSCHandlers.cpp // IMU2OSC // // Created by Jamie Bullock on 18/05/2012. // Copyright (c) 2012 Jamie Bullock. All rights reserved. // #include <iostream> #include "osc/OscOutboundPacketStream.h" #include "ip/UdpSocket.h" //#include "IpEndpointName.h" #define OUTPUT_BUFFER_SIZE 1024 #define ADDRESS "127.0.0.1" #define PORT 7000 UdpTransmitSocket transmitSocket(IpEndpointName(ADDRESS, PORT)); //void osc_init(const char *address, unsigned int port) //{ // IpEndpointName endpointName( //} void osc_init(const char *address, unsigned int port) { UdpTransmitSocket newTransmitSocket(IpEndpointName(address, port)); transmitSocket = newTransmitSocket; } void osc_send_euler(double *euler) { char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); p << osc::BeginMessage( "/x-imu/euler" ) << (float)euler[0] << (float)euler[1] << (float)euler[2] << osc::EndMessage; transmitSocket.Send( p.Data(), p.Size() ); p.Clear(); } void osc_send_cal(double *gyro, double *accel, double *mag) { char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); p << osc::BeginMessage( "/x-imu/calibrated" ) << (float)gyro[0] << (float)gyro[1] << (float)gyro[2] << (float)accel[0] << (float)accel[1] << (float)accel[2] << (float)mag[0] << (float)mag[1] << (float)mag[2] << osc::EndMessage; transmitSocket.Send( p.Data(), p.Size() ); p.Clear(); } <commit_msg>Dynamically allocate UDP transmit socket<commit_after>// // IMUOSCHandlers.cpp // IMU2OSC // // Created by Jamie Bullock on 18/05/2012. // Copyright (c) 2012 Jamie Bullock. All rights reserved. // #include <iostream> #include "osc/OscOutboundPacketStream.h" #include "ip/UdpSocket.h" //#include "IpEndpointName.h" #define OUTPUT_BUFFER_SIZE 1024 #define ADDRESS "127.0.0.1" #define PORT 7000 UdpTransmitSocket *transmitSocket = NULL; void osc_init(const char *address, unsigned int port) { // UdpTransmitSocket newTransmitSocket(IpEndpointName(address, port)); if (transmitSocket != NULL) { delete transmitSocket; } transmitSocket = new UdpTransmitSocket(IpEndpointName(address, port)); } void osc_send_euler(double *euler) { char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); p << osc::BeginMessage( "/x-imu/euler" ) << (float)euler[0] << (float)euler[1] << (float)euler[2] << osc::EndMessage; if (transmitSocket->IsConnected()) { transmitSocket->Send( p.Data(), p.Size() ); } else { printf("No OSC connection\n"); } p.Clear(); } void osc_send_cal(double *gyro, double *accel, double *mag) { char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); p << osc::BeginMessage( "/x-imu/calibrated" ) << (float)gyro[0] << (float)gyro[1] << (float)gyro[2] << (float)accel[0] << (float)accel[1] << (float)accel[2] << (float)mag[0] << (float)mag[1] << (float)mag[2] << osc::EndMessage; if (transmitSocket->IsConnected()) { transmitSocket->Send( p.Data(), p.Size() ); } p.Clear(); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "dll/rbm.hpp" #include "dll/ocv_visualizer.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" int main(int /*argc*/, char* /*argv*/[]){ dll::rbm_desc< 28 * 28, 10*10, dll::momentum, dll::trainer<dll::pcd1_trainer_t>, dll::batch_size<50>, dll::visible<dll::unit_type::GAUSSIAN>, dll::watcher<dll::opencv_rbm_visualizer>>::rbm_t rbm; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(); mnist::normalize_dataset(dataset); rbm.train(dataset.training_images, 500, dll::init_watcher, 10); return 0; } <commit_msg>Adapt sample<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "dll/rbm.hpp" #include "dll/ocv_visualizer.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" int main(int /*argc*/, char* /*argv*/[]){ dll::rbm_desc< 28 * 28, 10*10, dll::momentum, dll::trainer<dll::pcd1_trainer_t>, dll::batch_size<50>, dll::visible<dll::unit_type::GAUSSIAN>, dll::watcher<dll::opencv_rbm_visualizer>>::rbm_t rbm; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(); mnist::normalize_dataset(dataset); rbm.train(dataset.training_images, 500); return 0; } <|endoftext|>
<commit_before>#include "cqts_engine.h" #include <QFile> #include <QDir> #include <QStringList> #include <QTextStream> #include <QDebug> CQTs_engine::CQTs_engine() { } /*****class handler*****/ /*ClassFile structure: *Class Name *lv max *datanumber *endofile */ CQTs_Class::CQTs_Class(QString classLink){ QFile file(classLink+".ClC"); int data;//data-sink for bab and ST if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ Name="error"; data=0; lmax=-1; //add an alert! } else{ int data; QTextStream in(&file); Name= in.readLine(); in >> lmax; in >> data; } } /*****utilities*****/ QStringList extensionFind(QString ext,QString dir){ QDir workDir(dir); QStringList filelist; filelist = workDir.entryList(QStringList(ext),QDir::Files | QDir::NoSymLinks); return filelist; } QStringList extensionFind(QString ext){ return extensionFind(ext,"./"); } <commit_msg>need to test constructor for classhandler<commit_after>#include "cqts_engine.h" #include <QFile> #include <QDir> #include <QStringList> #include <QTextStream> #include <QDebug> CQTs_engine::CQTs_engine() { } /*****class handler*****/ /*ClassFile structure: *Class Name *lv max *datanumber *endofile */ CQTs_Class::CQTs_Class(QString classLink){ QFile file(classLink+".ClC");//temporary int data;//data-sink for bab and ST int F=16, R=8, W=4, bab=3;//mask for ST&BAB if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ Name="error"; data=0; lmax=-1; //add an alert! } else{ int data; QTextStream in(&file); Name= in.readLine(); in >> lmax; in >> data; } fort = (data & F)/F; ref = (data & R)/R; will = (data & W)/W; fort = (data & F)/F; bab = (data & bab)/bab; } /*****utilities*****/ QStringList extensionFind(QString ext,QString dir){ QDir workDir(dir); QStringList filelist; filelist = workDir.entryList(QStringList(ext),QDir::Files | QDir::NoSymLinks); return filelist; } QStringList extensionFind(QString ext){ return extensionFind(ext,"./"); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONAL_BASE_HH #define DUNE_GDT_FUNCTIONAL_BASE_HH #include <dune/common/dynvector.hh> #include <dune/gdt/assembler/gridwalker.hh> #include <dune/gdt/assembler/local/codim0.hh> #include <dune/gdt/assembler/local/codim1.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Functional { // forward, to be used in the traits template <class ImpTraits> class AssemblableVolumeBase; template <class ImpTraits> class AssemblableVolumeBaseTraits { public: typedef typename ImpTraits::derived_type derived_type; typedef typename ImpTraits::GridViewType GridViewType; typedef typename ImpTraits::SpaceType SpaceType; typedef typename ImpTraits::VectorType VectorType; typedef typename ImpTraits::ScalarType ScalarType; }; // class AssemblableVolumeBaseTraits template <class ImpTraits> class AssemblableVolumeBase : public AssemblableFunctionalInterface<ImpTraits>, public Functor::Codim0<typename ImpTraits::GridViewType> { typedef AssemblableFunctionalInterface<ImpTraits> InterfaceType; typedef AssemblableVolumeBaseTraits<ImpTraits> Traits; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; typedef typename GridViewType::template Codim<0>::Entity EntityType; private: typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType; typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType; public: AssemblableVolumeBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view) : vector_(vector) , space_(space) , grid_view_(grid_view) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableVolumeBase(VectorType& vector, const SpaceType& space) : vector_(vector) , space_(space) , grid_view_(*(space.grid_view())) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const SpaceType& space() const { return space_; } VectorType& vector() { return vector_; } const VectorType& vector() const { return vector_; } private: virtual const LocalFunctionalType& local_functional() const = 0; public: virtual void prepare() { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional())); const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired(); const size_t max_local_size = space_.mapper().maxNumDofs(); tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0], DynamicVector<ScalarType>(max_local_size)), std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1], DynamicVector<ScalarType>(max_local_size))}; tmp_indices_ = DynamicVector<size_t>(max_local_size, 0); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) { assert(prepared_); local_assembler_->assembleLocal(space_, entity, vector_, tmp_local_vectors_, tmp_indices_); } // ... apply_local(...) void assemble() { if (!assembled_) { GridWalker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { assemble(); return vector_.dot(source); } // ... apply(...) private: VectorType& vector_; const SpaceType& space_; const GridViewType& grid_view_; std::unique_ptr<LocalAssemblerType> local_assembler_; bool prepared_; bool assembled_; std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_; DynamicVector<size_t> tmp_indices_; }; // class AssemblableVolumeBase // forward, to be used in the traits template <class ImpTraits> class AssemblableFaceBase; template <class ImpTraits> class AssemblableFaceBaseTraits { public: typedef typename ImpTraits::derived_type derived_type; typedef typename ImpTraits::GridViewType GridViewType; typedef typename ImpTraits::SpaceType SpaceType; typedef typename ImpTraits::VectorType VectorType; typedef typename ImpTraits::ScalarType ScalarType; }; // class AssemblableFaceBaseTraits template <class ImpTraits> class AssemblableFaceBase : public AssemblableFunctionalInterface<ImpTraits>, public Functor::Codim1<typename ImpTraits::GridViewType> { typedef AssemblableFunctionalInterface<AssemblableFaceBaseTraits<ImpTraits>> InterfaceType; typedef AssemblableFaceBaseTraits<ImpTraits> Traits; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::Intersection IntersectionType; private: typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType; typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType; public: AssemblableFaceBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view) : vector_(vector) , space_(space) , grid_view_(grid_view) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableFaceBase(VectorType& vector, const SpaceType& space) : vector_(vector) , space_(space) , grid_view_(*(space.grid_view())) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const SpaceType& space() const { return space_; } VectorType& vector() { assemble(); return vector_; } const VectorType& vector() const { assemble(); return vector_; } private: virtual const LocalFunctionalType& local_functional() const = 0; public: virtual void prepare() { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional())); const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired(); const size_t max_local_size = space_.mapper().maxNumDofs(); tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0], DynamicVector<ScalarType>(max_local_size)), std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1], DynamicVector<ScalarType>(max_local_size))}; tmp_indices_ = DynamicVector<size_t>(max_local_size, 0); prepared_ = true; } } // ... prepare() virtual void apply_local(const IntersectionType& intersection) { assert(prepared_); local_assembler_->assembleLocal(space_, intersection, vector_, tmp_local_vectors_, tmp_indices_); } // ... apply_local(...) void assemble() { if (!assembled_) { GridWalker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { assemble(); return vector_.dot(source); } // ... apply(...) private: VectorType& vector_; const SpaceType& space_; const GridViewType& grid_view_; std::unique_ptr<LocalAssemblerType> local_assembler_; bool prepared_; bool assembled_; std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_; DynamicVector<size_t> tmp_indices_; }; // class AssemblableFaceBase } // namespace Functional } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONAL_BASE_HH <commit_msg>[functional.base]<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONAL_BASE_HH #define DUNE_GDT_FUNCTIONAL_BASE_HH #include <dune/common/dynvector.hh> #include <dune/gdt/assembler/gridwalker.hh> #include <dune/gdt/assembler/local/codim0.hh> #include <dune/gdt/assembler/local/codim1.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Functional { // forward, to be used in the traits template <class ImpTraits> class AssemblableVolumeBase; template <class ImpTraits> class AssemblableVolumeBaseTraits { public: typedef typename ImpTraits::derived_type derived_type; typedef typename ImpTraits::GridViewType GridViewType; typedef typename ImpTraits::SpaceType SpaceType; typedef typename ImpTraits::VectorType VectorType; typedef typename ImpTraits::ScalarType ScalarType; }; // class AssemblableVolumeBaseTraits template <class ImpTraits> class AssemblableVolumeBase : public AssemblableFunctionalInterface<ImpTraits>, public Functor::Codim0<typename ImpTraits::GridViewType> { typedef AssemblableFunctionalInterface<ImpTraits> InterfaceType; typedef AssemblableVolumeBaseTraits<ImpTraits> Traits; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; typedef typename GridViewType::template Codim<0>::Entity EntityType; private: typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType; typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType; public: AssemblableVolumeBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view) : vector_(vector) , space_(space) , grid_view_(grid_view) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableVolumeBase(VectorType& vector, const SpaceType& space) : vector_(vector) , space_(space) , grid_view_(*(space.grid_view())) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const SpaceType& space() const { return space_; } VectorType& vector() { return vector_; } const VectorType& vector() const { return vector_; } private: virtual const LocalFunctionalType& local_functional() const = 0; public: virtual void prepare() { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional())); const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired(); const size_t max_local_size = space_.mapper().maxNumDofs(); tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0], DynamicVector<ScalarType>(max_local_size)), std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1], DynamicVector<ScalarType>(max_local_size))}; tmp_indices_ = DynamicVector<size_t>(max_local_size, 0); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) { assert(prepared_); local_assembler_->assembleLocal(space_, entity, vector_, tmp_local_vectors_, tmp_indices_); } // ... apply_local(...) void assemble() { if (!assembled_) { GridWalker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { assemble(); return vector_.dot(source); } // ... apply(...) private: VectorType& vector_; const SpaceType& space_; const GridViewType& grid_view_; std::unique_ptr<LocalAssemblerType> local_assembler_; bool prepared_; bool assembled_; std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_; DynamicVector<size_t> tmp_indices_; }; // class AssemblableVolumeBase // forward, to be used in the traits template <class ImpTraits> class AssemblableFaceBase; template <class ImpTraits> class AssemblableFaceBaseTraits { public: typedef typename ImpTraits::derived_type derived_type; typedef typename ImpTraits::GridViewType GridViewType; typedef typename ImpTraits::SpaceType SpaceType; typedef typename ImpTraits::VectorType VectorType; typedef typename ImpTraits::ScalarType ScalarType; }; // class AssemblableFaceBaseTraits template <class ImpTraits> class AssemblableFaceBase : public AssemblableFunctionalInterface<ImpTraits>, public Functor::Codim1<typename ImpTraits::GridViewType> { typedef AssemblableFunctionalInterface<AssemblableFaceBaseTraits<ImpTraits>> InterfaceType; typedef AssemblableFaceBaseTraits<ImpTraits> Traits; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::SpaceType SpaceType; typedef typename Traits::VectorType VectorType; typedef typename Traits::ScalarType ScalarType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::Intersection IntersectionType; private: typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType; typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType; public: AssemblableFaceBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view) : vector_(vector) , space_(space) , grid_view_(grid_view) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableFaceBase(VectorType& vector, const SpaceType& space) : vector_(vector) , space_(space) , grid_view_(*(space.grid_view())) , local_assembler_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const SpaceType& space() const { return space_; } VectorType& vector() { assemble(); return vector_; } const VectorType& vector() const { assemble(); return vector_; } private: virtual const LocalFunctionalType& local_functional() const = 0; public: virtual void prepare() { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional())); const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired(); const size_t max_local_size = space_.mapper().maxNumDofs(); tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0], DynamicVector<ScalarType>(max_local_size)), std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1], DynamicVector<ScalarType>(max_local_size))}; tmp_indices_ = DynamicVector<size_t>(max_local_size, 0); prepared_ = true; } } // ... prepare() virtual void apply_local(const IntersectionType& intersection) { assert(prepared_); assert(local_assembler_); local_assembler_->assembleLocal(space_, intersection, vector_, tmp_local_vectors_, tmp_indices_); } // ... apply_local(...) void assemble() { if (!assembled_) { GridWalker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() template <class S> ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const { assemble(); return vector_.dot(source); } // ... apply(...) private: VectorType& vector_; const SpaceType& space_; const GridViewType& grid_view_; std::unique_ptr<LocalAssemblerType> local_assembler_; bool prepared_; bool assembled_; std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_; DynamicVector<size_t> tmp_indices_; }; // class AssemblableFaceBase } // namespace Functional } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONAL_BASE_HH <|endoftext|>
<commit_before>/** * @file PathTest.cpp * @brief Path class tester. * @author zer0 * @date 2016-04-07 */ #include <gtest/gtest.h> #include <libtbag/filesystem/Path.hpp> using namespace libtbag; using namespace libtbag::filesystem; TEST(PathStaticTest, StyleChecker) { #if defined(WIN32) || defined(_WIN32) ASSERT_TRUE(Path::isWindowsStyle()); ASSERT_FALSE(Path::isPosixStyle()); #else ASSERT_FALSE(Path::isWindowsStyle()); ASSERT_TRUE(Path::isPosixStyle()); #endif } TEST(PathStaticTest, Constructors) { char const * const TEMP = "TEMP"; Path p0; Path p1 = Path(TEMP); Path p2 = Path(std::string(TEMP)); Path p3 = Path(TEMP, Path::update_generic()); Path p4 = Path(std::string(TEMP), Path::update_generic()); Path p5 = p1; Path p6_move = Path(TEMP); Path p6 = std::move(p6_move); ASSERT_STREQ(p0.getString().c_str(), ""); ASSERT_STREQ(p1.getString().c_str(), TEMP); ASSERT_STREQ(p2.getString().c_str(), TEMP); ASSERT_STREQ(p3.getString().c_str(), TEMP); ASSERT_STREQ(p4.getString().c_str(), TEMP); ASSERT_STREQ(p5.getString().c_str(), TEMP); ASSERT_STREQ(p6.getString().c_str(), TEMP); } TEST(PathStaticTest, initializer_list) { Path p0 = {"/", "TE", "M", "P"}; ASSERT_EQ(p0.getString(), Path::BaseString("/TE/M/P")); } TEST(PathStaticTest, AssignOperators) { char const * const TEMP = "TEMP"; auto rvalue_test = [&]() -> Path { return Path(TEMP); }; Path const TEMP_PATH = Path(TEMP); std::string const TEMP_STRING = TEMP; ASSERT_STREQ(TEMP_PATH.getString().c_str(), TEMP); Path p0; p0.setString(""); p0 = TEMP; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0.setString(""); p0 = TEMP_STRING; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0.setString(""); p0 = std::string(TEMP); ASSERT_STREQ(p0.getString().c_str(), TEMP); p0.setString(""); p0 = TEMP_PATH; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0.setString(""); p0 = rvalue_test(); ASSERT_STREQ(p0.getString().c_str(), TEMP); } TEST(PathStaticTest, isProhibitedFilename) { std::string const FILENAME1 = "TEMP"; ASSERT_FALSE(Path::isProhibitedFilenameOfWindows(FILENAME1)); ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME1)); std::string const FILENAME2 = "TE\\MP"; ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME2)); ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME2)); std::string const FILENAME3 = "TE/MP"; ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME3)); ASSERT_TRUE(Path::isProhibitedFilenameOfPosix(FILENAME3)); } TEST(PathStaticTest, removeLastSeparator) { std::string const PREFIX = "\\/TE/\\MP"; std::string const WINDOWS_SUFFIX = "\\\\"; std::string const TEMP = PREFIX + WINDOWS_SUFFIX + "//"; Path::BaseString windows = Path::removeLastSeparatorOfWindows(TEMP); Path::BaseString posix = Path::removeLastSeparatorOfPosix(TEMP); ASSERT_EQ(windows, PREFIX); ASSERT_EQ(posix, PREFIX + WINDOWS_SUFFIX); } TEST(PathStaticTest, replaceHomeDirectoryShortcut_1) { std::string const HOME = Common::getHomeDir(); std::string const TEMP = "~"; ASSERT_EQ(Path::replaceHomeDirectoryShortcut(TEMP), HOME); } TEST(PathStaticTest, replaceHomeDirectoryShortcut_2) { std::string const HOME = Common::getHomeDir(); std::string const TEMP = "TEMP"; std::string const TEST = std::string("~/") + TEMP; Path p1 = Path(Path::replaceHomeDirectoryShortcut(TEMP), Path::update_generic()); Path p2 = Path(Common::getHomeDir(), Path::update_generic()); p2.append(TEMP); ASSERT_EQ(p2.getNative(), p2.getNative()); } // Fixture. class PathTest : public ::testing::Test { public: std::string ws; std::string ps; std::string gs; std::string s; std::string depth0; std::string depth1; std::string depth2; std::string depth3; std::string depth4; std::string depth5; std::string test_path; std::string windows_path; std::string posix_path; std::string generic_path; std::string canonical_path; Path path; public: PathTest() { ws = PATH_SEPARATOR_STRING_OF_WINDOWS; ps = PATH_SEPARATOR_STRING_OF_POSIX; gs = GetGenericPathSeparatorString(); s = GetPathSeparatorString(); } virtual ~PathTest() { __EMPTY_BLOCK__ } public: virtual void SetUp() override { __EMPTY_BLOCK__ } virtual void TearDown() override { __EMPTY_BLOCK__ } public: void setupOfWindows() { depth0 = "O:"; depth1 = "Temp"; depth2 = "Directory"; depth3 = ".."; depth4 = "."; depth5 = "File.tmp"; test_path = R"(O:\\Temp\Directory/..\.//\\/File.tmp\/)"; windows_path = R"(O:\Temp\File.tmp)"; posix_path = R"(O:/Temp/Directory/.././File.tmp)"; generic_path = R"(O:/Temp/Directory/.././File.tmp)"; canonical_path = R"(O:/Temp/File.tmp)"; path = Path(test_path); } void setupOfPosix() { depth0 = "/"; depth1 = "Temp"; depth2 = "\\Directory"; depth3 = ".."; depth4 = "."; depth5 = "File.tmp"; test_path = R"(/Temp/\Directory/.././////File.tmp//)"; windows_path = R"(/Temp/File.tmp)"; posix_path = R"(/Temp/\Directory/.././File.tmp)"; generic_path = R"(/Temp/\Directory/.././File.tmp)"; canonical_path = R"(/Temp/File.tmp)"; path = Path(test_path); } }; TEST_F(PathTest, getGeneric) { setupOfWindows(); ASSERT_EQ(Path::getGenericOfWindows(test_path), generic_path); setupOfPosix(); ASSERT_EQ(Path::getGenericOfPosix(test_path), generic_path); } TEST_F(PathTest, getNative) { #if defined(WIN32) || defined(_WIN32) setupOfWindows(); ASSERT_EQ(path.getNative(), windows_path); #else setupOfPosix(); ASSERT_EQ(path.getNative(), posix_path); #endif } TEST_F(PathTest, getRootDir) { setupOfWindows(); ASSERT_EQ(Path::getRootDirOfWindows(test_path), depth0); setupOfPosix(); ASSERT_EQ(Path::getRootDirOfPosix(test_path), depth0); } TEST_F(PathTest, isAbsolute) { setupOfWindows(); ASSERT_TRUE(Path::isAbsoluteOfWindows(test_path)); ASSERT_FALSE(Path::isAbsoluteOfPosix(test_path)); setupOfPosix(); ASSERT_TRUE(Path::isAbsoluteOfPosix(test_path)); ASSERT_FALSE(Path::isAbsoluteOfWindows(test_path)); } TEST_F(PathTest, append) { Path p0; p0.append(depth0); p0.append(depth1, Path::BaseString(GetGenericPathSeparatorString())); p0 /= depth2; p0 += depth3; p0.append(depth4); p0.append(depth5); ASSERT_EQ(p0.getGeneric(), generic_path); p0 = ""; p0.append("/"); ASSERT_EQ(p0.getString(), Path::BaseString("/")); } TEST_F(PathTest, getParentOfWindows) { setupOfWindows(); Path::BaseString test1 = Path::getParentOfWindows(test_path); Path::BaseString test2 = R"(O:\\Temp\Directory/..\.//\\)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp\Directory/..)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp\Directory)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = ""; ASSERT_EQ(test1, test2); // OTHER. test1 = Path::getParentOfWindows("TEST_PATH"); test2 = ""; ASSERT_EQ(test1, test2); } TEST_F(PathTest, getParentOfPosix) { setupOfPosix(); Path::BaseString test1 = Path::getParentOfPosix(test_path); Path::BaseString test2 = R"(/Temp/\Directory/.././///)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp/\Directory/..)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp/\Directory)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = "/"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = ""; ASSERT_EQ(test1, test2); // OTHER. test1 = Path::getParentOfPosix("TEST_PATH"); test2 = ""; ASSERT_EQ(test1, test2); } TEST_F(PathTest, splitNodes) { setupOfWindows(); Path::Nodes nodes = Path::splitNodesOfWindows(test_path); ASSERT_EQ(nodes.size(), 6U); ASSERT_EQ(nodes[0], depth0); ASSERT_EQ(nodes[1], depth1); ASSERT_EQ(nodes[2], depth2); ASSERT_EQ(nodes[3], depth3); ASSERT_EQ(nodes[4], depth4); ASSERT_EQ(nodes[5], depth5); setupOfPosix(); nodes = Path::splitNodesOfPosix(test_path); ASSERT_EQ(nodes.size(), 6U); ASSERT_EQ(nodes[0], depth0); ASSERT_EQ(nodes[1], depth1); ASSERT_EQ(nodes[2], depth2); ASSERT_EQ(nodes[3], depth3); ASSERT_EQ(nodes[4], depth4); ASSERT_EQ(nodes[5], depth5); } <commit_msg>Code refactoring.<commit_after>/** * @file PathTest.cpp * @brief Path class tester. * @author zer0 * @date 2016-04-07 */ #include <gtest/gtest.h> #include <libtbag/filesystem/Path.hpp> using namespace libtbag; using namespace libtbag::filesystem; TEST(PathStaticTest, StyleChecker) { #if defined(WIN32) || defined(_WIN32) ASSERT_TRUE(Path::isWindowsStyle()); ASSERT_FALSE(Path::isPosixStyle()); #else ASSERT_FALSE(Path::isWindowsStyle()); ASSERT_TRUE(Path::isPosixStyle()); #endif } TEST(PathStaticTest, Constructors) { char const * const TEMP = "TEMP"; Path p0; Path p1 = Path(TEMP); Path p2 = Path(std::string(TEMP)); Path p3 = Path(TEMP, Path::update_generic()); Path p4 = Path(std::string(TEMP), Path::update_generic()); Path p5 = p1; Path p6_move = Path(TEMP); Path p6 = std::move(p6_move); ASSERT_STREQ(p0.getString().c_str(), ""); ASSERT_STREQ(p1.getString().c_str(), TEMP); ASSERT_STREQ(p2.getString().c_str(), TEMP); ASSERT_STREQ(p3.getString().c_str(), TEMP); ASSERT_STREQ(p4.getString().c_str(), TEMP); ASSERT_STREQ(p5.getString().c_str(), TEMP); ASSERT_STREQ(p6.getString().c_str(), TEMP); } TEST(PathStaticTest, initializer_list) { Path p0 = {"/", "TE", "M", "P"}; ASSERT_EQ(p0.getString(), Path::BaseString("/TE/M/P")); } TEST(PathStaticTest, AssignOperators) { char const * const TEMP = "TEMP"; auto rvalue_test = [&]() -> Path { return Path(TEMP); }; Path const TEMP_PATH = Path(TEMP); std::string const TEMP_STRING = TEMP; ASSERT_STREQ(TEMP_PATH.getString().c_str(), TEMP); Path p0; p0 = TEMP; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0 = TEMP_STRING; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0 = std::string(TEMP); ASSERT_STREQ(p0.getString().c_str(), TEMP); p0 = TEMP_PATH; ASSERT_STREQ(p0.getString().c_str(), TEMP); p0 = rvalue_test(); ASSERT_STREQ(p0.getString().c_str(), TEMP); } TEST(PathStaticTest, isProhibitedFilename) { std::string const FILENAME1 = "TEMP"; ASSERT_FALSE(Path::isProhibitedFilenameOfWindows(FILENAME1)); ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME1)); std::string const FILENAME2 = "TE\\MP"; ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME2)); ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME2)); std::string const FILENAME3 = "TE/MP"; ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME3)); ASSERT_TRUE(Path::isProhibitedFilenameOfPosix(FILENAME3)); } TEST(PathStaticTest, removeLastSeparator) { std::string const PREFIX = "\\/TE/\\MP"; std::string const WINDOWS_SUFFIX = "\\\\"; std::string const TEMP = PREFIX + WINDOWS_SUFFIX + "//"; Path::BaseString windows = Path::removeLastSeparatorOfWindows(TEMP); Path::BaseString posix = Path::removeLastSeparatorOfPosix(TEMP); ASSERT_EQ(windows, PREFIX); ASSERT_EQ(posix, PREFIX + WINDOWS_SUFFIX); } TEST(PathStaticTest, replaceHomeDirectoryShortcut_1) { std::string const HOME = Common::getHomeDir(); std::string const TEMP = "~"; ASSERT_EQ(Path::replaceHomeDirectoryShortcut(TEMP), HOME); } TEST(PathStaticTest, replaceHomeDirectoryShortcut_2) { std::string const HOME = Common::getHomeDir(); std::string const TEMP = "TEMP"; std::string const TEST = std::string("~/") + TEMP; Path p1 = Path(Path::replaceHomeDirectoryShortcut(TEMP), Path::update_generic()); Path p2 = Path(Common::getHomeDir(), Path::update_generic()); p2.append(TEMP); ASSERT_EQ(p2.getNative(), p2.getNative()); } // Fixture. class PathTest : public ::testing::Test { public: std::string ws; std::string ps; std::string gs; std::string s; std::string depth0; std::string depth1; std::string depth2; std::string depth3; std::string depth4; std::string depth5; std::string test_path; std::string windows_path; std::string posix_path; std::string generic_path; std::string canonical_path; Path path; public: PathTest() { ws = PATH_SEPARATOR_STRING_OF_WINDOWS; ps = PATH_SEPARATOR_STRING_OF_POSIX; gs = GetGenericPathSeparatorString(); s = GetPathSeparatorString(); } virtual ~PathTest() { __EMPTY_BLOCK__ } public: virtual void SetUp() override { __EMPTY_BLOCK__ } virtual void TearDown() override { __EMPTY_BLOCK__ } public: void setupOfWindows() { depth0 = "O:"; depth1 = "Temp"; depth2 = "Directory"; depth3 = ".."; depth4 = "."; depth5 = "File.tmp"; test_path = R"(O:\\Temp\Directory/..\.//\\/File.tmp\/)"; windows_path = R"(O:\Temp\File.tmp)"; posix_path = R"(O:/Temp/Directory/.././File.tmp)"; generic_path = R"(O:/Temp/Directory/.././File.tmp)"; canonical_path = R"(O:/Temp/File.tmp)"; path = Path(test_path); } void setupOfPosix() { depth0 = "/"; depth1 = "Temp"; depth2 = "\\Directory"; depth3 = ".."; depth4 = "."; depth5 = "File.tmp"; test_path = R"(/Temp/\Directory/.././////File.tmp//)"; windows_path = R"(/Temp/File.tmp)"; posix_path = R"(/Temp/\Directory/.././File.tmp)"; generic_path = R"(/Temp/\Directory/.././File.tmp)"; canonical_path = R"(/Temp/File.tmp)"; path = Path(test_path); } }; TEST_F(PathTest, getGeneric) { setupOfWindows(); ASSERT_EQ(Path::getGenericOfWindows(test_path), generic_path); setupOfPosix(); ASSERT_EQ(Path::getGenericOfPosix(test_path), generic_path); } TEST_F(PathTest, getNative) { #if defined(WIN32) || defined(_WIN32) setupOfWindows(); ASSERT_EQ(path.getNative(), windows_path); #else setupOfPosix(); ASSERT_EQ(path.getNative(), posix_path); #endif } TEST_F(PathTest, getRootDir) { setupOfWindows(); ASSERT_EQ(Path::getRootDirOfWindows(test_path), depth0); setupOfPosix(); ASSERT_EQ(Path::getRootDirOfPosix(test_path), depth0); } TEST_F(PathTest, isAbsolute) { setupOfWindows(); ASSERT_TRUE(Path::isAbsoluteOfWindows(test_path)); ASSERT_FALSE(Path::isAbsoluteOfPosix(test_path)); setupOfPosix(); ASSERT_TRUE(Path::isAbsoluteOfPosix(test_path)); ASSERT_FALSE(Path::isAbsoluteOfWindows(test_path)); } TEST_F(PathTest, append) { Path p0; p0.append(depth0); p0.append(depth1, Path::BaseString(GetGenericPathSeparatorString())); p0 /= depth2; p0 += depth3; p0.append(depth4); p0.append(depth5); ASSERT_EQ(p0.getGeneric(), generic_path); p0 = ""; p0.append("/"); ASSERT_EQ(p0.getString(), Path::BaseString("/")); } TEST_F(PathTest, getParentOfWindows) { setupOfWindows(); Path::BaseString test1 = Path::getParentOfWindows(test_path); Path::BaseString test2 = R"(O:\\Temp\Directory/..\.//\\)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp\Directory/..)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp\Directory)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\\Temp)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = R"(O:\)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfWindows(test1); test2 = ""; ASSERT_EQ(test1, test2); // OTHER. test1 = Path::getParentOfWindows("TEST_PATH"); test2 = ""; ASSERT_EQ(test1, test2); } TEST_F(PathTest, getParentOfPosix) { setupOfPosix(); Path::BaseString test1 = Path::getParentOfPosix(test_path); Path::BaseString test2 = R"(/Temp/\Directory/.././///)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp/\Directory/..)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp/\Directory)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = R"(/Temp)"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = "/"; ASSERT_EQ(test1, test2); test1 = Path::getParentOfPosix(test1); test2 = ""; ASSERT_EQ(test1, test2); // OTHER. test1 = Path::getParentOfPosix("TEST_PATH"); test2 = ""; ASSERT_EQ(test1, test2); } TEST_F(PathTest, splitNodesOfWindows) { setupOfWindows(); Path::Nodes nodes = Path::splitNodesOfWindows(test_path); ASSERT_EQ(nodes.size(), 6U); ASSERT_EQ(nodes[0], depth0); ASSERT_EQ(nodes[1], depth1); ASSERT_EQ(nodes[2], depth2); ASSERT_EQ(nodes[3], depth3); ASSERT_EQ(nodes[4], depth4); ASSERT_EQ(nodes[5], depth5); } TEST_F(PathTest, splitNodesOfPosix) { setupOfPosix(); Path::Nodes nodes = Path::splitNodesOfPosix(test_path); ASSERT_EQ(nodes.size(), 6U); ASSERT_EQ(nodes[0], depth0); ASSERT_EQ(nodes[1], depth1); ASSERT_EQ(nodes[2], depth2); ASSERT_EQ(nodes[3], depth3); ASSERT_EQ(nodes[4], depth4); ASSERT_EQ(nodes[5], depth5); } <|endoftext|>
<commit_before> // CopyBlocks.cpp // Implements the test for cChunkData::CopyBlockTypes() range copying #include "Globals.h" #include "ChunkData.h" int main(int argc, char ** argv) { // Set up a cChunkData with known contents - all blocks 0x01, all metas 0x02: cChunkData Data; cChunkDef::BlockTypes BlockTypes; cChunkDef::BlockNibbles BlockMetas; memset(BlockTypes, 0x01, sizeof(BlockTypes)); memset(BlockMetas, 0x02, sizeof(BlockMetas)); Data.SetBlockTypes(BlockTypes); Data.SetMetas(BlockMetas); // Try to read varying amounts of blocktypes from the cChunkData. // Verify that the exact amount of memory is copied, by copying to a larger buffer and checking its boundaries BLOCKTYPE TestBuffer[5 * cChunkDef::NumBlocks]; size_t WritePosIdx = 2 * cChunkDef::NumBlocks; BLOCKTYPE * WritePosition = &TestBuffer[WritePosIdx]; for (size_t idx = 0; idx < 5000; idx++) { for (size_t len = 1; len < 1000; len += 15) { //printf("Testing copying %u blocks from index %u\n", (unsigned)len, (unsigned)idx); //initalize buffer memset(TestBuffer, 0x03, sizeof(TestBuffer)); Data.CopyBlockTypes(WritePosition, idx, len); // Verify the data copied: for (size_t i = 0; i < len; i++) { assert_test(WritePosition[i] == 0x01); } // Verify the space before the copied data hasn't been changed: for (size_t i = 0; i < WritePosIdx; i++) { assert_test(TestBuffer[i] == 0x03); } // Verify the space after the copied data hasn't been changed: for (size_t i = WritePosIdx + idx + len; i < ARRAYCOUNT(TestBuffer); i++) { assert_test(TestBuffer[i] == 0x03); } } } // for idx return 0; } <commit_msg>Reduced the number of cChunkData::CopyBlockTypes() tests, added progress.<commit_after> // CopyBlocks.cpp // Implements the test for cChunkData::CopyBlockTypes() range copying #include "Globals.h" #include "ChunkData.h" int main(int argc, char ** argv) { // Set up a cChunkData with known contents - all blocks 0x01, all metas 0x02: cChunkData Data; cChunkDef::BlockTypes BlockTypes; cChunkDef::BlockNibbles BlockMetas; memset(BlockTypes, 0x01, sizeof(BlockTypes)); memset(BlockMetas, 0x02, sizeof(BlockMetas)); Data.SetBlockTypes(BlockTypes); Data.SetMetas(BlockMetas); // Try to read varying amounts of blocktypes from the cChunkData. // Verify that the exact amount of memory is copied, by copying to a larger buffer and checking its boundaries BLOCKTYPE TestBuffer[5 * cChunkDef::NumBlocks]; size_t WritePosIdx = 2 * cChunkDef::NumBlocks; BLOCKTYPE * WritePosition = &TestBuffer[WritePosIdx]; memset(TestBuffer, 0x03, sizeof(TestBuffer)); size_t LastReportedStep = 1; for (size_t idx = 0; idx < 5000; idx += 7) { if (idx / 500 != LastReportedStep) { printf("Testing index %u...\n", (unsigned)idx); LastReportedStep = idx / 500; } for (size_t len = 3; len < 1000; len += 13) { Data.CopyBlockTypes(WritePosition, idx, len); // Verify the data copied: for (size_t i = 0; i < len; i++) { assert_test(WritePosition[i] == 0x01); } // Verify the space before the copied data hasn't been changed: for (size_t i = 0; i < WritePosIdx; i++) { assert_test(TestBuffer[i] == 0x03); } // Verify the space after the copied data hasn't been changed: for (size_t i = WritePosIdx + idx + len; i < ARRAYCOUNT(TestBuffer); i++) { assert_test(TestBuffer[i] == 0x03); } // Re-initialize the buffer for the next test: for (size_t i = 0; i < len; i++) { WritePosition[i] = 0x03; } } // for len } // for idx return 0; } <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkHalf.h" #include "SkRasterPipeline.h" DEF_TEST(SkRasterPipeline, r) { // Build and run a simple pipeline to exercise SkRasterPipeline, // drawing 50% transparent blue over opaque red in half-floats. Sk4h red = SkFloatToHalf_finite_ftz({ 1.0f, 0.0f, 0.0f, 1.0f }), blue = SkFloatToHalf_finite_ftz({ 0.0f, 0.0f, 0.5f, 0.5f }), result; SkRasterPipeline p; p.append(SkRasterPipeline::load_s_f16, &blue); p.append(SkRasterPipeline::load_d_f16, &red); p.append(SkRasterPipeline::srcover); p.append(SkRasterPipeline::store_f16, &result); p.run(1); Sk4f f = SkHalfToFloat_finite_ftz(result); // We should see half-intensity magenta. #if !defined(SK_BUILD_FOR_MAC) REPORTER_ASSERT(r, f[0] == 0.5f); REPORTER_ASSERT(r, f[1] == 0.0f); REPORTER_ASSERT(r, f[2] == 0.5f); REPORTER_ASSERT(r, f[3] == 1.0f); #else SkDebugf("SkRasterPipeline test: %g %g %g %g\n", f[0], f[1], f[2], f[3]); #endif } DEF_TEST(SkRasterPipeline_empty, r) { // No asserts... just a test that this is safe to run. SkRasterPipeline p; p.run(20); } DEF_TEST(SkRasterPipeline_nonsense, r) { // No asserts... just a test that this is safe to run and terminates. // srcover() calls st->next(); this makes sure we've always got something there to call. SkRasterPipeline p; p.append(SkRasterPipeline::srcover); p.run(20); } <commit_msg>Revert "Debug Mac test failure."<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkHalf.h" #include "SkRasterPipeline.h" DEF_TEST(SkRasterPipeline, r) { // Build and run a simple pipeline to exercise SkRasterPipeline, // drawing 50% transparent blue over opaque red in half-floats. Sk4h red = SkFloatToHalf_finite_ftz({ 1.0f, 0.0f, 0.0f, 1.0f }), blue = SkFloatToHalf_finite_ftz({ 0.0f, 0.0f, 0.5f, 0.5f }), result; SkRasterPipeline p; p.append(SkRasterPipeline::load_s_f16, &blue); p.append(SkRasterPipeline::load_d_f16, &red); p.append(SkRasterPipeline::srcover); p.append(SkRasterPipeline::store_f16, &result); p.run(1); Sk4f f = SkHalfToFloat_finite_ftz(result); // We should see half-intensity magenta. REPORTER_ASSERT(r, f[0] == 0.5f); REPORTER_ASSERT(r, f[1] == 0.0f); REPORTER_ASSERT(r, f[2] == 0.5f); REPORTER_ASSERT(r, f[3] == 1.0f); } DEF_TEST(SkRasterPipeline_empty, r) { // No asserts... just a test that this is safe to run. SkRasterPipeline p; p.run(20); } DEF_TEST(SkRasterPipeline_nonsense, r) { // No asserts... just a test that this is safe to run and terminates. // srcover() calls st->next(); this makes sure we've always got something there to call. SkRasterPipeline p; p.append(SkRasterPipeline::srcover); p.run(20); } <|endoftext|>
<commit_before>/* network.cpp * * Kubo Ryosuke */ #include "network/CsaClient.h" #include <fstream> using namespace sunfish; int network() { // logger settings std::ofstream fout("network.log", std::ios::out); if (fout) { Loggers::send.addStream(fout); Loggers::receive.addStream(fout); } Loggers::error.addStream(std::cerr, "\x1b[31m", "\x1b[39m"); Loggers::warning.addStream(std::cerr, "\x1b[33m", "\x1b[39m"); Loggers::message.addStream(std::cerr, "\x1b[32m", "\x1b[39m"); Loggers::send.addStream(std::cerr, true, true, "\x1b[34m", "\x1b[39m"); Loggers::receive.addStream(std::cerr, true, true, "\x1b[35m", "\x1b[39m"); #ifndef NDEBUG Loggers::debug.addStream(std::cerr, "\x1b[36m", "\x1b[39m"); Loggers::develop.addStream(std::cerr, "\x1b[37m", "\x1b[39m"); #endif // NDEBUG CsaClient csaClient; csaClient.execute(); return 0; } <commit_msg>Change message color<commit_after>/* network.cpp * * Kubo Ryosuke */ #include "network/CsaClient.h" #include <fstream> using namespace sunfish; int network() { // logger settings std::ofstream fout("network.log", std::ios::out); if (fout) { Loggers::send.addStream(fout); Loggers::receive.addStream(fout); } Loggers::error.addStream(std::cerr, "\x1b[31m", "\x1b[39m"); Loggers::warning.addStream(std::cerr, "\x1b[33m", "\x1b[39m"); Loggers::message.addStream(std::cerr/*, "\x1b[32m", "\x1b[39m"*/); Loggers::send.addStream(std::cerr, true, true, "\x1b[34m", "\x1b[39m"); Loggers::receive.addStream(std::cerr, true, true, "\x1b[35m", "\x1b[39m"); #ifndef NDEBUG Loggers::debug.addStream(std::cerr, "\x1b[36m", "\x1b[39m"); Loggers::develop.addStream(std::cerr, "\x1b[37m", "\x1b[39m"); #endif // NDEBUG CsaClient csaClient; csaClient.execute(); return 0; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "dirtab.h" #include <cerrno> #include <cstdio> #include <cstdlib> #include "util.h" namespace catalog { Dirtab::Dirtab() : valid_(true) {} bool Dirtab::Open(const std::string &dirtab_path) { if (!FileExists(dirtab_path)) { LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'", dirtab_path.c_str()); valid_ = false; return valid_; } FILE *dirtab_file = fopen(dirtab_path.c_str(), "r"); if (dirtab_file == NULL) { LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s' " "(errno: %d)", dirtab_path.c_str(), errno); valid_ = false; return valid_; } valid_ = Parse(dirtab_file); fclose(dirtab_file); return valid_; } bool Dirtab::Parse(const std::string &dirtab) { valid_ = true; off_t line_offset = 0; while (line_offset < static_cast<off_t>(dirtab.size())) { std::string line = GetLineMem(dirtab.c_str() + line_offset, dirtab.size() - line_offset); line_offset += line.size() + 1; // +1 == skipped \n if (!ParseLine(line)) { valid_ = false; } } valid_ = valid_ && CheckRuleValidity(); return valid_; } bool Dirtab::Parse(FILE *dirtab_file) { valid_ = true; std::string line; while (GetLineFile(dirtab_file, &line)) { if (!ParseLine(line)) { valid_ = false; } } valid_ = valid_ && CheckRuleValidity(); return valid_; } bool Dirtab::ParseLine(const std::string &line) { // line parsing is done using std::string iterators. Each parsing method ex- // pects an iterator and the end iterator. While parsing itr is constantly // incremented to walk through the given .cvmfsdirtab line. std::string::const_iterator itr = line.begin(); const std::string::const_iterator iend = line.end(); bool negation = false; // parse preamble SkipWhitespace(iend, &itr); if (*itr == Dirtab::kCommentMarker) { return true; } else if (*itr == Dirtab::kNegationMarker) { negation = true; ++itr; SkipWhitespace(iend, &itr); } // extract and parse pathspec std::string pathspec_str(itr, iend); return this->ParsePathspec(pathspec_str, negation); } bool Dirtab::ParsePathspec(const std::string &pathspec_str, bool negation) { if (pathspec_str.empty()) { return true; } Pathspec pathspec(pathspec_str); // all generated Pathspecs need to be valid and positive rules must be // absolute. Otherwise the .cvmfsdirtab is not valid. if ( !pathspec.IsValid() || (!negation && !pathspec.IsAbsolute())) { return false; } // create a new dirtab rule const Rule rule(pathspec, negation); AddRule(rule); return true; } void Dirtab::AddRule(const Rule &rule) { if (rule.is_negation) { negative_rules_.push_back(rule); } else { positive_rules_.push_back(rule); } } bool Dirtab::CheckRuleValidity() const { // check if there are contradicting positive and negative rules Rules::const_iterator p = positive_rules_.begin(); const Rules::const_iterator pend = positive_rules_.end(); for (; p != pend; ++p) { assert(!p->is_negation); Rules::const_iterator n = negative_rules_.begin(); const Rules::const_iterator nend = negative_rules_.end(); for (; n != nend; ++n) { assert(n->is_negation); if (p->pathspec == n->pathspec) { return false; } } } return true; } bool Dirtab::IsMatching(const std::string &path) const { // check if path has a positive match bool has_positive_match = false; Rules::const_iterator p = positive_rules_.begin(); const Rules::const_iterator pend = positive_rules_.end(); for (; p != pend; ++p) { assert(!p->is_negation); if (p->pathspec.IsMatching(path)) { has_positive_match = true; break; } } return has_positive_match && !IsOpposing(path); } bool Dirtab::IsOpposing(const std::string &path) const { Rules::const_iterator n = negative_rules_.begin(); const Rules::const_iterator nend = negative_rules_.end(); for (; n != nend; ++n) { assert(n->is_negation); if (n->pathspec.IsMatchingRelaxed(path)) { return true; } } return false; } bool RelaxedPathFilter::ParsePathspec(const std::string &pathspec_str, bool negation) { if (negation) { return Dirtab::ParsePathspec(pathspec_str, true); } bool success = true; std::string current_pathspec_str = pathspec_str; while (current_pathspec_str.length() > 0) { if (!Dirtab::ParsePathspec(current_pathspec_str, false)) success = false; int new_length = current_pathspec_str.find_last_of("/"); current_pathspec_str = current_pathspec_str.substr(0, new_length); } return success; } } // namespace catalog <commit_msg>FIX: return type in dirt.cc<commit_after>/** * This file is part of the CernVM File System. */ #include "dirtab.h" #include <cerrno> #include <cstdio> #include <cstdlib> #include "util.h" namespace catalog { Dirtab::Dirtab() : valid_(true) {} bool Dirtab::Open(const std::string &dirtab_path) { if (!FileExists(dirtab_path)) { LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'", dirtab_path.c_str()); valid_ = false; return valid_; } FILE *dirtab_file = fopen(dirtab_path.c_str(), "r"); if (dirtab_file == NULL) { LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s' " "(errno: %d)", dirtab_path.c_str(), errno); valid_ = false; return valid_; } valid_ = Parse(dirtab_file); fclose(dirtab_file); return valid_; } bool Dirtab::Parse(const std::string &dirtab) { valid_ = true; off_t line_offset = 0; while (line_offset < static_cast<off_t>(dirtab.size())) { std::string line = GetLineMem(dirtab.c_str() + line_offset, dirtab.size() - line_offset); line_offset += line.size() + 1; // +1 == skipped \n if (!ParseLine(line)) { valid_ = false; } } valid_ = valid_ && CheckRuleValidity(); return valid_; } bool Dirtab::Parse(FILE *dirtab_file) { valid_ = true; std::string line; while (GetLineFile(dirtab_file, &line)) { if (!ParseLine(line)) { valid_ = false; } } valid_ = valid_ && CheckRuleValidity(); return valid_; } bool Dirtab::ParseLine(const std::string &line) { // line parsing is done using std::string iterators. Each parsing method ex- // pects an iterator and the end iterator. While parsing itr is constantly // incremented to walk through the given .cvmfsdirtab line. std::string::const_iterator itr = line.begin(); const std::string::const_iterator iend = line.end(); bool negation = false; // parse preamble SkipWhitespace(iend, &itr); if (*itr == Dirtab::kCommentMarker) { return true; } else if (*itr == Dirtab::kNegationMarker) { negation = true; ++itr; SkipWhitespace(iend, &itr); } // extract and parse pathspec std::string pathspec_str(itr, iend); return this->ParsePathspec(pathspec_str, negation); } bool Dirtab::ParsePathspec(const std::string &pathspec_str, bool negation) { if (pathspec_str.empty()) { return true; } Pathspec pathspec(pathspec_str); // all generated Pathspecs need to be valid and positive rules must be // absolute. Otherwise the .cvmfsdirtab is not valid. if ( !pathspec.IsValid() || (!negation && !pathspec.IsAbsolute())) { return false; } // create a new dirtab rule const Rule rule(pathspec, negation); AddRule(rule); return true; } void Dirtab::AddRule(const Rule &rule) { if (rule.is_negation) { negative_rules_.push_back(rule); } else { positive_rules_.push_back(rule); } } bool Dirtab::CheckRuleValidity() const { // check if there are contradicting positive and negative rules Rules::const_iterator p = positive_rules_.begin(); const Rules::const_iterator pend = positive_rules_.end(); for (; p != pend; ++p) { assert(!p->is_negation); Rules::const_iterator n = negative_rules_.begin(); const Rules::const_iterator nend = negative_rules_.end(); for (; n != nend; ++n) { assert(n->is_negation); if (p->pathspec == n->pathspec) { return false; } } } return true; } bool Dirtab::IsMatching(const std::string &path) const { // check if path has a positive match bool has_positive_match = false; Rules::const_iterator p = positive_rules_.begin(); const Rules::const_iterator pend = positive_rules_.end(); for (; p != pend; ++p) { assert(!p->is_negation); if (p->pathspec.IsMatching(path)) { has_positive_match = true; break; } } return has_positive_match && !IsOpposing(path); } bool Dirtab::IsOpposing(const std::string &path) const { Rules::const_iterator n = negative_rules_.begin(); const Rules::const_iterator nend = negative_rules_.end(); for (; n != nend; ++n) { assert(n->is_negation); if (n->pathspec.IsMatchingRelaxed(path)) { return true; } } return false; } bool RelaxedPathFilter::ParsePathspec(const std::string &pathspec_str, bool negation) { if (negation) { return Dirtab::ParsePathspec(pathspec_str, true); } bool success = true; std::string current_pathspec_str = pathspec_str; while (current_pathspec_str.length() > 0) { if (!Dirtab::ParsePathspec(current_pathspec_str, false)) success = false; size_t new_length = current_pathspec_str.find_last_of("/"); current_pathspec_str = current_pathspec_str.substr(0, new_length); } return success; } } // namespace catalog <|endoftext|>
<commit_before>/* * CvFindChessboardCorners_Processor.cpp * * Created on: 16-10-2010 * Author: mateusz */ #include "CvFindChessboardCorners_Processor.hpp" namespace Processors { namespace CvFindChessboardCorners { using namespace std; using namespace boost; using namespace cv; using namespace Types::Objects3D; CvFindChessboardCorners_Processor::CvFindChessboardCorners_Processor(const std::string & name) : Component(name), prop_subpix("subpix", true), prop_subpix_window("subpix_window", 9, "range"), prop_scale("scale", true), prop_scale_factor("scale_factor", 2, "range"), prop_width("chessboard.width", 9), prop_height("chessboard.height", 6), prop_square_width("chessboard.square_width", 1), prop_square_height("chessboard.square_height", 1), prop_fastCheck("flags.fast_check", true), prop_filterQuads("flags.filter_quads", true), prop_adaptiveThreshold("flags.adaptive_treshold", true), prop_normalizeImage("flags.normalize_image", true) { findChessboardCornersFlags = 0; registerProperty(prop_subpix); prop_subpix_window.addConstraint("3"); prop_subpix_window.addConstraint("11"); registerProperty(prop_subpix_window); registerProperty(prop_scale); prop_scale_factor.addConstraint("1"); prop_scale_factor.addConstraint("8"); registerProperty(prop_scale_factor); registerProperty(prop_width); registerProperty(prop_height); registerProperty(prop_square_width); registerProperty(prop_square_height); prop_fastCheck.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_fastCheck); prop_filterQuads.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_filterQuads); prop_adaptiveThreshold.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_adaptiveThreshold); prop_normalizeImage.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_normalizeImage); prop_width.setCallback(boost::bind(&CvFindChessboardCorners_Processor::sizeCallback, this, _1, _2)); prop_height.setCallback(boost::bind(&CvFindChessboardCorners_Processor::sizeCallback, this, _1, _2)); } CvFindChessboardCorners_Processor::~CvFindChessboardCorners_Processor() { } bool CvFindChessboardCorners_Processor::onFinish() { return true; } bool CvFindChessboardCorners_Processor::onStop() { return true; } bool CvFindChessboardCorners_Processor::onInit() { h_onNewImage.setup(this, &CvFindChessboardCorners_Processor::onNewImage); registerHandler("onNewImage", &h_onNewImage); registerStream("in_img", &in_img); registerStream("out_chessboard", &out_chessboard); registerStream("out_imagePosition", &out_imagePosition); chessboardFound = registerEvent("chessboardFound"); chessboardNotFound = registerEvent("chessboardNotFound"); initChessboard(); LOG(LTRACE) << "component initialized\n"; return true; } void CvFindChessboardCorners_Processor::initChessboard() { LOG(LINFO) << "CvFindChessboardCorners_Processor: width: " << prop_width << "\n"; LOG(LINFO) << "CvFindChessboardCorners_Processor: height: " << prop_height << "\n"; LOG(LINFO) << "CvFindChessboardCorners_Processor: squareSize: " << prop_square_width << "x" << prop_square_height << "m\n"; chessboard = boost::shared_ptr <Chessboard>(new Chessboard(cv::Size(prop_width, prop_height))); vector <Point3f> modelPoints; for (int i = 0; i < prop_height; ++i) { for (int j = 0; j < prop_width; ++j) { modelPoints.push_back(Point3f(-j * prop_square_height, -i * prop_square_width, 0)); } } chessboard->setModelPoints(modelPoints); } void CvFindChessboardCorners_Processor::sizeCallback(int old_value, int new_value) { initChessboard(); } void CvFindChessboardCorners_Processor::flagsCallback(bool old_value, bool new_value) { if(prop_fastCheck){ findChessboardCornersFlags |= CV_CALIB_CB_FAST_CHECK; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_FAST_CHECK; } if(prop_filterQuads){ findChessboardCornersFlags |= CV_CALIB_CB_FILTER_QUADS; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_FILTER_QUADS; } if(prop_adaptiveThreshold){ findChessboardCornersFlags |= CV_CALIB_CB_ADAPTIVE_THRESH; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_ADAPTIVE_THRESH; } if(prop_normalizeImage){ findChessboardCornersFlags |= CV_CALIB_CB_NORMALIZE_IMAGE; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_NORMALIZE_IMAGE; } } bool CvFindChessboardCorners_Processor::onStart() { return true; } bool CvFindChessboardCorners_Processor::onStep() { return true; } void CvFindChessboardCorners_Processor::onNewImage() { LOG(LTRACE) << "void CvFindChessboardCorners_Processor::onNewImage() begin\n"; try { if(in_img.empty()){ return; } Mat image = in_img.read(); timer.restart(); cv::resize(image, sub_img, Size(), 1.0 / prop_scale_factor, 1.0 / prop_scale_factor, INTER_NEAREST); bool found; cv::Size chessboardSize(prop_width, prop_height); if (prop_scale) { found = findChessboardCorners(sub_img, chessboardSize, corners, findChessboardCornersFlags); for (size_t i = 0; i < corners.size(); ++i) { corners[i].x *= prop_scale_factor; corners[i].y *= prop_scale_factor; } } else { found = findChessboardCorners(image, chessboardSize, corners, findChessboardCornersFlags); } LOG(LTRACE) << "findChessboardCorners() execution time: " << timer.elapsed() << " s\n"; if (found) { LOG(LTRACE) << "chessboard found\n"; if (prop_subpix) { cornerSubPix(image, corners, Size(prop_subpix_window, prop_subpix_window), Size(1, 1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 50, 1e-3)); } chessboard->setImagePoints(corners); out_chessboard.write(*chessboard); Types::ImagePosition imagePosition; double maxPixels = std::max(image.size().width, image.size().height); imagePosition.elements[0] = (corners[0].x - image.size().width / 2) / maxPixels; imagePosition.elements[1] = (corners[1].y - image.size().height / 2) / maxPixels; imagePosition.elements[2] = 0; imagePosition.elements[3] = 0; out_imagePosition.write(imagePosition); chessboardFound->raise(); } else { LOG(LTRACE) << "chessboard not found\n"; chessboardNotFound->raise(); } } catch (const Exception& e) { LOG(LERROR) << e.what() << "\n"; } LOG(LTRACE) << "void CvFindChessboardCorners_Processor::onNewImage() end\n"; } } // namespace CvFindChessboardCorners { } // namespace Processors { <commit_msg>IB-EIH visual servo in progress<commit_after>/* * CvFindChessboardCorners_Processor.cpp * * Created on: 16-10-2010 * Author: mateusz */ #include "CvFindChessboardCorners_Processor.hpp" namespace Processors { namespace CvFindChessboardCorners { using namespace std; using namespace boost; using namespace cv; using namespace Types::Objects3D; CvFindChessboardCorners_Processor::CvFindChessboardCorners_Processor(const std::string & name) : Component(name), prop_subpix("subpix", true), prop_subpix_window("subpix_window", 9, "range"), prop_scale("scale", true), prop_scale_factor("scale_factor", 2, "range"), prop_width("chessboard.width", 9), prop_height("chessboard.height", 6), prop_square_width("chessboard.square_width", 1), prop_square_height("chessboard.square_height", 1), prop_fastCheck("flags.fast_check", true), prop_filterQuads("flags.filter_quads", true), prop_adaptiveThreshold("flags.adaptive_treshold", true), prop_normalizeImage("flags.normalize_image", true) { findChessboardCornersFlags = 0; registerProperty(prop_subpix); prop_subpix_window.addConstraint("3"); prop_subpix_window.addConstraint("11"); registerProperty(prop_subpix_window); registerProperty(prop_scale); prop_scale_factor.addConstraint("1"); prop_scale_factor.addConstraint("8"); registerProperty(prop_scale_factor); registerProperty(prop_width); registerProperty(prop_height); registerProperty(prop_square_width); registerProperty(prop_square_height); prop_fastCheck.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_fastCheck); prop_filterQuads.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_filterQuads); prop_adaptiveThreshold.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_adaptiveThreshold); prop_normalizeImage.setCallback(boost::bind(&CvFindChessboardCorners_Processor::flagsCallback, this, _1, _2)); registerProperty(prop_normalizeImage); prop_width.setCallback(boost::bind(&CvFindChessboardCorners_Processor::sizeCallback, this, _1, _2)); prop_height.setCallback(boost::bind(&CvFindChessboardCorners_Processor::sizeCallback, this, _1, _2)); } CvFindChessboardCorners_Processor::~CvFindChessboardCorners_Processor() { } bool CvFindChessboardCorners_Processor::onFinish() { return true; } bool CvFindChessboardCorners_Processor::onStop() { return true; } bool CvFindChessboardCorners_Processor::onInit() { h_onNewImage.setup(this, &CvFindChessboardCorners_Processor::onNewImage); registerHandler("onNewImage", &h_onNewImage); registerStream("in_img", &in_img); registerStream("out_chessboard", &out_chessboard); registerStream("out_imagePosition", &out_imagePosition); chessboardFound = registerEvent("chessboardFound"); chessboardNotFound = registerEvent("chessboardNotFound"); initChessboard(); LOG(LTRACE) << "component initialized\n"; return true; } void CvFindChessboardCorners_Processor::initChessboard() { LOG(LINFO) << "CvFindChessboardCorners_Processor: width: " << prop_width << "\n"; LOG(LINFO) << "CvFindChessboardCorners_Processor: height: " << prop_height << "\n"; LOG(LINFO) << "CvFindChessboardCorners_Processor: squareSize: " << prop_square_width << "x" << prop_square_height << "m\n"; chessboard = boost::shared_ptr <Chessboard>(new Chessboard(cv::Size(prop_width, prop_height))); vector <Point3f> modelPoints; for (int i = 0; i < prop_height; ++i) { for (int j = 0; j < prop_width; ++j) { modelPoints.push_back(Point3f(-j * prop_square_height, -i * prop_square_width, 0)); } } chessboard->setModelPoints(modelPoints); } void CvFindChessboardCorners_Processor::sizeCallback(int old_value, int new_value) { initChessboard(); } void CvFindChessboardCorners_Processor::flagsCallback(bool old_value, bool new_value) { if(prop_fastCheck){ findChessboardCornersFlags |= CV_CALIB_CB_FAST_CHECK; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_FAST_CHECK; } if(prop_filterQuads){ findChessboardCornersFlags |= CV_CALIB_CB_FILTER_QUADS; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_FILTER_QUADS; } if(prop_adaptiveThreshold){ findChessboardCornersFlags |= CV_CALIB_CB_ADAPTIVE_THRESH; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_ADAPTIVE_THRESH; } if(prop_normalizeImage){ findChessboardCornersFlags |= CV_CALIB_CB_NORMALIZE_IMAGE; } else { findChessboardCornersFlags &= ~CV_CALIB_CB_NORMALIZE_IMAGE; } } bool CvFindChessboardCorners_Processor::onStart() { return true; } bool CvFindChessboardCorners_Processor::onStep() { return true; } void CvFindChessboardCorners_Processor::onNewImage() { LOG(LTRACE) << "void CvFindChessboardCorners_Processor::onNewImage() begin\n"; try { if(in_img.empty()){ return; } Mat image = in_img.read(); timer.restart(); cv::resize(image, sub_img, Size(), 1.0 / prop_scale_factor, 1.0 / prop_scale_factor, INTER_NEAREST); bool found; cv::Size chessboardSize(prop_width, prop_height); if (prop_scale) { found = findChessboardCorners(sub_img, chessboardSize, corners, findChessboardCornersFlags); for (size_t i = 0; i < corners.size(); ++i) { corners[i].x *= prop_scale_factor; corners[i].y *= prop_scale_factor; } } else { found = findChessboardCorners(image, chessboardSize, corners, findChessboardCornersFlags); } LOG(LTRACE) << "findChessboardCorners() execution time: " << timer.elapsed() << " s\n"; if (found) { LOG(LTRACE) << "chessboard found\n"; if (prop_subpix) { cornerSubPix(image, corners, Size(prop_subpix_window, prop_subpix_window), Size(1, 1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 50, 1e-3)); } chessboard->setImagePoints(corners); out_chessboard.write(*chessboard); Types::ImagePosition imagePosition; double maxPixels = std::max(image.size().width, image.size().height); imagePosition.elements[0] = (corners[0].x - image.size().width / 2) / maxPixels; imagePosition.elements[1] = (corners[0].y - image.size().height / 2) / maxPixels; imagePosition.elements[2] = 0; imagePosition.elements[3] = - atan2(corners[1].y - corners[0].y, corners[1].x - corners[0].x); out_imagePosition.write(imagePosition); chessboardFound->raise(); } else { LOG(LTRACE) << "chessboard not found\n"; chessboardNotFound->raise(); } } catch (const Exception& e) { LOG(LERROR) << e.what() << "\n"; } LOG(LTRACE) << "void CvFindChessboardCorners_Processor::onNewImage() end\n"; } } // namespace CvFindChessboardCorners { } // namespace Processors { <|endoftext|>
<commit_before>/* WiFiClient.cpp - TCP/IP client for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define LWIP_INTERNAL extern "C" { #include "include/wl_definitions.h" #include "osapi.h" #include "ets_sys.h" } #include "debug.h" #include "ESP8266WiFi.h" #include "WiFiClient.h" #include "WiFiServer.h" #include "lwip/opt.h" #include "lwip/tcp.h" #include "lwip/inet.h" #include "cbuf.h" #include "include/ClientContext.h" #include "c_types.h" ICACHE_FLASH_ATTR WiFiClient::WiFiClient() : _client(0) { } ICACHE_FLASH_ATTR WiFiClient::WiFiClient(ClientContext* client) : _client(client) { _client->ref(); } ICACHE_FLASH_ATTR WiFiClient::~WiFiClient() { if (_client) _client->unref(); } ICACHE_FLASH_ATTR WiFiClient::WiFiClient(const WiFiClient& other) { _client = other._client; if (_client) _client->ref(); } WiFiClient& ICACHE_FLASH_ATTR WiFiClient::operator=(const WiFiClient& other) { if (_client) _client->unref(); _client = other._client; if (_client) _client->ref(); return *this; } int ICACHE_FLASH_ATTR WiFiClient::connect(const char* host, uint16_t port) { IPAddress remote_addr; if (WiFi.hostByName(host, remote_addr)) { return connect(remote_addr, port); } return 0; } int ICACHE_FLASH_ATTR WiFiClient::connect(IPAddress ip, uint16_t port) { if (_client) stop(); tcp_pcb* pcb = tcp_new(); if (!pcb) return 0; ip_addr_t addr; addr.addr = ip; tcp_arg(pcb, this); tcp_err(pcb, &WiFiClient::_s_err); tcp_connect(pcb, &addr, port, reinterpret_cast<tcp_connected_fn>(&WiFiClient::_s_connected)); esp_yield(); if (_client) return 1; // if tcp_error was called, pcb has already been destroyed. // tcp_abort(pcb); return 0; } int8_t ICACHE_FLASH_ATTR WiFiClient::_connected(void* pcb, int8_t err) { tcp_pcb* tpcb = reinterpret_cast<tcp_pcb*>(pcb); _client = new ClientContext(tpcb, 0, 0); _client->ref(); esp_schedule(); return ERR_OK; } void ICACHE_FLASH_ATTR WiFiClient::_err(int8_t err) { DEBUGV(":err %d\r\n", err); esp_schedule(); } size_t ICACHE_FLASH_ATTR WiFiClient::write(uint8_t b) { return write(&b, 1); } size_t ICACHE_FLASH_ATTR WiFiClient::write(const uint8_t *buf, size_t size) { if (!_client || !size) { return 0; } return _client->write(reinterpret_cast<const char*>(buf), size); } extern "C" uint32_t esp_micros_at_task_start(); int ICACHE_FLASH_ATTR WiFiClient::available() { static uint32_t lastPollTime = 0; if (!_client) return 0; if (lastPollTime > esp_micros_at_task_start()) yield(); lastPollTime = micros(); int result = _client->getSize(); return result; } int ICACHE_FLASH_ATTR WiFiClient::read() { if (!available()) return -1; return _client->read(); } int ICACHE_FLASH_ATTR WiFiClient::read(uint8_t* buf, size_t size) { return (int) _client->read(reinterpret_cast<char*>(buf), size); } int ICACHE_FLASH_ATTR WiFiClient::peek() { if (!available()) return -1; return _client->peek(); } void ICACHE_FLASH_ATTR WiFiClient::flush() { if (_client) _client->flush(); } void ICACHE_FLASH_ATTR WiFiClient::stop() { if (!_client) return; _client->unref(); _client = 0; } uint8_t ICACHE_FLASH_ATTR WiFiClient::connected() { if (!_client) return 0; return _client->state() == ESTABLISHED; } uint8_t ICACHE_FLASH_ATTR WiFiClient::status() { if (!_client) return CLOSED; return _client->state(); } ICACHE_FLASH_ATTR WiFiClient::operator bool() { return _client != 0; } IPAddress WiFiClient::remoteIP() { if (!_client) return IPAddress(0U); return IPAddress(_client->getRemoteAddress()); } uint16_t WiFiClient::remotePort() { if (!_client) return 0; return _client->getRemotePort(); } int8_t ICACHE_FLASH_ATTR WiFiClient::_s_connected(void* arg, void* tpcb, int8_t err) { return reinterpret_cast<WiFiClient*>(arg)->_connected(tpcb, err); } void ICACHE_FLASH_ATTR WiFiClient::_s_err(void* arg, int8_t err) { reinterpret_cast<WiFiClient*>(arg)->_err(err); } <commit_msg>ESP8266WiFi: made connected() return true if data is available<commit_after>/* WiFiClient.cpp - TCP/IP client for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define LWIP_INTERNAL extern "C" { #include "include/wl_definitions.h" #include "osapi.h" #include "ets_sys.h" } #include "debug.h" #include "ESP8266WiFi.h" #include "WiFiClient.h" #include "WiFiServer.h" #include "lwip/opt.h" #include "lwip/tcp.h" #include "lwip/inet.h" #include "cbuf.h" #include "include/ClientContext.h" #include "c_types.h" ICACHE_FLASH_ATTR WiFiClient::WiFiClient() : _client(0) { } ICACHE_FLASH_ATTR WiFiClient::WiFiClient(ClientContext* client) : _client(client) { _client->ref(); } ICACHE_FLASH_ATTR WiFiClient::~WiFiClient() { if (_client) _client->unref(); } ICACHE_FLASH_ATTR WiFiClient::WiFiClient(const WiFiClient& other) { _client = other._client; if (_client) _client->ref(); } WiFiClient& ICACHE_FLASH_ATTR WiFiClient::operator=(const WiFiClient& other) { if (_client) _client->unref(); _client = other._client; if (_client) _client->ref(); return *this; } int ICACHE_FLASH_ATTR WiFiClient::connect(const char* host, uint16_t port) { IPAddress remote_addr; if (WiFi.hostByName(host, remote_addr)) { return connect(remote_addr, port); } return 0; } int ICACHE_FLASH_ATTR WiFiClient::connect(IPAddress ip, uint16_t port) { if (_client) stop(); tcp_pcb* pcb = tcp_new(); if (!pcb) return 0; ip_addr_t addr; addr.addr = ip; tcp_arg(pcb, this); tcp_err(pcb, &WiFiClient::_s_err); tcp_connect(pcb, &addr, port, reinterpret_cast<tcp_connected_fn>(&WiFiClient::_s_connected)); esp_yield(); if (_client) return 1; // if tcp_error was called, pcb has already been destroyed. // tcp_abort(pcb); return 0; } int8_t ICACHE_FLASH_ATTR WiFiClient::_connected(void* pcb, int8_t err) { tcp_pcb* tpcb = reinterpret_cast<tcp_pcb*>(pcb); _client = new ClientContext(tpcb, 0, 0); _client->ref(); esp_schedule(); return ERR_OK; } void ICACHE_FLASH_ATTR WiFiClient::_err(int8_t err) { DEBUGV(":err %d\r\n", err); esp_schedule(); } size_t ICACHE_FLASH_ATTR WiFiClient::write(uint8_t b) { return write(&b, 1); } size_t ICACHE_FLASH_ATTR WiFiClient::write(const uint8_t *buf, size_t size) { if (!_client || !size) { return 0; } return _client->write(reinterpret_cast<const char*>(buf), size); } extern "C" uint32_t esp_micros_at_task_start(); int ICACHE_FLASH_ATTR WiFiClient::available() { static uint32_t lastPollTime = 0; if (!_client) return 0; if (lastPollTime > esp_micros_at_task_start()) yield(); lastPollTime = micros(); int result = _client->getSize(); return result; } int ICACHE_FLASH_ATTR WiFiClient::read() { if (!available()) return -1; return _client->read(); } int ICACHE_FLASH_ATTR WiFiClient::read(uint8_t* buf, size_t size) { return (int) _client->read(reinterpret_cast<char*>(buf), size); } int ICACHE_FLASH_ATTR WiFiClient::peek() { if (!available()) return -1; return _client->peek(); } void ICACHE_FLASH_ATTR WiFiClient::flush() { if (_client) _client->flush(); } void ICACHE_FLASH_ATTR WiFiClient::stop() { if (!_client) return; _client->unref(); _client = 0; } uint8_t ICACHE_FLASH_ATTR WiFiClient::connected() { if (!_client) return 0; return _client->state() == ESTABLISHED || available(); } uint8_t ICACHE_FLASH_ATTR WiFiClient::status() { if (!_client) return CLOSED; return _client->state(); } ICACHE_FLASH_ATTR WiFiClient::operator bool() { return _client != 0; } IPAddress WiFiClient::remoteIP() { if (!_client) return IPAddress(0U); return IPAddress(_client->getRemoteAddress()); } uint16_t WiFiClient::remotePort() { if (!_client) return 0; return _client->getRemotePort(); } int8_t ICACHE_FLASH_ATTR WiFiClient::_s_connected(void* arg, void* tpcb, int8_t err) { return reinterpret_cast<WiFiClient*>(arg)->_connected(tpcb, err); } void ICACHE_FLASH_ATTR WiFiClient::_s_err(void* arg, int8_t err) { reinterpret_cast<WiFiClient*>(arg)->_err(err); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "gfx/blit.h" #include "base/logging.h" #include "build/build_config.h" #include "gfx/point.h" #include "gfx/rect.h" #include "skia/ext/platform_canvas.h" #include "skia/ext/platform_device.h" #if defined(TOOLKIT_GTK) #include <cairo/cairo.h> #endif #if defined(OS_MACOSX) #include "base/mac_util.h" #include "base/scoped_cftyperef.h" #endif namespace gfx { namespace { // Returns true if the given canvas has any part of itself clipped out or // any non-identity tranform. bool HasClipOrTransform(const skia::PlatformCanvas& canvas) { if (!canvas.getTotalMatrix().isIdentity()) return true; const SkRegion& clip_region = canvas.getTotalClip(); if (clip_region.isEmpty() || clip_region.isComplex()) return true; // Now we know the clip is a regular rectangle, make sure it covers the // entire canvas. const SkBitmap& bitmap = canvas.getTopPlatformDevice().accessBitmap(false); const SkIRect& clip_bounds = clip_region.getBounds(); if (clip_bounds.fLeft != 0 || clip_bounds.fTop != 0 || clip_bounds.fRight != bitmap.width() || clip_bounds.fBottom != bitmap.height()) return true; return false; } } // namespace void BlitContextToContext(NativeDrawingContext dst_context, const Rect& dst_rect, NativeDrawingContext src_context, const Point& src_origin) { #if defined(OS_WIN) BitBlt(dst_context, dst_rect.x(), dst_rect.y(), dst_rect.width(), dst_rect.height(), src_context, src_origin.x(), src_origin.y(), SRCCOPY); #elif defined(OS_MACOSX) // Only translations and/or vertical flips in the source context are // supported; more complex source context transforms will be ignored. // If there is a translation on the source context, we need to account for // it ourselves since CGBitmapContextCreateImage will bypass it. Rect src_rect(src_origin, dst_rect.size()); CGAffineTransform transform = CGContextGetCTM(src_context); bool flipped = fabs(transform.d + 1) < 0.0001; CGFloat delta_y = flipped ? CGBitmapContextGetHeight(src_context) - transform.ty : transform.ty; src_rect.Offset(transform.tx, delta_y); scoped_cftyperef<CGImageRef> src_image(CGBitmapContextCreateImage(src_context)); scoped_cftyperef<CGImageRef> src_sub_image( CGImageCreateWithImageInRect(src_image, src_rect.ToCGRect())); CGContextDrawImage(dst_context, dst_rect.ToCGRect(), src_sub_image); #else // Linux, BSD, others // Only translations in the source context are supported; more complex // source context transforms will be ignored. cairo_save(dst_context); double surface_x = src_origin.x(); double surface_y = src_origin.y(); cairo_user_to_device(src_context, &surface_x, &surface_y); cairo_set_source_surface(dst_context, cairo_get_target(src_context), dst_rect.x()-surface_x, dst_rect.y()-surface_y); cairo_rectangle(dst_context, dst_rect.x(), dst_rect.y(), dst_rect.width(), dst_rect.height()); cairo_clip(dst_context); cairo_paint(dst_context); cairo_restore(dst_context); #endif } static NativeDrawingContext GetContextFromCanvas( skia::PlatformCanvas *canvas) { skia::PlatformDevice& device = canvas->getTopPlatformDevice(); #if defined(OS_WIN) return device.getBitmapDC(); #elif defined(OS_MACOSX) return device.GetBitmapContext(); #else // Linux, BSD, others return device.beginPlatformPaint(); #endif } void BlitContextToCanvas(skia::PlatformCanvas *dst_canvas, const Rect& dst_rect, NativeDrawingContext src_context, const Point& src_origin) { BlitContextToContext(GetContextFromCanvas(dst_canvas), dst_rect, src_context, src_origin); } void BlitCanvasToContext(NativeDrawingContext dst_context, const Rect& dst_rect, skia::PlatformCanvas *src_canvas, const Point& src_origin) { BlitContextToContext(dst_context, dst_rect, GetContextFromCanvas(src_canvas), src_origin); } void BlitCanvasToCanvas(skia::PlatformCanvas *dst_canvas, const Rect& dst_rect, skia::PlatformCanvas *src_canvas, const Point& src_origin) { BlitContextToContext(GetContextFromCanvas(dst_canvas), dst_rect, GetContextFromCanvas(src_canvas), src_origin); } #if defined(OS_WIN) void ScrollCanvas(skia::PlatformCanvas* canvas, const gfx::Rect& clip, const gfx::Point& amount) { DCHECK(!HasClipOrTransform(*canvas)); // Don't support special stuff. HDC hdc = canvas->beginPlatformPaint(); RECT damaged_rect; RECT r = clip.ToRECT(); ScrollDC(hdc, amount.x(), amount.y(), NULL, &r, NULL, &damaged_rect); canvas->endPlatformPaint(); } #elif defined(OS_POSIX) // Cairo has no nice scroll function so we do our own. On Mac it's possible to // use platform scroll code, but it's complex so we just use the same path // here. Either way it will be software-only, so it shouldn't matter much. void ScrollCanvas(skia::PlatformCanvas* canvas, const gfx::Rect& in_clip, const gfx::Point& amount) { DCHECK(!HasClipOrTransform(*canvas)); // Don't support special stuff. SkBitmap& bitmap = const_cast<SkBitmap&>( canvas->getTopPlatformDevice().accessBitmap(true)); SkAutoLockPixels lock(bitmap); // We expect all coords to be inside the canvas, so clip here. gfx::Rect clip = in_clip.Intersect( gfx::Rect(0, 0, bitmap.width(), bitmap.height())); // Compute the set of pixels we'll actually end up painting. gfx::Rect dest_rect = clip; dest_rect.Offset(amount); dest_rect = dest_rect.Intersect(clip); if (dest_rect.size() == gfx::Size()) return; // Nothing to do. // Compute the source pixels that will map to the dest_rect gfx::Rect src_rect = dest_rect; src_rect.Offset(-amount.x(), -amount.y()); size_t row_bytes = dest_rect.width() * 4; if (amount.y() > 0) { // Data is moving down, copy from the bottom up. for (int y = dest_rect.height() - 1; y >= 0; y--) { memcpy(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } else if (amount.y() < 0) { // Data is moving up, copy from the top down. for (int y = 0; y < dest_rect.height(); y++) { memcpy(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } else if (amount.x() != 0) { // Horizontal-only scroll. We can do it in either top-to-bottom or bottom- // to-top, but have to be careful about the order for copying each row. // Fortunately, memmove already handles this for us. for (int y = 0; y < dest_rect.height(); y++) { memmove(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } } #endif } // namespace gfx <commit_msg>Fix ChromeOS build by putting back define from previous patch (tried incorrectly to clean this up).<commit_after>// Copyright (c) 2009 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 "gfx/blit.h" #include "base/logging.h" #include "build/build_config.h" #include "gfx/point.h" #include "gfx/rect.h" #include "skia/ext/platform_canvas.h" #include "skia/ext/platform_device.h" #if defined(OS_POSIX) && !defined(OS_MACOSX) #include <cairo/cairo.h> #endif #if defined(OS_MACOSX) #include "base/mac_util.h" #include "base/scoped_cftyperef.h" #endif namespace gfx { namespace { // Returns true if the given canvas has any part of itself clipped out or // any non-identity tranform. bool HasClipOrTransform(const skia::PlatformCanvas& canvas) { if (!canvas.getTotalMatrix().isIdentity()) return true; const SkRegion& clip_region = canvas.getTotalClip(); if (clip_region.isEmpty() || clip_region.isComplex()) return true; // Now we know the clip is a regular rectangle, make sure it covers the // entire canvas. const SkBitmap& bitmap = canvas.getTopPlatformDevice().accessBitmap(false); const SkIRect& clip_bounds = clip_region.getBounds(); if (clip_bounds.fLeft != 0 || clip_bounds.fTop != 0 || clip_bounds.fRight != bitmap.width() || clip_bounds.fBottom != bitmap.height()) return true; return false; } } // namespace void BlitContextToContext(NativeDrawingContext dst_context, const Rect& dst_rect, NativeDrawingContext src_context, const Point& src_origin) { #if defined(OS_WIN) BitBlt(dst_context, dst_rect.x(), dst_rect.y(), dst_rect.width(), dst_rect.height(), src_context, src_origin.x(), src_origin.y(), SRCCOPY); #elif defined(OS_MACOSX) // Only translations and/or vertical flips in the source context are // supported; more complex source context transforms will be ignored. // If there is a translation on the source context, we need to account for // it ourselves since CGBitmapContextCreateImage will bypass it. Rect src_rect(src_origin, dst_rect.size()); CGAffineTransform transform = CGContextGetCTM(src_context); bool flipped = fabs(transform.d + 1) < 0.0001; CGFloat delta_y = flipped ? CGBitmapContextGetHeight(src_context) - transform.ty : transform.ty; src_rect.Offset(transform.tx, delta_y); scoped_cftyperef<CGImageRef> src_image(CGBitmapContextCreateImage(src_context)); scoped_cftyperef<CGImageRef> src_sub_image( CGImageCreateWithImageInRect(src_image, src_rect.ToCGRect())); CGContextDrawImage(dst_context, dst_rect.ToCGRect(), src_sub_image); #else // Linux, BSD, others // Only translations in the source context are supported; more complex // source context transforms will be ignored. cairo_save(dst_context); double surface_x = src_origin.x(); double surface_y = src_origin.y(); cairo_user_to_device(src_context, &surface_x, &surface_y); cairo_set_source_surface(dst_context, cairo_get_target(src_context), dst_rect.x()-surface_x, dst_rect.y()-surface_y); cairo_rectangle(dst_context, dst_rect.x(), dst_rect.y(), dst_rect.width(), dst_rect.height()); cairo_clip(dst_context); cairo_paint(dst_context); cairo_restore(dst_context); #endif } static NativeDrawingContext GetContextFromCanvas( skia::PlatformCanvas *canvas) { skia::PlatformDevice& device = canvas->getTopPlatformDevice(); #if defined(OS_WIN) return device.getBitmapDC(); #elif defined(OS_MACOSX) return device.GetBitmapContext(); #else // Linux, BSD, others return device.beginPlatformPaint(); #endif } void BlitContextToCanvas(skia::PlatformCanvas *dst_canvas, const Rect& dst_rect, NativeDrawingContext src_context, const Point& src_origin) { BlitContextToContext(GetContextFromCanvas(dst_canvas), dst_rect, src_context, src_origin); } void BlitCanvasToContext(NativeDrawingContext dst_context, const Rect& dst_rect, skia::PlatformCanvas *src_canvas, const Point& src_origin) { BlitContextToContext(dst_context, dst_rect, GetContextFromCanvas(src_canvas), src_origin); } void BlitCanvasToCanvas(skia::PlatformCanvas *dst_canvas, const Rect& dst_rect, skia::PlatformCanvas *src_canvas, const Point& src_origin) { BlitContextToContext(GetContextFromCanvas(dst_canvas), dst_rect, GetContextFromCanvas(src_canvas), src_origin); } #if defined(OS_WIN) void ScrollCanvas(skia::PlatformCanvas* canvas, const gfx::Rect& clip, const gfx::Point& amount) { DCHECK(!HasClipOrTransform(*canvas)); // Don't support special stuff. HDC hdc = canvas->beginPlatformPaint(); RECT damaged_rect; RECT r = clip.ToRECT(); ScrollDC(hdc, amount.x(), amount.y(), NULL, &r, NULL, &damaged_rect); canvas->endPlatformPaint(); } #elif defined(OS_POSIX) // Cairo has no nice scroll function so we do our own. On Mac it's possible to // use platform scroll code, but it's complex so we just use the same path // here. Either way it will be software-only, so it shouldn't matter much. void ScrollCanvas(skia::PlatformCanvas* canvas, const gfx::Rect& in_clip, const gfx::Point& amount) { DCHECK(!HasClipOrTransform(*canvas)); // Don't support special stuff. SkBitmap& bitmap = const_cast<SkBitmap&>( canvas->getTopPlatformDevice().accessBitmap(true)); SkAutoLockPixels lock(bitmap); // We expect all coords to be inside the canvas, so clip here. gfx::Rect clip = in_clip.Intersect( gfx::Rect(0, 0, bitmap.width(), bitmap.height())); // Compute the set of pixels we'll actually end up painting. gfx::Rect dest_rect = clip; dest_rect.Offset(amount); dest_rect = dest_rect.Intersect(clip); if (dest_rect.size() == gfx::Size()) return; // Nothing to do. // Compute the source pixels that will map to the dest_rect gfx::Rect src_rect = dest_rect; src_rect.Offset(-amount.x(), -amount.y()); size_t row_bytes = dest_rect.width() * 4; if (amount.y() > 0) { // Data is moving down, copy from the bottom up. for (int y = dest_rect.height() - 1; y >= 0; y--) { memcpy(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } else if (amount.y() < 0) { // Data is moving up, copy from the top down. for (int y = 0; y < dest_rect.height(); y++) { memcpy(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } else if (amount.x() != 0) { // Horizontal-only scroll. We can do it in either top-to-bottom or bottom- // to-top, but have to be careful about the order for copying each row. // Fortunately, memmove already handles this for us. for (int y = 0; y < dest_rect.height(); y++) { memmove(bitmap.getAddr32(dest_rect.x(), dest_rect.y() + y), bitmap.getAddr32(src_rect.x(), src_rect.y() + y), row_bytes); } } } #endif } // namespace gfx <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "xcompositeglxintegration.h" #include "waylandobject.h" #include "wayland_wrapper/wlcompositor.h" #include "wayland-xcomposite-server-protocol.h" #include <QtGui/QPlatformNativeInterface> #include <QtGui/QOpenGLContext> #include "xcompositebuffer.h" #include "xcompositehandler.h" #include <X11/extensions/Xcomposite.h> #include <QtCore/QDebug> QVector<int> qglx_buildSpec() { QVector<int> spec(48); int i = 0; spec[i++] = GLX_LEVEL; spec[i++] = 0; spec[i++] = GLX_DRAWABLE_TYPE; spec[i++] = GLX_PIXMAP_BIT | GLX_WINDOW_BIT; spec[i++] = GLX_BIND_TO_TEXTURE_TARGETS_EXT; spec[i++] = GLX_TEXTURE_2D_BIT_EXT; spec[i++] = GLX_BIND_TO_TEXTURE_RGB_EXT; spec[i++] = TRUE; spec[i++] = 0; return spec; } struct wl_xcomposite_interface XCompositeHandler::xcomposite_interface = { XCompositeHandler::create_buffer }; GraphicsHardwareIntegration *GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor) { return new XCompositeGLXIntegration(compositor); } XCompositeGLXIntegration::XCompositeGLXIntegration(WaylandCompositor *compositor) : GraphicsHardwareIntegration(compositor) , mDisplay(0) , mHandler(0) { QPlatformNativeInterface *nativeInterface = QGuiApplicationPrivate::platformIntegration()->nativeInterface(); if (nativeInterface) { mDisplay = static_cast<Display *>(nativeInterface->nativeResourceForWindow("Display",m_compositor->window())); if (!mDisplay) qFatal("could not retireve Display from platform integration"); } else { qFatal("Platform integration doesn't have native interface"); } mScreen = XDefaultScreen(mDisplay); } XCompositeGLXIntegration::~XCompositeGLXIntegration() { delete mHandler; } void XCompositeGLXIntegration::initializeHardware(Wayland::Display *waylandDisplay) { mHandler = new XCompositeHandler(m_compositor->handle(),mDisplay,m_compositor->window()); wl_display_add_global(waylandDisplay->handle(),&wl_xcomposite_interface,mHandler,XCompositeHandler::xcomposite_bind_func); QOpenGLContext *glContext = new QOpenGLContext(); glContext->create(); m_glxBindTexImageEXT = reinterpret_cast<PFNGLXBINDTEXIMAGEEXTPROC>(glContext->getProcAddress("glXBindTexImageEXT")); if (!m_glxBindTexImageEXT) { qDebug() << "Did not find glxBindTexImageExt, everything will FAIL!"; } m_glxReleaseTexImageEXT = reinterpret_cast<PFNGLXRELEASETEXIMAGEEXTPROC>(glContext->getProcAddress("glXReleaseTexImageEXT")); if (!m_glxReleaseTexImageEXT) { qDebug() << "Did not find glxReleaseTexImageExt"; } delete glContext; } GLuint XCompositeGLXIntegration::createTextureFromBuffer(wl_buffer *buffer, QOpenGLContext *) { XCompositeBuffer *compositorBuffer = Wayland::wayland_cast<XCompositeBuffer *>(buffer); Pixmap pixmap = XCompositeNameWindowPixmap(mDisplay, compositorBuffer->window()); QVector<int> glxConfigSpec = qglx_buildSpec(); int numberOfConfigs; GLXFBConfig *configs = glXChooseFBConfig(mDisplay,mScreen,glxConfigSpec.constData(),&numberOfConfigs); QVector<int> attribList; attribList.append(GLX_TEXTURE_FORMAT_EXT); attribList.append(GLX_TEXTURE_FORMAT_RGB_EXT); attribList.append(GLX_TEXTURE_TARGET_EXT); attribList.append(GLX_TEXTURE_2D_EXT); attribList.append(0); GLXPixmap glxPixmap = glXCreatePixmap(mDisplay,*configs,pixmap,attribList.constData()); uint inverted = 0; glXQueryDrawable(mDisplay, glxPixmap, GLX_Y_INVERTED_EXT,&inverted); compositorBuffer->setInvertedY(!inverted); XFree(configs); GLuint textureId; glGenTextures(1,&textureId); glBindTexture(GL_TEXTURE_2D, textureId); m_glxBindTexImageEXT(mDisplay,glxPixmap,GLX_FRONT_EXT, 0); //Do we need to change the api so that we do bind and release in the painevent? //The specification states that when deleting the texture the color buffer is deleted // m_glxReleaseTexImageEXT(mDisplay,glxPixmap,GLX_FRONT_EXT); return textureId; } bool XCompositeGLXIntegration::isYInverted(wl_buffer *buffer) const { XCompositeBuffer *compositorBuffer = Wayland::wayland_cast<XCompositeBuffer *>(buffer); return compositorBuffer->isYInverted(); } <commit_msg>Make glx backend compiling again after qtbase broke the includes<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "xcompositeglxintegration.h" #include "waylandobject.h" #include "wayland_wrapper/wlcompositor.h" #include "wayland-xcomposite-server-protocol.h" #include <QtGui/QPlatformNativeInterface> #include <QtGui/QPlatformIntegration> #include <QtGui/QOpenGLContext> #include "xcompositebuffer.h" #include "xcompositehandler.h" #include <X11/extensions/Xcomposite.h> #include <QtCore/QDebug> QVector<int> qglx_buildSpec() { QVector<int> spec(48); int i = 0; spec[i++] = GLX_LEVEL; spec[i++] = 0; spec[i++] = GLX_DRAWABLE_TYPE; spec[i++] = GLX_PIXMAP_BIT | GLX_WINDOW_BIT; spec[i++] = GLX_BIND_TO_TEXTURE_TARGETS_EXT; spec[i++] = GLX_TEXTURE_2D_BIT_EXT; spec[i++] = GLX_BIND_TO_TEXTURE_RGB_EXT; spec[i++] = TRUE; spec[i++] = 0; return spec; } struct wl_xcomposite_interface XCompositeHandler::xcomposite_interface = { XCompositeHandler::create_buffer }; GraphicsHardwareIntegration *GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor) { return new XCompositeGLXIntegration(compositor); } XCompositeGLXIntegration::XCompositeGLXIntegration(WaylandCompositor *compositor) : GraphicsHardwareIntegration(compositor) , mDisplay(0) , mHandler(0) { QPlatformNativeInterface *nativeInterface = QGuiApplicationPrivate::platformIntegration()->nativeInterface(); if (nativeInterface) { mDisplay = static_cast<Display *>(nativeInterface->nativeResourceForWindow("Display",m_compositor->window())); if (!mDisplay) qFatal("could not retireve Display from platform integration"); } else { qFatal("Platform integration doesn't have native interface"); } mScreen = XDefaultScreen(mDisplay); } XCompositeGLXIntegration::~XCompositeGLXIntegration() { delete mHandler; } void XCompositeGLXIntegration::initializeHardware(Wayland::Display *waylandDisplay) { mHandler = new XCompositeHandler(m_compositor->handle(),mDisplay,m_compositor->window()); wl_display_add_global(waylandDisplay->handle(),&wl_xcomposite_interface,mHandler,XCompositeHandler::xcomposite_bind_func); QOpenGLContext *glContext = new QOpenGLContext(); glContext->create(); m_glxBindTexImageEXT = reinterpret_cast<PFNGLXBINDTEXIMAGEEXTPROC>(glContext->getProcAddress("glXBindTexImageEXT")); if (!m_glxBindTexImageEXT) { qDebug() << "Did not find glxBindTexImageExt, everything will FAIL!"; } m_glxReleaseTexImageEXT = reinterpret_cast<PFNGLXRELEASETEXIMAGEEXTPROC>(glContext->getProcAddress("glXReleaseTexImageEXT")); if (!m_glxReleaseTexImageEXT) { qDebug() << "Did not find glxReleaseTexImageExt"; } delete glContext; } GLuint XCompositeGLXIntegration::createTextureFromBuffer(wl_buffer *buffer, QOpenGLContext *) { XCompositeBuffer *compositorBuffer = Wayland::wayland_cast<XCompositeBuffer *>(buffer); Pixmap pixmap = XCompositeNameWindowPixmap(mDisplay, compositorBuffer->window()); QVector<int> glxConfigSpec = qglx_buildSpec(); int numberOfConfigs; GLXFBConfig *configs = glXChooseFBConfig(mDisplay,mScreen,glxConfigSpec.constData(),&numberOfConfigs); QVector<int> attribList; attribList.append(GLX_TEXTURE_FORMAT_EXT); attribList.append(GLX_TEXTURE_FORMAT_RGB_EXT); attribList.append(GLX_TEXTURE_TARGET_EXT); attribList.append(GLX_TEXTURE_2D_EXT); attribList.append(0); GLXPixmap glxPixmap = glXCreatePixmap(mDisplay,*configs,pixmap,attribList.constData()); uint inverted = 0; glXQueryDrawable(mDisplay, glxPixmap, GLX_Y_INVERTED_EXT,&inverted); compositorBuffer->setInvertedY(!inverted); XFree(configs); GLuint textureId; glGenTextures(1,&textureId); glBindTexture(GL_TEXTURE_2D, textureId); m_glxBindTexImageEXT(mDisplay,glxPixmap,GLX_FRONT_EXT, 0); //Do we need to change the api so that we do bind and release in the painevent? //The specification states that when deleting the texture the color buffer is deleted // m_glxReleaseTexImageEXT(mDisplay,glxPixmap,GLX_FRONT_EXT); return textureId; } bool XCompositeGLXIntegration::isYInverted(wl_buffer *buffer) const { XCompositeBuffer *compositorBuffer = Wayland::wayland_cast<XCompositeBuffer *>(buffer); return compositorBuffer->isYInverted(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef STORED_VALUE_H #define STORED_VALUE_H 1 #include "locks.hh" extern "C" { extern rel_time_t (*ep_current_time)(); } // Forward declaration for StoredValue class HashTable; class StoredValue { public: StoredValue(const Item &itm, StoredValue *n) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.getNBytes()), flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n), cas(itm.getCas()) { markDirty(); } StoredValue(const Item &itm, StoredValue *n, bool setDirty) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.getNBytes()), flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n), cas(itm.getCas()) { if (setDirty) { markDirty(); } else { markClean(NULL, NULL); } } ~StoredValue() { } void markDirty() { data_age = ep_current_time(); if (!isDirty()) { dirtied = data_age; } } void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) { data_age = dataAge; dirtied = dirtyAge; } // returns time this object was dirtied. void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) { if (dirtyAge) { *dirtyAge = dirtied; } if (dataAge) { *dataAge = data_age; } dirtied = 0; data_age = 0; } bool isDirty() const { return dirtied != 0; } bool isClean() const { return dirtied == 0; } const std::string &getKey() const { return key; } const std::string &getValue() const { return value; } rel_time_t getExptime() const { return exptime; } uint32_t getFlags() const { return flags; } void setValue(const char *v, const size_t nv, uint32_t newFlags, rel_time_t newExp, uint64_t theCas) { cas = theCas; flags = newFlags; exptime = newExp; value.assign(v, nv); markDirty(); } uint64_t getCas() const { return cas; } private: friend class HashTable; std::string key; std::string value; uint32_t flags; rel_time_t exptime; rel_time_t dirtied; rel_time_t data_age; StoredValue *next; uint64_t cas; DISALLOW_COPY_AND_ASSIGN(StoredValue); }; typedef enum { NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY } mutation_type_t; class HashTableVisitor { public: virtual ~HashTableVisitor() {} virtual void visit(StoredValue *v) = 0; }; class HashTable { public: // Construct with number of buckets and locks. HashTable(size_t s = 196613, size_t l = 193) { size = s; n_locks = l; active = true; values = (StoredValue**)calloc(s, sizeof(StoredValue**)); mutexes = new Mutex[l]; } ~HashTable() { clear(); delete []mutexes; free(values); } void clear() { assert(active); for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); while (values[i]) { StoredValue *v = values[i]; values[i] = v->next; delete v; } } } StoredValue *find(std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); return unlocked_find(key, bucket_num); } mutation_type_t set(const Item &val, bool preserveCas = false) { assert(active); mutation_type_t rv = NOT_FOUND; int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); Item &itm = const_cast<Item&>(val); if (v) { if (val.getCas() != 0 && val.getCas() != v->getCas()) { return INVALID_CAS; } if (!preserveCas) { itm.setCas(); } rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY; v->setValue(itm.getData(), itm.getNBytes(), itm.getFlags(), itm.getExptime(), itm.getCas()); } else { if (!preserveCas) { if (itm.getCas() != 0) { return INVALID_CAS; } itm.setCas(); } v = new StoredValue(itm, values[bucket_num]); values[bucket_num] = v; } return rv; } bool add(const Item &val, bool isDirty, bool preserveCas = false) { assert(active); int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); if (v) { return false; } else { Item &itm = const_cast<Item&>(val); if (!preserveCas) { itm.setCas(); } v = new StoredValue(itm, values[bucket_num], isDirty); values[bucket_num] = v; } return true; } bool add(const Item &val) { return add(val, true); } StoredValue *unlocked_find(const std::string &key, int bucket_num) { StoredValue *v = values[bucket_num]; while (v) { if (key.compare(v->key) == 0) { return v; } v = v->next; } return NULL; } inline int bucket(const std::string &key) { assert(active); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return abs(h) % (int)size; } // Get the mutex for a bucket (for doing your own lock management) inline Mutex &getMutex(int bucket_num) { assert(active); assert(bucket_num < (int)size); assert(bucket_num >= 0); int lock_num = bucket_num % (int)n_locks; assert(lock_num < (int)n_locks); assert(lock_num >= 0); return mutexes[lock_num]; } // True if it existed bool del(const std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); StoredValue *v = values[bucket_num]; // Special case empty bucket. if (!v) { return false; } // Special case the first one if (key.compare(v->key) == 0) { values[bucket_num] = v->next; delete v; return true; } while (v->next) { if (key.compare(v->next->key) == 0) { StoredValue *tmp = v->next; v->next = v->next->next; delete tmp; return true; } else { v = v->next; } } return false; } void visit(HashTableVisitor &visitor) { for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); StoredValue *v = values[i]; while (v) { visitor.visit(v); v = v->next; } } } private: size_t size; size_t n_locks; bool active; StoredValue **values; Mutex *mutexes; DISALLOW_COPY_AND_ASSIGN(HashTable); }; #endif /* STORED_VALUE_H */ <commit_msg>Remove preserveCas argument to set and add.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef STORED_VALUE_H #define STORED_VALUE_H 1 #include "locks.hh" extern "C" { extern rel_time_t (*ep_current_time)(); } // Forward declaration for StoredValue class HashTable; class StoredValue { public: StoredValue(const Item &itm, StoredValue *n) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.getNBytes()), flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n), cas(itm.getCas()) { markDirty(); } StoredValue(const Item &itm, StoredValue *n, bool setDirty) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.getNBytes()), flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n), cas(itm.getCas()) { if (setDirty) { markDirty(); } else { markClean(NULL, NULL); } } ~StoredValue() { } void markDirty() { data_age = ep_current_time(); if (!isDirty()) { dirtied = data_age; } } void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) { data_age = dataAge; dirtied = dirtyAge; } // returns time this object was dirtied. void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) { if (dirtyAge) { *dirtyAge = dirtied; } if (dataAge) { *dataAge = data_age; } dirtied = 0; data_age = 0; } bool isDirty() const { return dirtied != 0; } bool isClean() const { return dirtied == 0; } const std::string &getKey() const { return key; } const std::string &getValue() const { return value; } rel_time_t getExptime() const { return exptime; } uint32_t getFlags() const { return flags; } void setValue(const char *v, const size_t nv, uint32_t newFlags, rel_time_t newExp, uint64_t theCas) { cas = theCas; flags = newFlags; exptime = newExp; value.assign(v, nv); markDirty(); } uint64_t getCas() const { return cas; } private: friend class HashTable; std::string key; std::string value; uint32_t flags; rel_time_t exptime; rel_time_t dirtied; rel_time_t data_age; StoredValue *next; uint64_t cas; DISALLOW_COPY_AND_ASSIGN(StoredValue); }; typedef enum { NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY } mutation_type_t; class HashTableVisitor { public: virtual ~HashTableVisitor() {} virtual void visit(StoredValue *v) = 0; }; class HashTable { public: // Construct with number of buckets and locks. HashTable(size_t s = 196613, size_t l = 193) { size = s; n_locks = l; active = true; values = (StoredValue**)calloc(s, sizeof(StoredValue**)); mutexes = new Mutex[l]; } ~HashTable() { clear(); delete []mutexes; free(values); } void clear() { assert(active); for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); while (values[i]) { StoredValue *v = values[i]; values[i] = v->next; delete v; } } } StoredValue *find(std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); return unlocked_find(key, bucket_num); } mutation_type_t set(const Item &val) { assert(active); mutation_type_t rv = NOT_FOUND; int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); Item &itm = const_cast<Item&>(val); if (v) { if (val.getCas() != 0 && val.getCas() != v->getCas()) { return INVALID_CAS; } itm.setCas(); rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY; v->setValue(itm.getData(), itm.getNBytes(), itm.getFlags(), itm.getExptime(), itm.getCas()); } else { if (itm.getCas() != 0) { return INVALID_CAS; } v = new StoredValue(itm, values[bucket_num]); values[bucket_num] = v; } return rv; } bool add(const Item &val, bool isDirty = true) { assert(active); int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); if (v) { return false; } else { Item &itm = const_cast<Item&>(val); itm.setCas(); v = new StoredValue(itm, values[bucket_num], isDirty); values[bucket_num] = v; } return true; } StoredValue *unlocked_find(const std::string &key, int bucket_num) { StoredValue *v = values[bucket_num]; while (v) { if (key.compare(v->key) == 0) { return v; } v = v->next; } return NULL; } inline int bucket(const std::string &key) { assert(active); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return abs(h) % (int)size; } // Get the mutex for a bucket (for doing your own lock management) inline Mutex &getMutex(int bucket_num) { assert(active); assert(bucket_num < (int)size); assert(bucket_num >= 0); int lock_num = bucket_num % (int)n_locks; assert(lock_num < (int)n_locks); assert(lock_num >= 0); return mutexes[lock_num]; } // True if it existed bool del(const std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); StoredValue *v = values[bucket_num]; // Special case empty bucket. if (!v) { return false; } // Special case the first one if (key.compare(v->key) == 0) { values[bucket_num] = v->next; delete v; return true; } while (v->next) { if (key.compare(v->next->key) == 0) { StoredValue *tmp = v->next; v->next = v->next->next; delete tmp; return true; } else { v = v->next; } } return false; } void visit(HashTableVisitor &visitor) { for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); StoredValue *v = values[i]; while (v) { visitor.visit(v); v = v->next; } } } private: size_t size; size_t n_locks; bool active; StoredValue **values; Mutex *mutexes; DISALLOW_COPY_AND_ASSIGN(HashTable); }; #endif /* STORED_VALUE_H */ <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konrad Enzensberger <e.konrad@mpegcode.com> // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "FileReaderPositionProviderPlugin.h" #include <QtCore/QTimer> #include <QtCore/QFile> #include "GeoDataCoordinates.h" #include "GeoDataParser.h" #include "GeoDataDocument.h" #include "GeoDataTypes.h" #include "GeoDataData.h" #include "GeoDataFolder.h" #include "GeoDataPlacemark.h" #include "GeoDataLineString.h" #include "GeoDataLinearRing.h" #include "GeoDataIconStyle.h" #include "MarbleDirs.h" #include "MarbleDebug.h" namespace Marble { class FileReaderPositionProviderPluginPrivate { public: FileReaderPositionProviderPluginPrivate(); ~FileReaderPositionProviderPluginPrivate(); void importKmlFromData(); void createSimulationPlacemarks( GeoDataContainer *container ); int m_currentIndex; PositionProviderStatus m_status; GeoDataLineString m_lineString; }; FileReaderPositionProviderPluginPrivate::FileReaderPositionProviderPluginPrivate() : m_currentIndex( 0 ), m_status( PositionProviderStatusAcquiring ) { // nothing to do } FileReaderPositionProviderPluginPrivate::~FileReaderPositionProviderPluginPrivate() { m_lineString.clear(); } void FileReaderPositionProviderPluginPrivate::importKmlFromData() { GeoDataParser parser( GeoData_KML ); QString filename = MarbleDirs::path( "routing" ); filename += "/route.kml"; QFile file( filename ); if ( !file.exists() ) { mDebug() << "The GPS file reader plugin expects routing/route.kml to exist in the local marble dir."; mDebug() << "Create a route and exit Marble to have it created automatically."; return; } // Open file in right mode file.open( QIODevice::ReadOnly ); if ( !parser.read( &file ) ) { mDebug() << "Could not import kml file. No position updates will happen."; return; } GeoDocument* doc = parser.releaseDocument(); if ( doc ) { GeoDataDocument* document = dynamic_cast<GeoDataDocument*>( doc ); if ( document && document->size() > 0 ) { document->setDocumentRole( UserDocument ); document->setFileName( filename ); createSimulationPlacemarks( dynamic_cast<GeoDataDocument*>( &document->last() ) ); } } file.close(); } void FileReaderPositionProviderPluginPrivate::createSimulationPlacemarks( GeoDataContainer *container ) { if ( !container ) { return; } m_lineString.clear(); QVector<GeoDataFolder*> folders = container->folderList(); foreach( const GeoDataFolder *folder, folders ) { foreach( const GeoDataPlacemark *placemark, folder->placemarkList() ) { GeoDataGeometry* geometry = placemark->geometry(); GeoDataLineString* lineString = dynamic_cast<GeoDataLineString*>( geometry ); if ( lineString ) { m_lineString = *lineString; return; } } } foreach( const GeoDataPlacemark *placemark, container->placemarkList() ) { GeoDataGeometry* geometry = placemark->geometry(); GeoDataLineString* lineString = dynamic_cast<GeoDataLineString*>( geometry ); if ( lineString ) { m_lineString = *lineString; return; } } } QString FileReaderPositionProviderPlugin::name() const { return tr( "File Reader Position ProviderPlugin" ); } QString FileReaderPositionProviderPlugin::nameId() const { return "FileReaderPositionProviderPlugin"; } QString FileReaderPositionProviderPlugin::guiString() const { return tr( "GPS Position Simulation (File Reader)" ); } QString FileReaderPositionProviderPlugin::version() const { return "1.0"; } QString FileReaderPositionProviderPlugin::description() const { return tr( "Reports the GPS position from a previously calculated route." ); } QString FileReaderPositionProviderPlugin::copyrightYears() const { return "2011"; } QList<PluginAuthor> FileReaderPositionProviderPlugin::pluginAuthors() const { return QList<PluginAuthor>() << PluginAuthor( "Konrad Enzensberger", "e.konrad@mpegcode.com" ) << PluginAuthor( QString::fromUtf8( "Dennis Nienhüser" ), "earthwings@gentoo.org" ); } QIcon FileReaderPositionProviderPlugin::icon() const { return QIcon(); } PositionProviderPlugin* FileReaderPositionProviderPlugin::newInstance() const { return new FileReaderPositionProviderPlugin; } PositionProviderStatus FileReaderPositionProviderPlugin::status() const { return d->m_status; } GeoDataCoordinates FileReaderPositionProviderPlugin::position() const { return d->m_lineString.at( d->m_currentIndex ); } GeoDataAccuracy FileReaderPositionProviderPlugin::accuracy() const { GeoDataAccuracy result; // faked values result.level = GeoDataAccuracy::Detailed; result.horizontal = 10.0; result.vertical = 10.0; return result; } FileReaderPositionProviderPlugin::FileReaderPositionProviderPlugin() : d( new FileReaderPositionProviderPluginPrivate ) { // nothing to do } FileReaderPositionProviderPlugin::~FileReaderPositionProviderPlugin() { delete d; } void FileReaderPositionProviderPlugin::initialize() { d->m_status = PositionProviderStatusAcquiring; d->m_currentIndex = 0; d->importKmlFromData(); QTimer::singleShot( 1000, this, SLOT( update() ) ); } bool FileReaderPositionProviderPlugin::isInitialized() const { return ( d->m_lineString.size() > 0 ); } qreal FileReaderPositionProviderPlugin::speed() const { /** @todo: calculate speed */ return 0.0; } qreal FileReaderPositionProviderPlugin::direction() const { /** @todo: calculate direction */ return 0.0; } QDateTime FileReaderPositionProviderPlugin::timestamp() const { return QDateTime::currentDateTime(); } void FileReaderPositionProviderPlugin::update() { PositionProviderStatus newStatus = PositionProviderStatusAvailable; if ( d->m_currentIndex >= 0 && d->m_currentIndex < d->m_lineString.size() ) { if ( newStatus != d->m_status ) { d->m_status = newStatus; emit statusChanged( newStatus ); } if ( newStatus == PositionProviderStatusAvailable ) { emit positionChanged( position(), accuracy() ); } ++d->m_currentIndex; if( d->m_currentIndex < d->m_lineString.size() ) { QTimer::singleShot( 1000, this, SLOT( update() ) ); } } if ( !d->m_lineString.isEmpty() && d->m_currentIndex >= d->m_lineString.size() ) { // Repeat from start d->m_currentIndex = 0; update(); } } } // namespace Marble Q_EXPORT_PLUGIN2( FileReaderPositionProviderPlugin, Marble::FileReaderPositionProviderPlugin ) #include "FileReaderPositionProviderPlugin.moc" <commit_msg>have FileReaderPositionProviderPlugin make use of AlternativeRoutingModel's current route<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konrad Enzensberger <e.konrad@mpegcode.com> // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // Copyright 2012 Bernhard Beschow <bbeschow@cs.tu-berlin.de> // #include "FileReaderPositionProviderPlugin.h" #include <QtCore/QTimer> #include "GeoDataCoordinates.h" #include "GeoDataDocument.h" #include "GeoDataTypes.h" #include "GeoDataData.h" #include "GeoDataFolder.h" #include "GeoDataPlacemark.h" #include "GeoDataLineString.h" #include "GeoDataLinearRing.h" #include "GeoDataIconStyle.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include "routing/AlternativeRoutesModel.h" #include "routing/RoutingManager.h" namespace Marble { class FileReaderPositionProviderPluginPrivate { public: FileReaderPositionProviderPluginPrivate(); ~FileReaderPositionProviderPluginPrivate(); int m_currentIndex; PositionProviderStatus m_status; GeoDataLineString m_lineString; }; FileReaderPositionProviderPluginPrivate::FileReaderPositionProviderPluginPrivate() : m_currentIndex( -1 ), m_status( PositionProviderStatusUnavailable ) { // nothing to do } FileReaderPositionProviderPluginPrivate::~FileReaderPositionProviderPluginPrivate() { m_lineString.clear(); } QString FileReaderPositionProviderPlugin::name() const { return tr( "File Reader Position ProviderPlugin" ); } QString FileReaderPositionProviderPlugin::nameId() const { return "FileReaderPositionProviderPlugin"; } QString FileReaderPositionProviderPlugin::guiString() const { return tr( "GPS Position Simulation (File Reader)" ); } QString FileReaderPositionProviderPlugin::version() const { return "1.0"; } QString FileReaderPositionProviderPlugin::description() const { return tr( "Reports the GPS position from a previously calculated route." ); } QString FileReaderPositionProviderPlugin::copyrightYears() const { return "2011"; } QList<PluginAuthor> FileReaderPositionProviderPlugin::pluginAuthors() const { return QList<PluginAuthor>() << PluginAuthor( "Konrad Enzensberger", "e.konrad@mpegcode.com" ) << PluginAuthor( QString::fromUtf8( "Dennis Nienhüser" ), "earthwings@gentoo.org" ); } QIcon FileReaderPositionProviderPlugin::icon() const { return QIcon(); } PositionProviderPlugin* FileReaderPositionProviderPlugin::newInstance() const { return new FileReaderPositionProviderPlugin; } PositionProviderStatus FileReaderPositionProviderPlugin::status() const { return d->m_status; } GeoDataCoordinates FileReaderPositionProviderPlugin::position() const { return d->m_lineString.at( d->m_currentIndex ); } GeoDataAccuracy FileReaderPositionProviderPlugin::accuracy() const { GeoDataAccuracy result; // faked values result.level = GeoDataAccuracy::Detailed; result.horizontal = 10.0; result.vertical = 10.0; return result; } FileReaderPositionProviderPlugin::FileReaderPositionProviderPlugin() : d( new FileReaderPositionProviderPluginPrivate ) { // nothing to do } FileReaderPositionProviderPlugin::~FileReaderPositionProviderPlugin() { delete d; } void FileReaderPositionProviderPlugin::initialize() { d->m_currentIndex = 0; d->m_lineString.clear(); GeoDataDocument* document = const_cast<MarbleModel *>( marbleModel() )->routingManager()->alternativeRoutesModel()->currentRoute(); if ( document && document->size() > 0 ) { foreach( const GeoDataPlacemark *placemark, document->placemarkList() ) { GeoDataGeometry* geometry = placemark->geometry(); GeoDataLineString* lineString = dynamic_cast<GeoDataLineString*>( geometry ); if ( lineString ) { d->m_lineString << *lineString; } } } d->m_status = d->m_lineString.isEmpty() ? PositionProviderStatusUnavailable : PositionProviderStatusAcquiring; QTimer::singleShot( 1000, this, SLOT( update() ) ); } bool FileReaderPositionProviderPlugin::isInitialized() const { return ( d->m_currentIndex >= 0 ); } qreal FileReaderPositionProviderPlugin::speed() const { /** @todo: calculate speed */ return 0.0; } qreal FileReaderPositionProviderPlugin::direction() const { /** @todo: calculate direction */ return 0.0; } QDateTime FileReaderPositionProviderPlugin::timestamp() const { return QDateTime::currentDateTime(); } void FileReaderPositionProviderPlugin::update() { PositionProviderStatus newStatus = PositionProviderStatusAvailable; if ( d->m_currentIndex >= 0 && d->m_currentIndex < d->m_lineString.size() ) { if ( newStatus != d->m_status ) { d->m_status = newStatus; emit statusChanged( newStatus ); } if ( newStatus == PositionProviderStatusAvailable ) { emit positionChanged( position(), accuracy() ); } ++d->m_currentIndex; if( d->m_currentIndex < d->m_lineString.size() ) { QTimer::singleShot( 1000, this, SLOT( update() ) ); } } if ( !d->m_lineString.isEmpty() && d->m_currentIndex >= d->m_lineString.size() ) { // Repeat from start d->m_currentIndex = 0; update(); } } } // namespace Marble Q_EXPORT_PLUGIN2( FileReaderPositionProviderPlugin, Marble::FileReaderPositionProviderPlugin ) #include "FileReaderPositionProviderPlugin.moc" <|endoftext|>
<commit_before>//============================================================================== // Single cell simulation view //============================================================================== #include "cellmlfile.h" #include "cellmlfilemanager.h" #include "cellmlfileruntime.h" #include "singlecellsimulationview.h" #include "toolbar.h" //============================================================================== #include "ui_singlecellsimulationview.h" //============================================================================== #include <QFileInfo> #include <QListView> #include <QProgressBar> #include <QSplitter> #include <QTime> //============================================================================== #include "qwt_plot_grid.h" #include "qwt_plot_curve.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulation { //============================================================================== GraphPanel::GraphPanel(QWidget *pParent) : QwtPlot(pParent) { // Customise our simulation view widget setCanvasBackground(Qt::white); // Remove the canvas' border as it otherwise looks odd, not to say ugly, // with one setCanvasLineWidth(0); // Add a grid to our simulation view widget QwtPlotGrid *grid = new QwtPlotGrid; grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(this); } //============================================================================== GraphPanel::~GraphPanel() { // Delete some internal objects resetCurves(); } //============================================================================== void GraphPanel::addCurve(QwtPlotCurve *pCurve, const bool &pRefresh) { // Add the curve to our list of curves mCurves.append(pCurve); // Refresh the graph panel, if needed if (pRefresh) replot(); } //============================================================================== void GraphPanel::resetCurves() { // Remove any existing curve foreach (QwtPlotCurve *curve, mCurves) { curve->detach(); delete curve; } mCurves.clear(); // Refresh the graph panel replot(); } //============================================================================== SingleCellSimulationView::SingleCellSimulationView(QWidget *pParent) : QWidget(pParent), mUi(new Ui::SingleCellSimulationView) { // Set up the UI mUi->setupUi(this); // Create a toolbar with different buttons Core::ToolBar *toolbar = new Core::ToolBar(this); toolbar->addAction(mUi->action); mUi->verticalLayout->addWidget(toolbar); mUi->verticalLayout->addWidget(newSeparatingLine()); // Create our vertical splitter QSplitter *mainVerticalSplitter = new QSplitter(Qt::Vertical, this); // Create a splitter for our graph panels and add a graph panel to it mGraphPanels = new QSplitter(Qt::Vertical, this); mGraphPanel = addGraphPanel(); mGraphPanels->addWidget(mGraphPanel); mGraphPanels->addWidget(addGraphPanel()); //---GRY--- These two graph mGraphPanels->addWidget(addGraphPanel()); // panels are just for // testing purposes... // Create a simulation output widget with a vertical layout on which we put // a separating line and our simulation output list view // Note: the separating line is because we remove, for aesthetical reasons, // the border of our simulation output list view... QWidget *simulationOutputWidget = new QWidget(this); QVBoxLayout *simulationOutputVerticalLayout= new QVBoxLayout(this); simulationOutputVerticalLayout->setContentsMargins(0, 0, 0, 0); simulationOutputVerticalLayout->setSpacing(0); simulationOutputWidget->setLayout(simulationOutputVerticalLayout); mSimulationOutput = new QListView(this); mSimulationOutput->setFrameStyle(QFrame::NoFrame); simulationOutputVerticalLayout->addWidget(newSeparatingLine()); simulationOutputVerticalLayout->addWidget(mSimulationOutput); // Populate our splitter and add it to our view mainVerticalSplitter->addWidget(mGraphPanels); mainVerticalSplitter->addWidget(simulationOutputWidget); mUi->verticalLayout->addWidget(mainVerticalSplitter); // Create our simulation progress widget mProgressBar = new QProgressBar(this); mUi->verticalLayout->addWidget(newSeparatingLine()); mUi->verticalLayout->addWidget(mProgressBar); } //============================================================================== SingleCellSimulationView::~SingleCellSimulationView() { // Delete the UI delete mUi; } //============================================================================== void SingleCellSimulationView::retranslateUi() { // Retranslate the whole view mUi->retranslateUi(this); } //============================================================================== GraphPanel * SingleCellSimulationView::addGraphPanel() { // Add a graph panel to our simulation view return new GraphPanel(this); } //============================================================================== QFrame * SingleCellSimulationView::newSeparatingLine() { // Return a separating line widget QFrame *res = new QFrame(this); res->setFrameShape(QFrame::HLine); res->setFrameShadow(QFrame::Sunken); return res; } //============================================================================== void SingleCellSimulationView::updateWith(const QString &pFileName) { qDebug("======================================="); qDebug("%s:", qPrintable(pFileName)); // Get a runtime for the file CellMLSupport::CellmlFileRuntime *cellmlFileRuntime = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)->runtime(); if (cellmlFileRuntime->isValid()) { qDebug(" - The CellML file's runtime was properly generated."); qDebug(" [Information] Model type = %s", (cellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode)?"ODE":"DAE"); } else { qDebug(" - The CellML file's runtime was NOT properly generated:"); foreach (const CellMLSupport::CellmlFileIssue &issue, cellmlFileRuntime->issues()) qDebug(" [%s] %s", (issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning", qPrintable(issue.formattedMessage())); } // Remove any existing curve mGraphPanel->resetCurves(); // Compute the model, if supported enum Model { Unknown, VanDerPol1928, Hodgkin1952, Noble1962, Noble1984, Noble1991, Noble1998, Zhang2000, Mitchell2003 } model; QString fileBaseName = QFileInfo(pFileName).baseName(); if (!fileBaseName.compare("van_der_pol_model_1928")) model = VanDerPol1928; else if ( !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952") || !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_modified") || !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_original")) model = Hodgkin1952; else if (!fileBaseName.compare("noble_model_1962")) model = Noble1962; else if (!fileBaseName.compare("noble_noble_SAN_model_1984")) model = Noble1984; else if (!fileBaseName.compare("noble_model_1991")) model = Noble1991; else if (!fileBaseName.compare("noble_model_1998")) model = Noble1998; else if ( !fileBaseName.compare("zhang_SAN_model_2000_0D_capable") || !fileBaseName.compare("zhang_SAN_model_2000_1D_capable") || !fileBaseName.compare("zhang_SAN_model_2000_all") || !fileBaseName.compare("zhang_SAN_model_2000_published")) model = Zhang2000; else if (!fileBaseName.compare("mitchell_schaeffer_2003")) model = Mitchell2003; else model = Unknown; if (cellmlFileRuntime->isValid() && (model != Unknown)) { typedef QVector<double> Doubles; int statesCount = cellmlFileRuntime->statesCount(); Doubles xData; Doubles yData[statesCount]; double voi = 0; // ms double voiStep; // ms double voiMax; // ms double constants[cellmlFileRuntime->constantsCount()]; double rates[cellmlFileRuntime->ratesCount()]; double states[statesCount]; double algebraic[cellmlFileRuntime->algebraicCount()]; int voiCount = 0; int voiOutputCount; // ms switch (model) { case Hodgkin1952: voiStep = 0.01; // ms voiMax = 50; // ms voiOutputCount = 10; break; case Noble1962: case Mitchell2003: voiStep = 0.01; // ms voiMax = 1000; // ms voiOutputCount = 100; break; case Noble1984: case Noble1991: case Noble1998: case Zhang2000: voiStep = 0.00001; // s voiMax = 1; // s voiOutputCount = 100; break; default: // van der Pol 1928 voiStep = 0.01; // s voiMax = 10; // s voiOutputCount = 1; } CellMLSupport::CellmlFileRuntimeOdeFunctions odeFunctions = cellmlFileRuntime->odeFunctions(); // Initialise the constants and compute the rates and variables QTime time; time.start(); odeFunctions.initializeConstants(constants, rates, states); odeFunctions.computeRates(voi, constants, rates, states, algebraic); odeFunctions.computeVariables(voi, constants, rates, states, algebraic); do { // Output the current data, if needed if(voiCount % voiOutputCount == 0) { xData.append(voi); for (int i = 0; i < statesCount; ++i) yData[i].append(states[i]); } // Compute the rates and variables odeFunctions.computeRates(voi, constants, rates, states, algebraic); odeFunctions.computeVariables(voi, constants, rates, states, algebraic); // Go to the next voiStep and integrate the states voi = ++voiCount*voiStep; for (int i = 0; i < statesCount; ++i) states[i] += voiStep*rates[i]; } while (voi < voiMax); xData.append(voi); for (int i = 0; i < statesCount; ++i) yData[i].append(states[i]); qDebug(" - Simulation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); // Add some curves to our plotting area for (int i = 0, iMax = (model == VanDerPol1928)?statesCount:1; i < iMax; ++i) { QwtPlotCurve *curve = new QwtPlotCurve(); curve->setRenderHint(QwtPlotItem::RenderAntialiased); curve->setPen(QPen(i%2?Qt::darkBlue:Qt::darkRed)); curve->setSamples(xData, yData[i]); curve->attach(mGraphPanel); // Keep track of the curve mGraphPanel->addCurve(curve, false); } // Make sure that the view is up-to-date mGraphPanel->replot(); } } //============================================================================== } // namespace SingleCellSimulation } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor improvement to our SingleCellSimulation plugin.<commit_after>//============================================================================== // Single cell simulation view //============================================================================== #include "cellmlfile.h" #include "cellmlfilemanager.h" #include "cellmlfileruntime.h" #include "singlecellsimulationview.h" #include "toolbar.h" //============================================================================== #include "ui_singlecellsimulationview.h" //============================================================================== #include <QFileInfo> #include <QListView> #include <QProgressBar> #include <QSplitter> #include <QTime> //============================================================================== #include "qwt_plot_grid.h" #include "qwt_plot_curve.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulation { //============================================================================== GraphPanel::GraphPanel(QWidget *pParent) : QwtPlot(pParent) { // Allow the graph panel to be of any size setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); // Have a white background by default setCanvasBackground(Qt::white); // Remove the canvas' border as it otherwise looks odd, not to say ugly, // with one setCanvasLineWidth(0); // Add a grid to our graph panel QwtPlotGrid *grid = new QwtPlotGrid; grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(this); } //============================================================================== GraphPanel::~GraphPanel() { // Delete some internal objects resetCurves(); } //============================================================================== void GraphPanel::addCurve(QwtPlotCurve *pCurve, const bool &pRefresh) { // Add the curve to our list of curves mCurves.append(pCurve); // Refresh the graph panel, if needed if (pRefresh) replot(); } //============================================================================== void GraphPanel::resetCurves() { // Remove any existing curve foreach (QwtPlotCurve *curve, mCurves) { curve->detach(); delete curve; } mCurves.clear(); // Refresh the graph panel replot(); } //============================================================================== SingleCellSimulationView::SingleCellSimulationView(QWidget *pParent) : QWidget(pParent), mUi(new Ui::SingleCellSimulationView) { // Set up the UI mUi->setupUi(this); // Create a toolbar with different buttons Core::ToolBar *toolbar = new Core::ToolBar(this); toolbar->addAction(mUi->action); mUi->verticalLayout->addWidget(toolbar); mUi->verticalLayout->addWidget(newSeparatingLine()); // Create our vertical splitter QSplitter *mainVerticalSplitter = new QSplitter(Qt::Vertical, this); // Create a splitter for our graph panels and add a graph panel to it mGraphPanels = new QSplitter(Qt::Vertical, this); mGraphPanel = addGraphPanel(); mGraphPanels->addWidget(mGraphPanel); mGraphPanels->addWidget(addGraphPanel()); //---GRY--- These two graph mGraphPanels->addWidget(addGraphPanel()); // panels are just for // testing purposes... // Create a simulation output widget with a vertical layout on which we put // a separating line and our simulation output list view // Note: the separating line is because we remove, for aesthetical reasons, // the border of our simulation output list view... QWidget *simulationOutputWidget = new QWidget(this); QVBoxLayout *simulationOutputVerticalLayout= new QVBoxLayout(simulationOutputWidget); simulationOutputVerticalLayout->setContentsMargins(0, 0, 0, 0); simulationOutputVerticalLayout->setSpacing(0); simulationOutputWidget->setLayout(simulationOutputVerticalLayout); mSimulationOutput = new QListView(this); mSimulationOutput->setFrameStyle(QFrame::NoFrame); simulationOutputVerticalLayout->addWidget(newSeparatingLine()); simulationOutputVerticalLayout->addWidget(mSimulationOutput); // Populate our splitter and add it to our view mainVerticalSplitter->addWidget(mGraphPanels); mainVerticalSplitter->addWidget(simulationOutputWidget); mUi->verticalLayout->addWidget(mainVerticalSplitter); // Create our simulation progress widget mProgressBar = new QProgressBar(this); mProgressBar->setAlignment(Qt::AlignCenter); mUi->verticalLayout->addWidget(newSeparatingLine()); mUi->verticalLayout->addWidget(mProgressBar); } //============================================================================== SingleCellSimulationView::~SingleCellSimulationView() { // Delete the UI delete mUi; } //============================================================================== void SingleCellSimulationView::retranslateUi() { // Retranslate the whole view mUi->retranslateUi(this); } //============================================================================== GraphPanel * SingleCellSimulationView::addGraphPanel() { // Add a graph panel to our simulation view return new GraphPanel(this); } //============================================================================== QFrame * SingleCellSimulationView::newSeparatingLine() { // Return a separating line widget QFrame *res = new QFrame(this); res->setFrameShape(QFrame::HLine); res->setFrameShadow(QFrame::Sunken); return res; } //============================================================================== void SingleCellSimulationView::updateWith(const QString &pFileName) { qDebug("======================================="); qDebug("%s:", qPrintable(pFileName)); // Get a runtime for the file CellMLSupport::CellmlFileRuntime *cellmlFileRuntime = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)->runtime(); if (cellmlFileRuntime->isValid()) { qDebug(" - The CellML file's runtime was properly generated."); qDebug(" [Information] Model type = %s", (cellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode)?"ODE":"DAE"); } else { qDebug(" - The CellML file's runtime was NOT properly generated:"); foreach (const CellMLSupport::CellmlFileIssue &issue, cellmlFileRuntime->issues()) qDebug(" [%s] %s", (issue.type() == CellMLSupport::CellmlFileIssue::Error)?"Error":"Warning", qPrintable(issue.formattedMessage())); } // Remove any existing curve mGraphPanel->resetCurves(); // Compute the model, if supported enum Model { Unknown, VanDerPol1928, Hodgkin1952, Noble1962, Noble1984, Noble1991, Noble1998, Zhang2000, Mitchell2003 } model; QString fileBaseName = QFileInfo(pFileName).baseName(); if (!fileBaseName.compare("van_der_pol_model_1928")) model = VanDerPol1928; else if ( !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952") || !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_modified") || !fileBaseName.compare("hodgkin_huxley_squid_axon_model_1952_original")) model = Hodgkin1952; else if (!fileBaseName.compare("noble_model_1962")) model = Noble1962; else if (!fileBaseName.compare("noble_noble_SAN_model_1984")) model = Noble1984; else if (!fileBaseName.compare("noble_model_1991")) model = Noble1991; else if (!fileBaseName.compare("noble_model_1998")) model = Noble1998; else if ( !fileBaseName.compare("zhang_SAN_model_2000_0D_capable") || !fileBaseName.compare("zhang_SAN_model_2000_1D_capable") || !fileBaseName.compare("zhang_SAN_model_2000_all") || !fileBaseName.compare("zhang_SAN_model_2000_published")) model = Zhang2000; else if (!fileBaseName.compare("mitchell_schaeffer_2003")) model = Mitchell2003; else model = Unknown; if (cellmlFileRuntime->isValid() && (model != Unknown)) { typedef QVector<double> Doubles; int statesCount = cellmlFileRuntime->statesCount(); Doubles xData; Doubles yData[statesCount]; double voi = 0; // ms double voiStep; // ms double voiMax; // ms double constants[cellmlFileRuntime->constantsCount()]; double rates[cellmlFileRuntime->ratesCount()]; double states[statesCount]; double algebraic[cellmlFileRuntime->algebraicCount()]; int voiCount = 0; int voiOutputCount; // ms switch (model) { case Hodgkin1952: voiStep = 0.01; // ms voiMax = 50; // ms voiOutputCount = 10; break; case Noble1962: case Mitchell2003: voiStep = 0.01; // ms voiMax = 1000; // ms voiOutputCount = 100; break; case Noble1984: case Noble1991: case Noble1998: case Zhang2000: voiStep = 0.00001; // s voiMax = 1; // s voiOutputCount = 100; break; default: // van der Pol 1928 voiStep = 0.01; // s voiMax = 10; // s voiOutputCount = 1; } CellMLSupport::CellmlFileRuntimeOdeFunctions odeFunctions = cellmlFileRuntime->odeFunctions(); // Initialise the constants and compute the rates and variables QTime time; time.start(); odeFunctions.initializeConstants(constants, rates, states); odeFunctions.computeRates(voi, constants, rates, states, algebraic); odeFunctions.computeVariables(voi, constants, rates, states, algebraic); do { // Output the current data, if needed if(voiCount % voiOutputCount == 0) { xData.append(voi); for (int i = 0; i < statesCount; ++i) yData[i].append(states[i]); } // Compute the rates and variables odeFunctions.computeRates(voi, constants, rates, states, algebraic); odeFunctions.computeVariables(voi, constants, rates, states, algebraic); // Go to the next voiStep and integrate the states voi = ++voiCount*voiStep; for (int i = 0; i < statesCount; ++i) states[i] += voiStep*rates[i]; } while (voi < voiMax); xData.append(voi); for (int i = 0; i < statesCount; ++i) yData[i].append(states[i]); qDebug(" - Simulation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); // Add some curves to our plotting area for (int i = 0, iMax = (model == VanDerPol1928)?statesCount:1; i < iMax; ++i) { QwtPlotCurve *curve = new QwtPlotCurve(); curve->setRenderHint(QwtPlotItem::RenderAntialiased); curve->setPen(QPen(i%2?Qt::darkBlue:Qt::darkRed)); curve->setSamples(xData, yData[i]); curve->attach(mGraphPanel); // Keep track of the curve mGraphPanel->addCurve(curve, false); } // Make sure that the view is up-to-date mGraphPanel->replot(); } } //============================================================================== } // namespace SingleCellSimulation } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* Copyright (c) 2017-2019 Xavier Leclercq and the wxCharts contributors. 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 "WxMath2DFrame.h" #include <wx/panel.h> #include <wx/sizer.h> #include <wx/charts/wxcharts.h> #include <cmath> const int ID_LineChart = 1; const int ID_StemChart = 2; const int ID_StepChart = 3; const int ID_CustomXAxis = 4; const int ID_CustomYAxis = 5; const int ID_Grid = 6; WxMath2DFrame::WxMath2DFrame(const wxString& title) : wxFrame(NULL, wxID_ANY, title) { m_menubar = new wxMenuBar( 0 ); m_typeMenu = new wxMenu(); wxMenuItem* m_line = new wxMenuItem( m_typeMenu, ID_LineChart, wxString( wxT("Line") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_line ); wxMenuItem* m_stem = new wxMenuItem( m_typeMenu, ID_StemChart, wxString( wxT("Stem") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_stem ); wxMenuItem* m_step = new wxMenuItem( m_typeMenu, ID_StepChart, wxString( wxT("Step") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_step ); m_menubar->Append( m_typeMenu, wxT("ChartType") ); m_axisMenu = new wxMenu(); wxMenuItem* m_customX = new wxMenuItem( m_axisMenu, ID_CustomXAxis, wxString( wxT("CustomX(exp)") ), wxEmptyString, wxITEM_CHECK ); m_axisMenu->Append( m_customX ); wxMenuItem* m_customY = new wxMenuItem( m_axisMenu, ID_CustomYAxis, wxString( wxT("CustomY(exp)") ), wxEmptyString, wxITEM_CHECK ); m_axisMenu->Append( m_customY ); m_menubar->Append( m_axisMenu, wxT("AxisType") ); m_gridMenu = new wxMenu(); wxMenuItem* m_grid = new wxMenuItem( m_gridMenu, ID_Grid, wxString( wxT("Grid") ), wxEmptyString, wxITEM_CHECK ); m_grid->Check( true ); m_gridMenu->Append( m_grid ); m_menubar->Append( m_gridMenu, wxT("Grid") ); this->SetMenuBar( m_menubar ); wxPanel* panel = new wxPanel(this, wxID_ANY); wxMath2DPlotData chartData; wxSharedPtr<wxMath2DPlotOptions> options(new wxMath2DPlotOptions()); options->GetCommonOptions().SetShowTooltips(false); wxVector<wxPoint2DDouble> points; auto pi = 3.1415926535897; auto tstart = -2*pi; for(auto i = 0u; i<100; i++) { auto x = tstart+0.1*i; points.push_back(wxPoint2DDouble(x,cos(x)*sin(x))); } wxMath2DPlotDataset::ptr dataset( new wxMath2DPlotDataset( wxColor(255, 255, 255, 0), wxColor(250, 20, 20, 0x78), wxColor(0, 0, 0, 0xB8), points) ); chartData.AddDataset(dataset); math2dPlotCtrl = new wxMath2DPlotCtrl(panel, wxID_ANY, chartData, options); wxChartGridOptions opt = math2dPlotCtrl->GetGridOptions(); opt.GetHorizontalGridLineOptions().SetMajorGridLineColor(wxColour("Grey")); opt.GetVerticalGridLineOptions().SetMajorGridLineColor(wxColour("Grey")); math2dPlotCtrl->SetGridOptions(opt); wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL); panelSizer->Add(math2dPlotCtrl, 1, wxEXPAND); panel->SetSizer(panelSizer); wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL); topSizer->Add(panel, 1, wxEXPAND); SetSizerAndFit(topSizer); Binds(); } void WxMath2DFrame::Binds() { m_gridMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetGridOptions(); opt.SetShowGridLines(m_gridMenu->IsChecked(ID_Grid)); math2dPlotCtrl->SetGridOptions(opt); }, ID_Grid); m_axisMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetChartOptions(); if (m_axisMenu->IsChecked(ID_CustomXAxis)) opt.SetAxisFuncX([](wxDouble x){return std::exp(x);}); else opt.SetAxisFuncX([](wxDouble x){return x;}); math2dPlotCtrl->SetChartOptions(opt); }, ID_CustomXAxis); m_axisMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetChartOptions(); if (m_axisMenu->IsChecked(ID_CustomYAxis)) opt.SetAxisFuncY([](wxDouble x){return std::exp(x);}); else opt.SetAxisFuncY([](wxDouble x){return x;}); math2dPlotCtrl->SetChartOptions(opt); }, ID_CustomYAxis); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_LINE); }, ID_LineChart); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_STEPPED); }, ID_StepChart); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_STEM); }, ID_StemChart); } <commit_msg>Fix WxMath2D sample compilation<commit_after>/* Copyright (c) 2017-2019 Xavier Leclercq and the wxCharts contributors. 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 "WxMath2DFrame.h" #include <wx/panel.h> #include <wx/sizer.h> #include <wx/charts/wxcharts.h> #include <cmath> const int ID_LineChart = 1; const int ID_StemChart = 2; const int ID_StepChart = 3; const int ID_CustomXAxis = 4; const int ID_CustomYAxis = 5; const int ID_Grid = 6; WxMath2DFrame::WxMath2DFrame(const wxString& title) : wxFrame(NULL, wxID_ANY, title) { m_menubar = new wxMenuBar( 0 ); m_typeMenu = new wxMenu(); wxMenuItem* m_line = new wxMenuItem( m_typeMenu, ID_LineChart, wxString( wxT("Line") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_line ); wxMenuItem* m_stem = new wxMenuItem( m_typeMenu, ID_StemChart, wxString( wxT("Stem") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_stem ); wxMenuItem* m_step = new wxMenuItem( m_typeMenu, ID_StepChart, wxString( wxT("Step") ), wxEmptyString, wxITEM_RADIO ); m_typeMenu->Append( m_step ); m_menubar->Append( m_typeMenu, wxT("ChartType") ); m_axisMenu = new wxMenu(); wxMenuItem* m_customX = new wxMenuItem( m_axisMenu, ID_CustomXAxis, wxString( wxT("CustomX(exp)") ), wxEmptyString, wxITEM_CHECK ); m_axisMenu->Append( m_customX ); wxMenuItem* m_customY = new wxMenuItem( m_axisMenu, ID_CustomYAxis, wxString( wxT("CustomY(exp)") ), wxEmptyString, wxITEM_CHECK ); m_axisMenu->Append( m_customY ); m_menubar->Append( m_axisMenu, wxT("AxisType") ); m_gridMenu = new wxMenu(); wxMenuItem* m_grid = new wxMenuItem( m_gridMenu, ID_Grid, wxString( wxT("Grid") ), wxEmptyString, wxITEM_CHECK ); m_grid->Check( true ); m_gridMenu->Append( m_grid ); m_menubar->Append( m_gridMenu, wxT("Grid") ); this->SetMenuBar( m_menubar ); wxPanel* panel = new wxPanel(this, wxID_ANY); wxMath2DPlotData chartData; wxSharedPtr<wxMath2DPlotOptions> options(new wxMath2DPlotOptions()); options->GetCommonOptions().SetShowTooltips(false); wxVector<wxPoint2DDouble> points; auto pi = 3.1415926535897; auto tstart = -2*pi; for(auto i = 0u; i<100; i++) { auto x = tstart+0.1*i; points.push_back(wxPoint2DDouble(x,cos(x)*sin(x))); } wxMath2DPlotDataset::ptr dataset( new wxMath2DPlotDataset( wxColor(255, 255, 255, 0), wxColor(250, 20, 20, 0x78), wxColor(0, 0, 0, 0xB8), points) ); chartData.AddDataset(dataset); math2dPlotCtrl = new wxMath2DPlotCtrl(panel, wxID_ANY, chartData, options); wxChartsGridOptions opt = math2dPlotCtrl->GetGridOptions(); opt.GetHorizontalGridLineOptions().SetMajorGridLineColor(wxColour("Grey")); opt.GetVerticalGridLineOptions().SetMajorGridLineColor(wxColour("Grey")); math2dPlotCtrl->SetGridOptions(opt); wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL); panelSizer->Add(math2dPlotCtrl, 1, wxEXPAND); panel->SetSizer(panelSizer); wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL); topSizer->Add(panel, 1, wxEXPAND); SetSizerAndFit(topSizer); Binds(); } void WxMath2DFrame::Binds() { m_gridMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetGridOptions(); opt.SetShowGridLines(m_gridMenu->IsChecked(ID_Grid)); math2dPlotCtrl->SetGridOptions(opt); }, ID_Grid); m_axisMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetChartOptions(); if (m_axisMenu->IsChecked(ID_CustomXAxis)) opt.SetAxisFuncX([](wxDouble x){return std::exp(x);}); else opt.SetAxisFuncX([](wxDouble x){return x;}); math2dPlotCtrl->SetChartOptions(opt); }, ID_CustomXAxis); m_axisMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { auto opt = math2dPlotCtrl->GetChartOptions(); if (m_axisMenu->IsChecked(ID_CustomYAxis)) opt.SetAxisFuncY([](wxDouble x){return std::exp(x);}); else opt.SetAxisFuncY([](wxDouble x){return x;}); math2dPlotCtrl->SetChartOptions(opt); }, ID_CustomYAxis); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_LINE); }, ID_LineChart); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_STEPPED); }, ID_StepChart); m_typeMenu->Bind(wxEVT_COMMAND_MENU_SELECTED,[&](wxCommandEvent &) { math2dPlotCtrl->SetChartType(0,wxCHARTTYPE_STEM); }, ID_StemChart); } <|endoftext|>
<commit_before>/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #ifdef HAVE_UCRED_H #include <ucred.h> #endif #ifdef HAVE_SYS_UCRED_H #include <sys/ucred.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #include <folly/SocketAddress.h> #include <folly/String.h> #include <folly/net/NetworkSocket.h> #include <memory> #include "FileDescriptor.h" #include "Pipe.h" using watchman::FileDescriptor; using watchman::Pipe; using namespace watchman; static const int kWriteTimeout = 60000; namespace { // This trait allows w_poll_events to wait on either a PipeEvent or // a descriptor contained in a UnixStream class PollableEvent : public watchman_event { public: virtual FileDescriptor::system_handle_type getFd() const = 0; }; // The event object, implemented as pipe class PipeEvent : public PollableEvent { public: SocketPair pipe; void notify() override { ignore_result(pipe.write.write("a", 1).hasValue()); } bool testAndClear() override { char buf[64]; bool signalled = false; while (true) { auto res = pipe.read.read(buf, sizeof(buf)); if (res.hasError() || res.value() == 0) { break; } signalled = true; } return signalled; } FileDescriptor::system_handle_type getFd() const override { return pipe.read.system_handle(); } FileDescriptor::system_handle_type system_handle() override { return pipe.read.system_handle(); } bool isSocket() override { return true; } }; // Event object that UnixStream returns via getEvents. // It cannot be poked by hand; it is just a helper to // allow waiting on a socket using w_poll_events. class FakeSocketEvent : public PollableEvent { private: FileDescriptor::system_handle_type socket; public: explicit FakeSocketEvent(FileDescriptor::system_handle_type fd) : socket(fd) {} void notify() override {} bool testAndClear() override { return false; } FileDescriptor::system_handle_type getFd() const override { return socket; } FileDescriptor::system_handle_type system_handle() override { return socket; } bool isSocket() override { return true; } }; class UnixStream : public watchman_stream { public: FileDescriptor fd; FakeSocketEvent evt; #ifdef SO_PEERCRED struct ucred cred; #elif defined(LOCAL_PEERCRED) struct xucred cred; #elif defined(SO_RECVUCRED) struct ucred_deleter { void operator()(ucred_t* utp) { ucred_free(utp); } }; std::unique_ptr<ucred_t, ucred_deleter> cred; #endif bool credvalid{false}; bool blocking_{false}; explicit UnixStream(FileDescriptor&& descriptor) : fd(std::move(descriptor)), evt(fd.system_handle()) { #ifdef SO_PEERCRED socklen_t len = sizeof(cred); credvalid = getsockopt(fd.fd(), SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0; #elif defined(LOCAL_PEERCRED) socklen_t len = sizeof(cred); #if defined(__FreeBSD__) || defined(__DragonFly__) credvalid = getsockopt(fd.fd(), 0, LOCAL_PEERCRED, &cred, &len) == 0; #else credvalid = getsockopt(fd.fd(), SOL_LOCAL, LOCAL_PEERCRED, &cred, &len) == 0; #endif #elif defined(SO_RECVUCRED) ucred_t* peer_cred{nullptr}; credvalid = getpeerucred(fd.fd(), &peer_cred) == 0; cred.reset(peer_cred); #endif } const FileDescriptor& getFileDescriptor() const override { return fd; } int read(void* buf, int size) override { auto res = fd.read(buf, size); if (res.hasError()) { #ifdef _WIN32 errno = map_win32_err(res.error().value()); #else errno = res.error().value(); #endif return -1; } errno = 0; return res.value(); } int write(const void* buf, int size) override { if (blocking_) { int wrote = 0; while (size > 0) { struct pollfd pfd; pfd.fd = fd.system_handle(); pfd.events = POLLOUT; #ifdef _WIN32 if (WSAPoll(&pfd, 1, kWriteTimeout) == 0) { errno = map_win32_err(WSAGetLastError()); break; } #else if (poll(&pfd, 1, kWriteTimeout) == 0) { break; } #endif if (pfd.revents & (POLLERR | POLLHUP)) { break; } auto x = fd.write(buf, size); if (x.hasError()) { #ifdef _WIN32 errno = map_win32_err(x.error().value()); #else errno = x.error().value(); #endif break; } if (x.value() == 0) { errno = 0; break; } wrote += x.value(); size -= x.value(); buf = reinterpret_cast<const void*>( reinterpret_cast<const char*>(buf) + x.value()); } return wrote == 0 ? -1 : wrote; } auto x = fd.write(buf, size); if (x.hasError()) { #ifdef _WIN32 errno = map_win32_err(x.error().value()); #else errno = x.error().value(); #endif return -1; } errno = 0; return x.value(); } w_evt_t getEvents() override { return &evt; } void setNonBlock(bool nonb) override { if (nonb) { fd.setNonBlock(); } else { fd.clearNonBlock(); } blocking_ = !nonb; } bool rewind() override { #ifndef _WIN32 return lseek(fd.fd(), 0, SEEK_SET) == 0; #else return false; #endif } bool shutdown() override { return ::shutdown( fd.system_handle(), #ifdef SHUT_RDWR SHUT_RDWR #else SD_BOTH #endif ); } // For these PEERCRED things, the uid reported is the effective uid of // the process, which may have been altered due to setuid or similar // mechanisms. We'll treat the other process as an owner if their // effective UID matches ours, or if they are root. bool peerIsOwner() override { #ifdef _WIN32 return true; #else if (!credvalid) { return false; } #ifdef SO_PEERCRED if (cred.uid == getuid() || cred.uid == 0) { return true; } #elif defined(LOCAL_PEERCRED) if (cred.cr_uid == getuid() || cred.cr_uid == 0) { return true; } #elif defined(SO_RECVUCRED) uid_t ucreduid = ucred_getruid(cred.get()); if (ucreduid == getuid() || ucreduid == 0) { return true; } #endif return false; #endif } pid_t getPeerProcessID() const override { if (!credvalid) { return 0; } #ifdef SO_PEERCRED return cred.pid; #elif defined(SO_RECVUCRED) pid_t ucredpid = ucred_getpid(cred.get()); if (ucredpid == (pid_t)-1) { return 0; } return ucredpid; #else return 0; #endif } }; } // namespace std::unique_ptr<watchman_event> w_event_make_sockets(void) { return std::make_unique<PipeEvent>(); } #define MAX_POLL_EVENTS 63 // Must match MAXIMUM_WAIT_OBJECTS-1 on win int w_poll_events_sockets(struct watchman_event_poll* p, int n, int timeoutms) { struct pollfd pfds[MAX_POLL_EVENTS]; int i; int res; if (n > MAX_POLL_EVENTS) { // Programmer error :-/ logf(FATAL, "{} > MAX_POLL_EVENTS ({})\n", n, MAX_POLL_EVENTS); } for (i = 0; i < n; i++) { auto pe = dynamic_cast<PollableEvent*>(p[i].evt); w_check(pe != nullptr, "PollableEvent!?"); pfds[i].fd = pe->getFd(); pfds[i].events = POLLIN; pfds[i].revents = 0; } #ifdef _WIN32 res = WSAPoll(pfds, n, timeoutms); auto win_err = WSAGetLastError(); errno = map_win32_err(win_err); #else res = poll(pfds, n, timeoutms); #endif for (i = 0; i < n; i++) { p[i].ready = pfds[i].revents != 0; } return res; } std::unique_ptr<watchman_stream> w_stm_fdopen(FileDescriptor&& fd) { if (!fd) { return nullptr; } #ifdef _WIN32 if (fd.fdType() != FileDescriptor::FDType::Socket) { return w_stm_fdopen_windows(std::move(fd)); } #endif return std::make_unique<UnixStream>(std::move(fd)); } std::unique_ptr<watchman_stream> w_stm_connect_unix( const char* path, int timeoutms) { struct sockaddr_un un {}; int max_attempts = timeoutms / 10; int attempts = 0; if (strlen(path) >= sizeof(un.sun_path) - 1) { logf(ERR, "w_stm_connect_unix({}) path is too long\n", path); errno = E2BIG; return NULL; } FileDescriptor fd( ::socket( PF_LOCAL, #ifdef SOCK_CLOEXEC SOCK_CLOEXEC | #endif SOCK_STREAM, 0), FileDescriptor::FDType::Socket); if (!fd) { return nullptr; } fd.setCloExec(); un.sun_family = PF_LOCAL; memcpy(un.sun_path, path, strlen(path) + 1); retry_connect: if (::connect(fd.system_handle(), (struct sockaddr*)&un, sizeof(un))) { #ifdef _WIN32 int win_err = WSAGetLastError(); int err = map_win32_err(win_err); #else int err = errno; #endif if (err == ECONNREFUSED || err == ENOENT) { if (attempts++ < max_attempts) { /* sleep override */ std::this_thread::sleep_for( std::chrono::microseconds(10000)); goto retry_connect; } } logf( ERR, "w_stm_connect_unix({}) failed to connect: {}\n", path, folly::errnoStr(err)); errno = err; return nullptr; } int bufsize = WATCHMAN_IO_BUF_SIZE; ::setsockopt( fd.system_handle(), SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&bufsize), sizeof(bufsize)); return w_stm_fdopen(std::move(fd)); } #ifndef _WIN32 std::unique_ptr<watchman_stream> w_stm_open(const char* filename, int flags, ...) { int mode = 0; // If we're creating, pull out the mode flag if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode = va_arg(ap, int); va_end(ap); } return w_stm_fdopen(FileDescriptor( open(filename, flags, mode), FileDescriptor::FDType::Unknown)); } #endif <commit_msg>Back out "log when connecting to unix socket fails"<commit_after>/* Copyright 2014-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #ifdef HAVE_UCRED_H #include <ucred.h> #endif #ifdef HAVE_SYS_UCRED_H #include <sys/ucred.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #include <folly/SocketAddress.h> #include <folly/net/NetworkSocket.h> #include <memory> #include "FileDescriptor.h" #include "Pipe.h" using watchman::FileDescriptor; using watchman::Pipe; using namespace watchman; static const int kWriteTimeout = 60000; namespace { // This trait allows w_poll_events to wait on either a PipeEvent or // a descriptor contained in a UnixStream class PollableEvent : public watchman_event { public: virtual FileDescriptor::system_handle_type getFd() const = 0; }; // The event object, implemented as pipe class PipeEvent : public PollableEvent { public: SocketPair pipe; void notify() override { ignore_result(pipe.write.write("a", 1).hasValue()); } bool testAndClear() override { char buf[64]; bool signalled = false; while (true) { auto res = pipe.read.read(buf, sizeof(buf)); if (res.hasError() || res.value() == 0) { break; } signalled = true; } return signalled; } FileDescriptor::system_handle_type getFd() const override { return pipe.read.system_handle(); } FileDescriptor::system_handle_type system_handle() override { return pipe.read.system_handle(); } bool isSocket() override { return true; } }; // Event object that UnixStream returns via getEvents. // It cannot be poked by hand; it is just a helper to // allow waiting on a socket using w_poll_events. class FakeSocketEvent : public PollableEvent { private: FileDescriptor::system_handle_type socket; public: explicit FakeSocketEvent(FileDescriptor::system_handle_type fd) : socket(fd) {} void notify() override {} bool testAndClear() override { return false; } FileDescriptor::system_handle_type getFd() const override { return socket; } FileDescriptor::system_handle_type system_handle() override { return socket; } bool isSocket() override { return true; } }; class UnixStream : public watchman_stream { public: FileDescriptor fd; FakeSocketEvent evt; #ifdef SO_PEERCRED struct ucred cred; #elif defined(LOCAL_PEERCRED) struct xucred cred; #elif defined(SO_RECVUCRED) struct ucred_deleter { void operator()(ucred_t* utp) { ucred_free(utp); } }; std::unique_ptr<ucred_t, ucred_deleter> cred; #endif bool credvalid{false}; bool blocking_{false}; explicit UnixStream(FileDescriptor&& descriptor) : fd(std::move(descriptor)), evt(fd.system_handle()) { #ifdef SO_PEERCRED socklen_t len = sizeof(cred); credvalid = getsockopt(fd.fd(), SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0; #elif defined(LOCAL_PEERCRED) socklen_t len = sizeof(cred); #if defined(__FreeBSD__) || defined(__DragonFly__) credvalid = getsockopt(fd.fd(), 0, LOCAL_PEERCRED, &cred, &len) == 0; #else credvalid = getsockopt(fd.fd(), SOL_LOCAL, LOCAL_PEERCRED, &cred, &len) == 0; #endif #elif defined(SO_RECVUCRED) ucred_t* peer_cred{nullptr}; credvalid = getpeerucred(fd.fd(), &peer_cred) == 0; cred.reset(peer_cred); #endif } const FileDescriptor& getFileDescriptor() const override { return fd; } int read(void* buf, int size) override { auto res = fd.read(buf, size); if (res.hasError()) { #ifdef _WIN32 errno = map_win32_err(res.error().value()); #else errno = res.error().value(); #endif return -1; } errno = 0; return res.value(); } int write(const void* buf, int size) override { if (blocking_) { int wrote = 0; while (size > 0) { struct pollfd pfd; pfd.fd = fd.system_handle(); pfd.events = POLLOUT; #ifdef _WIN32 if (WSAPoll(&pfd, 1, kWriteTimeout) == 0) { errno = map_win32_err(WSAGetLastError()); break; } #else if (poll(&pfd, 1, kWriteTimeout) == 0) { break; } #endif if (pfd.revents & (POLLERR | POLLHUP)) { break; } auto x = fd.write(buf, size); if (x.hasError()) { #ifdef _WIN32 errno = map_win32_err(x.error().value()); #else errno = x.error().value(); #endif break; } if (x.value() == 0) { errno = 0; break; } wrote += x.value(); size -= x.value(); buf = reinterpret_cast<const void*>( reinterpret_cast<const char*>(buf) + x.value()); } return wrote == 0 ? -1 : wrote; } auto x = fd.write(buf, size); if (x.hasError()) { #ifdef _WIN32 errno = map_win32_err(x.error().value()); #else errno = x.error().value(); #endif return -1; } errno = 0; return x.value(); } w_evt_t getEvents() override { return &evt; } void setNonBlock(bool nonb) override { if (nonb) { fd.setNonBlock(); } else { fd.clearNonBlock(); } blocking_ = !nonb; } bool rewind() override { #ifndef _WIN32 return lseek(fd.fd(), 0, SEEK_SET) == 0; #else return false; #endif } bool shutdown() override { return ::shutdown( fd.system_handle(), #ifdef SHUT_RDWR SHUT_RDWR #else SD_BOTH #endif ); } // For these PEERCRED things, the uid reported is the effective uid of // the process, which may have been altered due to setuid or similar // mechanisms. We'll treat the other process as an owner if their // effective UID matches ours, or if they are root. bool peerIsOwner() override { #ifdef _WIN32 return true; #else if (!credvalid) { return false; } #ifdef SO_PEERCRED if (cred.uid == getuid() || cred.uid == 0) { return true; } #elif defined(LOCAL_PEERCRED) if (cred.cr_uid == getuid() || cred.cr_uid == 0) { return true; } #elif defined(SO_RECVUCRED) uid_t ucreduid = ucred_getruid(cred.get()); if (ucreduid == getuid() || ucreduid == 0) { return true; } #endif return false; #endif } pid_t getPeerProcessID() const override { if (!credvalid) { return 0; } #ifdef SO_PEERCRED return cred.pid; #elif defined(SO_RECVUCRED) pid_t ucredpid = ucred_getpid(cred.get()); if (ucredpid == (pid_t)-1) { return 0; } return ucredpid; #else return 0; #endif } }; } // namespace std::unique_ptr<watchman_event> w_event_make_sockets(void) { return std::make_unique<PipeEvent>(); } #define MAX_POLL_EVENTS 63 // Must match MAXIMUM_WAIT_OBJECTS-1 on win int w_poll_events_sockets(struct watchman_event_poll* p, int n, int timeoutms) { struct pollfd pfds[MAX_POLL_EVENTS]; int i; int res; if (n > MAX_POLL_EVENTS) { // Programmer error :-/ logf(FATAL, "{} > MAX_POLL_EVENTS ({})\n", n, MAX_POLL_EVENTS); } for (i = 0; i < n; i++) { auto pe = dynamic_cast<PollableEvent*>(p[i].evt); w_check(pe != nullptr, "PollableEvent!?"); pfds[i].fd = pe->getFd(); pfds[i].events = POLLIN; pfds[i].revents = 0; } #ifdef _WIN32 res = WSAPoll(pfds, n, timeoutms); auto win_err = WSAGetLastError(); errno = map_win32_err(win_err); #else res = poll(pfds, n, timeoutms); #endif for (i = 0; i < n; i++) { p[i].ready = pfds[i].revents != 0; } return res; } std::unique_ptr<watchman_stream> w_stm_fdopen(FileDescriptor&& fd) { if (!fd) { return nullptr; } #ifdef _WIN32 if (fd.fdType() != FileDescriptor::FDType::Socket) { return w_stm_fdopen_windows(std::move(fd)); } #endif return std::make_unique<UnixStream>(std::move(fd)); } std::unique_ptr<watchman_stream> w_stm_connect_unix( const char* path, int timeoutms) { struct sockaddr_un un {}; int max_attempts = timeoutms / 10; int attempts = 0; if (strlen(path) >= sizeof(un.sun_path) - 1) { logf(ERR, "w_stm_connect_unix({}) path is too long\n", path); errno = E2BIG; return NULL; } FileDescriptor fd( ::socket( PF_LOCAL, #ifdef SOCK_CLOEXEC SOCK_CLOEXEC | #endif SOCK_STREAM, 0), FileDescriptor::FDType::Socket); if (!fd) { return nullptr; } fd.setCloExec(); un.sun_family = PF_LOCAL; memcpy(un.sun_path, path, strlen(path) + 1); retry_connect: if (::connect(fd.system_handle(), (struct sockaddr*)&un, sizeof(un))) { #ifdef _WIN32 int win_err = WSAGetLastError(); int err = map_win32_err(win_err); #else int err = errno; #endif if (err == ECONNREFUSED || err == ENOENT) { if (attempts++ < max_attempts) { /* sleep override */ std::this_thread::sleep_for( std::chrono::microseconds(10000)); goto retry_connect; } } errno = err; return nullptr; } int bufsize = WATCHMAN_IO_BUF_SIZE; ::setsockopt( fd.system_handle(), SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&bufsize), sizeof(bufsize)); return w_stm_fdopen(std::move(fd)); } #ifndef _WIN32 std::unique_ptr<watchman_stream> w_stm_open(const char* filename, int flags, ...) { int mode = 0; // If we're creating, pull out the mode flag if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode = va_arg(ap, int); va_end(ap); } return w_stm_fdopen(FileDescriptor( open(filename, flags, mode), FileDescriptor::FDType::Unknown)); } #endif <|endoftext|>
<commit_before>/*********************************************************************** filename: SampleData.cpp created: 4/6/2012 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "SampleData.h" #include "Sample.h" #include "Samples_xmlHandler.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/Version.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/TextureTarget.h" #include "CEGUI/BasicImage.h" #include "CEGUI/GUIContext.h" #include "CEGUI/Texture.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Window.h" using namespace CEGUI; #define S_(X) #X #define STRINGIZE(X) S_(X) typedef Sample& (*getSampleInstance)(); #define GetSampleInstanceFuncName "getSampleInstance" SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum) : d_name(sampleName), d_summary(summary), d_description(description), d_type(sampleTypeEnum), d_guiContext(0), d_textureTarget(0), d_textureTargetImage(0), d_sampleWindow(0), d_usedFilesString("") { } SampleData::~SampleData() { } CEGUI::String SampleData::getName() { return d_name; } CEGUI::String SampleData::getSummary() { return d_summary; } CEGUI::String SampleData::getSampleTypeString() { switch(d_type) { case ST_Module: return SampleDataHandler::SampleTypeCppModule; break; case ST_Lua: return SampleDataHandler::SampleTypeLua; break; case ST_Python: return SampleDataHandler::SampleTypePython; default: return ""; } } CEGUI::String SampleData::getDescription() { return d_description; } CEGUI::String SampleData::getUsedFilesString() { return d_usedFilesString; } void SampleData::setSampleWindow(CEGUI::Window* sampleWindow) { d_sampleWindow = sampleWindow; } CEGUI::Window* SampleData::getSampleWindow() { return d_sampleWindow; } void SampleData::initialise() { CEGUI::System& system(System::getSingleton()); d_textureTarget = system.getRenderer()->createTextureTarget(); d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); CEGUI::String imageName(d_textureTarget->getTexture().getName()); d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName)); d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); } void SampleData::deinitialise() { CEGUI::System& system(System::getSingleton()); if(d_guiContext) { system.destroyGUIContext(*d_guiContext); d_guiContext = 0; } if(d_textureTarget) { system.getRenderer()->destroyTextureTarget(d_textureTarget); d_textureTarget = 0; } } GUIContext* SampleData::getGuiContext() { return d_guiContext; } void SampleData::handleNewWindowSize(float width, float height) { CEGUI::Sizef windowSize(width, height); CEGUI::Rectf renderArea(CEGUI::Rectf(0.f, height, width, 0.f)); d_textureTargetImage->setArea(renderArea); d_textureTarget->declareRenderSize(windowSize); d_sampleWindow->getRenderingSurface()->invalidate(); } CEGUI::Image& SampleData::getRTTImage() { return *d_textureTargetImage; } void SampleData::setGUIContextRTT() { d_guiContext->setRenderTarget(*d_textureTarget); } void SampleData::clearRTTTexture() { d_textureTarget->clear(); } SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum) : SampleData(sampleName, summary, description ,sampleTypeEnum) { } SampleDataModule::~SampleDataModule() { } void SampleDataModule::initialise() { SampleData::initialise(); getSampleInstanceFromDLL(); d_usedFilesString = d_sample->getUsedFilesString(); d_sample->initialise(d_guiContext); } void SampleDataModule::deinitialise() { SampleData::deinitialise(); d_sample->deinitialise(); } void SampleDataModule::getSampleInstanceFromDLL() { // Version suffix for the dlls static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) ); CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix); getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName)); if(functionPointerGetSample == 0) { CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name; CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str())); } d_sample = &(functionPointerGetSample()); }<commit_msg>MOD: Start size fix<commit_after>/*********************************************************************** filename: SampleData.cpp created: 4/6/2012 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "SampleData.h" #include "Sample.h" #include "Samples_xmlHandler.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/Version.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/TextureTarget.h" #include "CEGUI/BasicImage.h" #include "CEGUI/GUIContext.h" #include "CEGUI/Texture.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Window.h" using namespace CEGUI; #define S_(X) #X #define STRINGIZE(X) S_(X) typedef Sample& (*getSampleInstance)(); #define GetSampleInstanceFuncName "getSampleInstance" SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum) : d_name(sampleName), d_summary(summary), d_description(description), d_type(sampleTypeEnum), d_guiContext(0), d_textureTarget(0), d_textureTargetImage(0), d_sampleWindow(0), d_usedFilesString("") { } SampleData::~SampleData() { } CEGUI::String SampleData::getName() { return d_name; } CEGUI::String SampleData::getSummary() { return d_summary; } CEGUI::String SampleData::getSampleTypeString() { switch(d_type) { case ST_Module: return SampleDataHandler::SampleTypeCppModule; break; case ST_Lua: return SampleDataHandler::SampleTypeLua; break; case ST_Python: return SampleDataHandler::SampleTypePython; default: return ""; } } CEGUI::String SampleData::getDescription() { return d_description; } CEGUI::String SampleData::getUsedFilesString() { return d_usedFilesString; } void SampleData::setSampleWindow(CEGUI::Window* sampleWindow) { d_sampleWindow = sampleWindow; } CEGUI::Window* SampleData::getSampleWindow() { return d_sampleWindow; } void SampleData::initialise() { CEGUI::System& system(System::getSingleton()); d_textureTarget = system.getRenderer()->createTextureTarget(); d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); d_textureTarget->declareRenderSize(CEGUI::Sizef(200.f, 200.f)); CEGUI::String imageName(d_textureTarget->getTexture().getName()); d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName)); d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); } void SampleData::deinitialise() { CEGUI::System& system(System::getSingleton()); if(d_guiContext) { system.destroyGUIContext(*d_guiContext); d_guiContext = 0; } if(d_textureTarget) { system.getRenderer()->destroyTextureTarget(d_textureTarget); d_textureTarget = 0; } } GUIContext* SampleData::getGuiContext() { return d_guiContext; } void SampleData::handleNewWindowSize(float width, float height) { CEGUI::Sizef windowSize(width, height); CEGUI::Rectf renderArea(CEGUI::Rectf(0.f, height, width, 0.f)); d_textureTargetImage->setArea(renderArea); d_textureTarget->declareRenderSize(windowSize); d_sampleWindow->getRenderingSurface()->invalidate(); } CEGUI::Image& SampleData::getRTTImage() { return *d_textureTargetImage; } void SampleData::setGUIContextRTT() { d_guiContext->setRenderTarget(*d_textureTarget); } void SampleData::clearRTTTexture() { d_textureTarget->clear(); } SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum) : SampleData(sampleName, summary, description ,sampleTypeEnum) { } SampleDataModule::~SampleDataModule() { } void SampleDataModule::initialise() { SampleData::initialise(); getSampleInstanceFromDLL(); d_usedFilesString = d_sample->getUsedFilesString(); d_sample->initialise(d_guiContext); } void SampleDataModule::deinitialise() { SampleData::deinitialise(); d_sample->deinitialise(); } void SampleDataModule::getSampleInstanceFromDLL() { // Version suffix for the dlls static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) ); CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix); getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName)); if(functionPointerGetSample == 0) { CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name; CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str())); } d_sample = &(functionPointerGetSample()); }<|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include "document_iterator.h" #include <vespa/document/select/gid_filter.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/persistence/spi/docentry.h> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".proton.persistenceengine.document_iterator"); using storage::spi::IterateResult; using storage::spi::DocEntry; using storage::spi::Timestamp; using document::Document; using document::DocumentId; namespace proton { namespace { DocEntry *createDocEntry(Timestamp timestamp, bool removed) { int flags = removed ? storage::spi::REMOVE_ENTRY : storage::spi::NONE; return new DocEntry(timestamp, flags); } DocEntry *createDocEntry(Timestamp timestamp, bool removed, Document::UP doc, ssize_t defaultSerializedSize) { if (doc) { if (removed) { return new DocEntry(timestamp, storage::spi::REMOVE_ENTRY, doc->getId()); } else { ssize_t serializedSize = defaultSerializedSize >= 0 ? defaultSerializedSize : doc->getSerializedSize(); return new DocEntry(timestamp, storage::spi::NONE, std::move(doc), serializedSize); } } else { return createDocEntry(timestamp, removed); } } } // namespace proton::<unnamed> bool DocumentIterator::useDocumentSelection() const { return (!_metaOnly && !_selection.getDocumentSelection().getDocumentSelection().empty()); } bool DocumentIterator::checkMeta(const search::DocumentMetaData &meta) const { if (!meta.valid()) { return false; } if (!_selection.getTimestampSubset().empty()) { return (std::binary_search(_selection.getTimestampSubset().begin(), _selection.getTimestampSubset().end(), Timestamp(meta.timestamp))); } if ((meta.timestamp < _selection.getFromTimestamp()) || (meta.timestamp > _selection.getToTimestamp())) { return false; } if ((_versions == storage::spi::NEWEST_DOCUMENT_ONLY) && meta.removed) { return false; } return true; } DocumentIterator::DocumentIterator(const storage::spi::Bucket &bucket, const document::FieldSet& fields, const storage::spi::Selection &selection, storage::spi::IncludedVersions versions, ssize_t defaultSerializedSize, bool ignoreMaxBytes, ReadConsistency readConsistency) : _bucket(bucket), _selection(selection), _versions(versions), _fields(fields.clone()), _defaultSerializedSize(defaultSerializedSize), _readConsistency(readConsistency), _metaOnly(fields.getType() == document::FieldSet::NONE), _ignoreMaxBytes(ignoreMaxBytes), _sources(), _nextItem(0), _list() { } void DocumentIterator::add(const IDocumentRetriever::SP &retriever) { _sources.push_back(retriever); } IterateResult DocumentIterator::iterate(size_t maxBytes) { if (_list.empty()) { for (const IDocumentRetriever::SP & source : _sources) { fetchCompleteSource(*source, _list); } } if ( _ignoreMaxBytes ) { return IterateResult(std::move(_list), true); } else { IterateResult::List results; for (size_t sz(0); (_nextItem < _list.size()) && ((sz < maxBytes) || results.empty()); _nextItem++) { DocEntry::LP & item = _list[_nextItem]; sz += item->getSize(); results.push_back(item); item.reset(); } return IterateResult(results, _nextItem >= _list.size()); } } namespace { class Match { public: Match(const IDocumentRetriever & source, bool metaOnly, const vespalib::string & selection) : _dscTrue(true), _metaOnly(metaOnly), _willAlwaysFail(false), _docidLimit(source.getDocIdLimit()) { if (!(_metaOnly || selection.empty())) { LOG(spam, "ParseSelect: %s", selection.c_str()); _cs = source.parseSelect(selection); CachedSelect &cs(*_cs); _dscTrue = cs._allTrue; if (cs._allFalse || cs._allInvalid) { assert(!_dscTrue); LOG(debug, "Nothing will ever match cs._allFalse = '%d' cs._allInvalid = '%d'", cs._allFalse, cs._allInvalid); _willAlwaysFail = true; } else { _select = (cs._attrSelect ? cs._attrSelect->clone() : cs._select->clone()); using document::select::GidFilter; _gidFilter = GidFilter::for_selection_root_node(*_select); _sc.reset(new SelectContext(*_cs)); _sc->getAttributeGuards(); } } else { _dscTrue = true; } } ~Match() { if (_sc) { _sc->dropAttributeGuards(); } } bool willAlwaysFail() const { return _willAlwaysFail; } bool match(const search::DocumentMetaData & meta) const { if (_dscTrue || _metaOnly) { return true; } if (meta.lid >= _docidLimit) { return false; } if (_sc) { _sc->_docId = meta.lid; } if (!_gidFilter.gid_might_match_selection(meta.gid)) { return false; } return (! _cs->_attrSelect) || (_cs->_attrSelect && (_select->contains(*_sc) == document::select::Result::True)); } bool match(const search::DocumentMetaData & meta, const Document * doc) const { if (_dscTrue || _metaOnly) { return true; } return (doc && (doc->getId().getGlobalId() == meta.gid) && (_cs->_attrSelect || (_select->contains(*doc) == document::select::Result::True))); } private: bool _dscTrue; bool _metaOnly; bool _willAlwaysFail; uint32_t _docidLimit; CachedSelect::SP _cs; document::select::Node::UP _select; document::select::GidFilter _gidFilter; std::unique_ptr<SelectContext> _sc; }; typedef vespalib::hash_map<uint32_t, uint32_t> LidIndexMap; class MatchVisitor : public search::IDocumentVisitor { public: MatchVisitor(const Match & matcher, const search::DocumentMetaData::Vector & metaData, const LidIndexMap & lidIndexMap, const document::FieldSet * fields, IterateResult::List & list, ssize_t defaultSerializedSize) : _matcher(matcher), _metaData(metaData), _lidIndexMap(lidIndexMap), _fields(fields), _list(list), _defaultSerializedSize(defaultSerializedSize) { } void visit(uint32_t lid, document::Document::UP doc) override { const search::DocumentMetaData & meta = _metaData[_lidIndexMap[lid]]; assert(lid == meta.lid); if (_matcher.match(meta, doc.get())) { if (doc && _fields) { document::FieldSet::stripFields(*doc, *_fields); } _list.emplace_back(createDocEntry(meta.timestamp, meta.removed, std::move(doc), _defaultSerializedSize)); } } private: const Match & _matcher; const search::DocumentMetaData::Vector & _metaData; const LidIndexMap & _lidIndexMap; const document::FieldSet * _fields; IterateResult::List & _list; size_t _defaultSerializedSize; }; } void DocumentIterator::fetchCompleteSource(const IDocumentRetriever & source, IterateResult::List & list) { IDocumentRetriever::ReadGuard sourceReadGuard(source.getReadGuard()); search::DocumentMetaData::Vector metaData; source.getBucketMetaData(_bucket, metaData); if (metaData.empty()) { return; } LOG(debug, "metadata count before filtering: %zu", metaData.size()); Match matcher(source, _metaOnly, _selection.getDocumentSelection().getDocumentSelection()); if (matcher.willAlwaysFail()) { return; } LidIndexMap lidIndexMap(3*metaData.size()); IDocumentRetriever::LidVector lidsToFetch; lidsToFetch.reserve(metaData.size()); for (size_t i(0); i < metaData.size(); i++) { const search::DocumentMetaData & meta = metaData[i]; if (checkMeta(meta)) { if (matcher.match(meta)) { lidsToFetch.emplace_back(meta.lid); lidIndexMap[meta.lid] = i; } } } LOG(debug, "metadata count after filtering: %zu", lidsToFetch.size()); if ( _metaOnly ) { for (uint32_t lid : lidsToFetch) { const search::DocumentMetaData & meta = metaData[lidIndexMap[lid]]; assert(lid == meta.lid); list.emplace_back(createDocEntry(meta.timestamp, meta.removed)); } } else { MatchVisitor visitor(matcher, metaData, lidIndexMap, _fields.get(), list, _defaultSerializedSize); source.visitDocuments(lidsToFetch, visitor, _readConsistency); } } } // namespace proton <commit_msg>Holding the lidlimit is mandatory.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include "document_iterator.h" #include <vespa/document/select/gid_filter.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/persistence/spi/docentry.h> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".proton.persistenceengine.document_iterator"); using storage::spi::IterateResult; using storage::spi::DocEntry; using storage::spi::Timestamp; using document::Document; using document::DocumentId; namespace proton { namespace { DocEntry *createDocEntry(Timestamp timestamp, bool removed) { int flags = removed ? storage::spi::REMOVE_ENTRY : storage::spi::NONE; return new DocEntry(timestamp, flags); } DocEntry *createDocEntry(Timestamp timestamp, bool removed, Document::UP doc, ssize_t defaultSerializedSize) { if (doc) { if (removed) { return new DocEntry(timestamp, storage::spi::REMOVE_ENTRY, doc->getId()); } else { ssize_t serializedSize = defaultSerializedSize >= 0 ? defaultSerializedSize : doc->getSerializedSize(); return new DocEntry(timestamp, storage::spi::NONE, std::move(doc), serializedSize); } } else { return createDocEntry(timestamp, removed); } } } // namespace proton::<unnamed> bool DocumentIterator::useDocumentSelection() const { return (!_metaOnly && !_selection.getDocumentSelection().getDocumentSelection().empty()); } bool DocumentIterator::checkMeta(const search::DocumentMetaData &meta) const { if (!meta.valid()) { return false; } if (!_selection.getTimestampSubset().empty()) { return (std::binary_search(_selection.getTimestampSubset().begin(), _selection.getTimestampSubset().end(), Timestamp(meta.timestamp))); } if ((meta.timestamp < _selection.getFromTimestamp()) || (meta.timestamp > _selection.getToTimestamp())) { return false; } if ((_versions == storage::spi::NEWEST_DOCUMENT_ONLY) && meta.removed) { return false; } return true; } DocumentIterator::DocumentIterator(const storage::spi::Bucket &bucket, const document::FieldSet& fields, const storage::spi::Selection &selection, storage::spi::IncludedVersions versions, ssize_t defaultSerializedSize, bool ignoreMaxBytes, ReadConsistency readConsistency) : _bucket(bucket), _selection(selection), _versions(versions), _fields(fields.clone()), _defaultSerializedSize(defaultSerializedSize), _readConsistency(readConsistency), _metaOnly(fields.getType() == document::FieldSet::NONE), _ignoreMaxBytes(ignoreMaxBytes), _sources(), _nextItem(0), _list() { } void DocumentIterator::add(const IDocumentRetriever::SP &retriever) { _sources.push_back(retriever); } IterateResult DocumentIterator::iterate(size_t maxBytes) { if (_list.empty()) { for (const IDocumentRetriever::SP & source : _sources) { fetchCompleteSource(*source, _list); } } if ( _ignoreMaxBytes ) { return IterateResult(std::move(_list), true); } else { IterateResult::List results; for (size_t sz(0); (_nextItem < _list.size()) && ((sz < maxBytes) || results.empty()); _nextItem++) { DocEntry::LP & item = _list[_nextItem]; sz += item->getSize(); results.push_back(item); item.reset(); } return IterateResult(results, _nextItem >= _list.size()); } } namespace { class Match { public: Match(const IDocumentRetriever & source, bool metaOnly, const vespalib::string & selection) : _dscTrue(true), _metaOnly(metaOnly), _willAlwaysFail(false), _docidLimit(source.getDocIdLimit()) { if (!(_metaOnly || selection.empty())) { LOG(spam, "ParseSelect: %s", selection.c_str()); _cs = source.parseSelect(selection); CachedSelect &cs(*_cs); _dscTrue = cs._allTrue; if (cs._allFalse || cs._allInvalid) { assert(!_dscTrue); LOG(debug, "Nothing will ever match cs._allFalse = '%d' cs._allInvalid = '%d'", cs._allFalse, cs._allInvalid); _willAlwaysFail = true; } else { _select = (cs._attrSelect ? cs._attrSelect->clone() : cs._select->clone()); using document::select::GidFilter; _gidFilter = GidFilter::for_selection_root_node(*_select); _sc.reset(new SelectContext(*_cs)); _sc->getAttributeGuards(); } } else { _dscTrue = true; } } ~Match() { if (_sc) { _sc->dropAttributeGuards(); } } bool willAlwaysFail() const { return _willAlwaysFail; } bool match(const search::DocumentMetaData & meta) const { if (meta.lid >= _docidLimit) { return false; } if (_dscTrue || _metaOnly) { return true; } if (_sc) { _sc->_docId = meta.lid; } if (!_gidFilter.gid_might_match_selection(meta.gid)) { return false; } return (! _cs->_attrSelect) || (_cs->_attrSelect && (_select->contains(*_sc) == document::select::Result::True)); } bool match(const search::DocumentMetaData & meta, const Document * doc) const { if (_dscTrue || _metaOnly) { return true; } return (doc && (doc->getId().getGlobalId() == meta.gid) && (_cs->_attrSelect || (_select->contains(*doc) == document::select::Result::True))); } private: bool _dscTrue; bool _metaOnly; bool _willAlwaysFail; uint32_t _docidLimit; CachedSelect::SP _cs; document::select::Node::UP _select; document::select::GidFilter _gidFilter; std::unique_ptr<SelectContext> _sc; }; typedef vespalib::hash_map<uint32_t, uint32_t> LidIndexMap; class MatchVisitor : public search::IDocumentVisitor { public: MatchVisitor(const Match & matcher, const search::DocumentMetaData::Vector & metaData, const LidIndexMap & lidIndexMap, const document::FieldSet * fields, IterateResult::List & list, ssize_t defaultSerializedSize) : _matcher(matcher), _metaData(metaData), _lidIndexMap(lidIndexMap), _fields(fields), _list(list), _defaultSerializedSize(defaultSerializedSize) { } void visit(uint32_t lid, document::Document::UP doc) override { const search::DocumentMetaData & meta = _metaData[_lidIndexMap[lid]]; assert(lid == meta.lid); if (_matcher.match(meta, doc.get())) { if (doc && _fields) { document::FieldSet::stripFields(*doc, *_fields); } _list.emplace_back(createDocEntry(meta.timestamp, meta.removed, std::move(doc), _defaultSerializedSize)); } } private: const Match & _matcher; const search::DocumentMetaData::Vector & _metaData; const LidIndexMap & _lidIndexMap; const document::FieldSet * _fields; IterateResult::List & _list; size_t _defaultSerializedSize; }; } void DocumentIterator::fetchCompleteSource(const IDocumentRetriever & source, IterateResult::List & list) { IDocumentRetriever::ReadGuard sourceReadGuard(source.getReadGuard()); search::DocumentMetaData::Vector metaData; source.getBucketMetaData(_bucket, metaData); if (metaData.empty()) { return; } LOG(debug, "metadata count before filtering: %zu", metaData.size()); Match matcher(source, _metaOnly, _selection.getDocumentSelection().getDocumentSelection()); if (matcher.willAlwaysFail()) { return; } LidIndexMap lidIndexMap(3*metaData.size()); IDocumentRetriever::LidVector lidsToFetch; lidsToFetch.reserve(metaData.size()); for (size_t i(0); i < metaData.size(); i++) { const search::DocumentMetaData & meta = metaData[i]; if (checkMeta(meta)) { if (matcher.match(meta)) { lidsToFetch.emplace_back(meta.lid); lidIndexMap[meta.lid] = i; } } } LOG(debug, "metadata count after filtering: %zu", lidsToFetch.size()); if ( _metaOnly ) { for (uint32_t lid : lidsToFetch) { const search::DocumentMetaData & meta = metaData[lidIndexMap[lid]]; assert(lid == meta.lid); list.emplace_back(createDocEntry(meta.timestamp, meta.removed)); } } else { MatchVisitor visitor(matcher, metaData, lidIndexMap, _fields.get(), list, _defaultSerializedSize); source.visitDocuments(lidsToFetch, visitor, _readConsistency); } } } // namespace proton <|endoftext|>
<commit_before>#include <algorithm> #include <ctime> #include "caffe2/core/net.h" #include "caffe2/core/operator.h" #include "caffe2/core/workspace.h" #include "caffe2/proto/caffe2.pb.h" namespace caffe2 { // TODO(Yangqing): move all the checks to a less fatal check mechanism. OperatorBase::OperatorBase(const OperatorDef& operator_def, Workspace* ws) : operator_def_(operator_def) { for (auto& arg : operator_def.arg()) { CHECK_GT(arg.name().size(), 0) << "Argument must have a name."; CHECK_EQ(arg_map_.count(arg.name()), 0) << "Duplicated argument name."; arg_map_[arg.name()] = &arg; } for (const string& input_str : operator_def_.input()) { inputs_.push_back(CHECK_NOTNULL(ws->GetBlob(input_str))); } for (const string& output_str : operator_def_.output()) { outputs_.push_back(CHECK_NOTNULL(ws->CreateBlob(output_str))); } } // Parameter getters. You can use these to get the arguments that you want. // We need to deal with the fact that we cannot really template into // protocol buffers... yuck. #define INSTANTIATE_GET_SINGLE_ARGUMENT(dtype, fieldname) \ template <> \ dtype OperatorBase::GetSingleArgument<dtype>( \ const string& name, const dtype& default_value) { \ if (arg_map_.count(name) == 0) { \ DVLOG(1) << "Using default parameter value " << default_value; \ return default_value; \ } \ CHECK(arg_map_[name]->has_##fieldname()) \ << "Argument does not have the right field: expected " \ << #fieldname; \ return arg_map_[name]->fieldname(); \ } INSTANTIATE_GET_SINGLE_ARGUMENT(float, f) INSTANTIATE_GET_SINGLE_ARGUMENT(int, i) INSTANTIATE_GET_SINGLE_ARGUMENT(string, s) // Undefine the argument just to be safe. #undef INSTANTIATE_GET_SINGLE_ARGUMENT #define INSTANTIATE_GET_REPEATED_ARGUMENT(dtype, fieldname) \ template <> \ vector<dtype> OperatorBase::GetRepeatedArgument<dtype>( \ const string& name) { \ if (arg_map_.count(name) == 0) { \ return vector<dtype>(); \ } \ vector<dtype> values; \ CHECK(arg_map_[name]->fieldname##_size()) \ << "Argument does not have the right field: expected " \ << #fieldname; \ for (const auto& v : arg_map_[name]->fieldname()) values.push_back(v); \ return values; \ } INSTANTIATE_GET_REPEATED_ARGUMENT(float, floats) INSTANTIATE_GET_REPEATED_ARGUMENT(int, ints) INSTANTIATE_GET_REPEATED_ARGUMENT(string, strings) #undef INSTANTIATE_GET_REPEATED_ARGUMENT bool OperatorBase::Verify() { // Check Blob counts. if (operator_def_.input_size() < MinInput() || operator_def_.input_size() > MaxInput()) { LOG(ERROR) << "Input size " << operator_def_.input_size() << " not in range [min=" << MinInput() << ", max=" << MaxInput() << "]."; LOG(ERROR) << "Error at operator " << operator_def_.name() << ":" << operator_def_.type(); return false; } if (operator_def_.output_size() < MinOutput() || operator_def_.output_size() > MaxOutput()) { LOG(ERROR) << "Output size " << operator_def_.output_size() << " not in range [min=" << MinOutput() << ", max=" << MaxOutput() << "]."; LOG(ERROR) << "Error at operator " << operator_def_.name() << ":" << operator_def_.type(); return false; } return true; } OperatorBase* CreateOperator(const OperatorDef& operator_def, Workspace* ws) { const string& key = operator_def.type(); switch (operator_def.device_option().device_type()) { case CPU: VLOG(1) << "Creating CPU operator " << key; return CPUOperatorRegistry()->Create(key, operator_def, ws); case CUDA: VLOG(1) << "Creating CUDA operator " << key; return CUDAOperatorRegistry()->Create(key, operator_def, ws); case CUDNN: VLOG(1) << "Using CuDNN implementation."; return CUDNNOperatorRegistry()->Create(key, operator_def, ws); } // Just to suppress some compiler error return nullptr; } DEFINE_REGISTRY(CPUOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); DEFINE_REGISTRY(CUDAOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); DEFINE_REGISTRY(CUDNNOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); } // namespace caffe2 <commit_msg>operator.cc: remove check for empty repeated argument (to allow empty shapes and other use cases)<commit_after>#include <algorithm> #include <ctime> #include "caffe2/core/net.h" #include "caffe2/core/operator.h" #include "caffe2/core/workspace.h" #include "caffe2/proto/caffe2.pb.h" namespace caffe2 { // TODO(Yangqing): move all the checks to a less fatal check mechanism. OperatorBase::OperatorBase(const OperatorDef& operator_def, Workspace* ws) : operator_def_(operator_def) { for (auto& arg : operator_def.arg()) { CHECK_GT(arg.name().size(), 0) << "Argument must have a name."; CHECK_EQ(arg_map_.count(arg.name()), 0) << "Duplicated argument name."; arg_map_[arg.name()] = &arg; } for (const string& input_str : operator_def_.input()) { inputs_.push_back(CHECK_NOTNULL(ws->GetBlob(input_str))); } for (const string& output_str : operator_def_.output()) { outputs_.push_back(CHECK_NOTNULL(ws->CreateBlob(output_str))); } } // Parameter getters. You can use these to get the arguments that you want. // We need to deal with the fact that we cannot really template into // protocol buffers... yuck. #define INSTANTIATE_GET_SINGLE_ARGUMENT(dtype, fieldname) \ template <> \ dtype OperatorBase::GetSingleArgument<dtype>( \ const string& name, const dtype& default_value) { \ if (arg_map_.count(name) == 0) { \ DVLOG(1) << "Using default parameter value " << default_value; \ return default_value; \ } \ CHECK(arg_map_[name]->has_##fieldname()) \ << "Argument does not have the right field: expected " \ << #fieldname; \ return arg_map_[name]->fieldname(); \ } INSTANTIATE_GET_SINGLE_ARGUMENT(float, f) INSTANTIATE_GET_SINGLE_ARGUMENT(int, i) INSTANTIATE_GET_SINGLE_ARGUMENT(string, s) // Undefine the argument just to be safe. #undef INSTANTIATE_GET_SINGLE_ARGUMENT #define INSTANTIATE_GET_REPEATED_ARGUMENT(dtype, fieldname) \ template <> \ vector<dtype> OperatorBase::GetRepeatedArgument<dtype>( \ const string& name) { \ if (arg_map_.count(name) == 0) { \ return vector<dtype>(); \ } \ vector<dtype> values; \ for (const auto& v : arg_map_[name]->fieldname()) values.push_back(v); \ return values; \ } INSTANTIATE_GET_REPEATED_ARGUMENT(float, floats) INSTANTIATE_GET_REPEATED_ARGUMENT(int, ints) INSTANTIATE_GET_REPEATED_ARGUMENT(string, strings) #undef INSTANTIATE_GET_REPEATED_ARGUMENT bool OperatorBase::Verify() { // Check Blob counts. if (operator_def_.input_size() < MinInput() || operator_def_.input_size() > MaxInput()) { LOG(ERROR) << "Input size " << operator_def_.input_size() << " not in range [min=" << MinInput() << ", max=" << MaxInput() << "]."; LOG(ERROR) << "Error at operator " << operator_def_.name() << ":" << operator_def_.type(); return false; } if (operator_def_.output_size() < MinOutput() || operator_def_.output_size() > MaxOutput()) { LOG(ERROR) << "Output size " << operator_def_.output_size() << " not in range [min=" << MinOutput() << ", max=" << MaxOutput() << "]."; LOG(ERROR) << "Error at operator " << operator_def_.name() << ":" << operator_def_.type(); return false; } return true; } OperatorBase* CreateOperator(const OperatorDef& operator_def, Workspace* ws) { const string& key = operator_def.type(); switch (operator_def.device_option().device_type()) { case CPU: VLOG(1) << "Creating CPU operator " << key; return CPUOperatorRegistry()->Create(key, operator_def, ws); case CUDA: VLOG(1) << "Creating CUDA operator " << key; return CUDAOperatorRegistry()->Create(key, operator_def, ws); case CUDNN: VLOG(1) << "Using CuDNN implementation."; return CUDNNOperatorRegistry()->Create(key, operator_def, ws); } // Just to suppress some compiler error return nullptr; } DEFINE_REGISTRY(CPUOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); DEFINE_REGISTRY(CUDAOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); DEFINE_REGISTRY(CUDNNOperatorRegistry, OperatorBase, const OperatorDef&, Workspace*); } // namespace caffe2 <|endoftext|>
<commit_before>// // NuoMaterial.cpp // ModelViewer // // Created by middleware on 8/28/16. // Copyright © 2016 middleware. All rights reserved. // #include "NuoMaterial.h" NuoMaterial::NuoMaterial() : id(-1) { } NuoMaterial::NuoMaterial(const tinyobj::material_t& material) : id(0), ambient_texname(material.ambient_texname), diffuse_texname(material.diffuse_texname), specular_texname(material.specular_texname), specular_highlight_texname(material.specular_highlight_texname), bump_texname(material.bump_texname), displacement_texname(material.displacement_texname), alpha_texname(material.alpha_texname), // PBR extension roughness_texname(material.roughness_texname), metallic_texname(material.metallic_texname), sheen_texname(material.sheen_texname), emissive_texname(material.emissive_texname), normal_texname(material.normal_texname) { } bool NuoMaterial::operator < (const NuoMaterial& other) const { if (id < other.id) return true; if (id > other.id) return false; return (ambient_texname < other.ambient_texname && diffuse_texname < other.diffuse_texname && specular_texname < other.specular_texname && specular_highlight_texname < other.specular_texname && bump_texname < other.bump_texname && displacement_texname < other.displacement_texname && alpha_texname < other.alpha_texname && // PBR extension roughness_texname < other.roughness_texname && metallic_texname < other.metallic_texname && sheen_texname < other.sheen_texname && emissive_texname < other.emissive_texname && normal_texname < other.normal_texname); } <commit_msg>Fix the comparer of materials.<commit_after>// // NuoMaterial.cpp // ModelViewer // // Created by middleware on 8/28/16. // Copyright © 2016 middleware. All rights reserved. // #include "NuoMaterial.h" NuoMaterial::NuoMaterial() : id(-1) { } NuoMaterial::NuoMaterial(const tinyobj::material_t& material) : id(0), ambient_texname(material.ambient_texname), diffuse_texname(material.diffuse_texname), specular_texname(material.specular_texname), specular_highlight_texname(material.specular_highlight_texname), bump_texname(material.bump_texname), displacement_texname(material.displacement_texname), alpha_texname(material.alpha_texname), // PBR extension roughness_texname(material.roughness_texname), metallic_texname(material.metallic_texname), sheen_texname(material.sheen_texname), emissive_texname(material.emissive_texname), normal_texname(material.normal_texname) { } bool NuoMaterial::operator < (const NuoMaterial& other) const { if (id < other.id) return true; if (id > other.id) return false; return (ambient_texname < other.ambient_texname || diffuse_texname < other.diffuse_texname || specular_texname < other.specular_texname || specular_highlight_texname < other.specular_texname || bump_texname < other.bump_texname || displacement_texname < other.displacement_texname || alpha_texname < other.alpha_texname || // PBR extension roughness_texname < other.roughness_texname || metallic_texname < other.metallic_texname || sheen_texname < other.sheen_texname || emissive_texname < other.emissive_texname || normal_texname < other.normal_texname); } <|endoftext|>
<commit_before>/// /// @file int128.cpp /// @brief Test int128_t and uint128_t types. /// /// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <int128_t.hpp> #include <stdint.h> #include <cassert> #include <iostream> #include <type_traits> using namespace std; using namespace primecount; #if defined(HAVE_INT128_T) #include <cstdlib> #include <sstream> #include <string> void check(bool OK) { cout << " " << (OK ? "OK" : "ERROR") << "\n"; if (!OK) exit(1); } #endif int main() { static_assert(prt::numeric_limits<int8_t>::max() == std::numeric_limits<int8_t>::max(), "prt::numeric_limits<int8_t>::max() is broken"); static_assert(prt::numeric_limits<uint64_t>::max() == std::numeric_limits<uint64_t>::max(), "prt::numeric_limits<uint64_t>::max() is broken"); static_assert(prt::is_integral<uint64_t>::value, "prt::is_integral<uint64_t> != true"); static_assert(!prt::is_integral<double>::value, "prt::is_integral<double> != false"); static_assert(prt::is_signed<int64_t>::value, "prt::is_signed<int64_t> != true"); static_assert(!prt::is_signed<uint64_t>::value, "prt::is_signed<uint64_t> != false"); static_assert(!prt::is_unsigned<int64_t>::value, "prt::is_unsigned<int64_t> != false"); static_assert(prt::is_unsigned<uint64_t>::value, "prt::is_unsigned<uint64_t> != true"); static_assert(std::is_same<typename prt::make_signed<uint64_t>::type, int64_t>::value, "prt::make_signed<uint64_t> != int64_t"); #if defined(HAVE_INT128_T) static_assert(prt::numeric_limits<uint128_t>::max() == ~((uint128_t) 0), "prt::numeric_limits<uint128_t>::max() is broken"); static_assert(prt::is_integral<int128_t>::value, "prt::is_integral<int128_t> != true"); static_assert(prt::is_integral<uint128_t>::value, "prt::is_integral<uint128_t> != true"); static_assert(prt::is_signed<int128_t>::value, "prt::is_signed<int128_t> != true"); static_assert(!prt::is_signed<uint128_t>::value, "prt::is_signed<uint128_t> != false"); static_assert(!prt::is_unsigned<int128_t>::value, "prt::is_unsigned<int128_t> != false"); static_assert(prt::is_unsigned<uint128_t>::value, "prt::is_unsigned<uint128_t> != true"); static_assert(std::is_same<typename prt::make_signed<int128_t>::type, int128_t>::value, "prt::make_signed<int128_t> != int128_t"); static_assert(std::is_same<typename prt::make_signed<uint128_t>::type, int128_t>::value, "prt::make_signed<uint128_t> != int128_t"); { ostringstream s; s << (((int128_t) 1 ) << 100); cout << "2^100 = " << s.str(); check(s.str() == "1267650600228229401496703205376"); } { ostringstream s; s << prt::numeric_limits<int128_t>::min(); cout << "-2^127 = " << s.str(); check(s.str() == "-170141183460469231731687303715884105728"); } { ostringstream s; s << prt::numeric_limits<int128_t>::max(); cout << "2^127-1 = " << s.str(); check(s.str() == "170141183460469231731687303715884105727"); } { ostringstream s; s << prt::numeric_limits<uint128_t>::max(); cout << "2^128-1 = " << s.str(); check(s.str() == "340282366920938463463374607431768211455"); } #endif cout << endl; cout << "All tests passed successfully!" << endl; return 0; } <commit_msg>Fix undefined behaviour<commit_after>/// /// @file int128.cpp /// @brief Test int128_t and uint128_t types. /// /// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <int128_t.hpp> #include <stdint.h> #include <cassert> #include <iostream> #include <type_traits> using namespace std; using namespace primecount; #if defined(HAVE_INT128_T) #include <cstdlib> #include <sstream> #include <string> void check(bool OK) { cout << " " << (OK ? "OK" : "ERROR") << "\n"; if (!OK) exit(1); } #endif int main() { static_assert(prt::numeric_limits<int8_t>::max() == std::numeric_limits<int8_t>::max(), "prt::numeric_limits<int8_t>::max() is broken"); static_assert(prt::numeric_limits<uint64_t>::max() == std::numeric_limits<uint64_t>::max(), "prt::numeric_limits<uint64_t>::max() is broken"); static_assert(prt::is_integral<uint64_t>::value, "prt::is_integral<uint64_t> != true"); static_assert(!prt::is_integral<double>::value, "prt::is_integral<double> != false"); static_assert(prt::is_signed<int64_t>::value, "prt::is_signed<int64_t> != true"); static_assert(!prt::is_signed<uint64_t>::value, "prt::is_signed<uint64_t> != false"); static_assert(!prt::is_unsigned<int64_t>::value, "prt::is_unsigned<int64_t> != false"); static_assert(prt::is_unsigned<uint64_t>::value, "prt::is_unsigned<uint64_t> != true"); static_assert(std::is_same<typename prt::make_signed<uint64_t>::type, int64_t>::value, "prt::make_signed<uint64_t> != int64_t"); #if defined(HAVE_INT128_T) static_assert(prt::numeric_limits<uint128_t>::max() == ~((uint128_t) 0), "prt::numeric_limits<uint128_t>::max() is broken"); static_assert(prt::is_integral<int128_t>::value, "prt::is_integral<int128_t> != true"); static_assert(prt::is_integral<uint128_t>::value, "prt::is_integral<uint128_t> != true"); static_assert(prt::is_signed<int128_t>::value, "prt::is_signed<int128_t> != true"); static_assert(!prt::is_signed<uint128_t>::value, "prt::is_signed<uint128_t> != false"); static_assert(!prt::is_unsigned<int128_t>::value, "prt::is_unsigned<int128_t> != false"); static_assert(prt::is_unsigned<uint128_t>::value, "prt::is_unsigned<uint128_t> != true"); static_assert(std::is_same<typename prt::make_signed<int128_t>::type, int128_t>::value, "prt::make_signed<int128_t> != int128_t"); static_assert(std::is_same<typename prt::make_signed<uint128_t>::type, int128_t>::value, "prt::make_signed<uint128_t> != int128_t"); { ostringstream s; s << (((int128_t) 1 ) << 100); cout << "2^100 = " << s.str(); check(s.str() == "1267650600228229401496703205376"); } { ostringstream s; s << prt::numeric_limits<int128_t>::min() + 1; cout << "-2^127+1 = " << s.str(); check(s.str() == "-170141183460469231731687303715884105727"); } { ostringstream s; s << prt::numeric_limits<int128_t>::max(); cout << "2^127-1 = " << s.str(); check(s.str() == "170141183460469231731687303715884105727"); } { ostringstream s; s << prt::numeric_limits<uint128_t>::max(); cout << "2^128-1 = " << s.str(); check(s.str() == "340282366920938463463374607431768211455"); } #endif cout << endl; cout << "All tests passed successfully!" << endl; return 0; } <|endoftext|>
<commit_before>#include "catch.hpp" #include "etl/fast_matrix.hpp" //{{{ Init tests TEST_CASE( "fast_matrix/init_1", "fast_matrix::fast_matrix(T)" ) { etl::fast_matrix<double, 2, 2> test_matrix(3.3); REQUIRE(test_matrix.size() == 4); for(std::size_t i = 0; i < test_matrix.size(); ++i){ REQUIRE(test_matrix[i] == 3.3); } } TEST_CASE( "fast_matrix/init_2", "fast_matrix::operator=(T)" ) { etl::fast_matrix<double, 2, 2> test_matrix; test_matrix = 3.3; REQUIRE(test_matrix.size() == 4); for(std::size_t i = 0; i < test_matrix.size(); ++i){ REQUIRE(test_matrix[i] == 3.3); } } TEST_CASE( "fast_matrix/init_3", "fast_matrix::fast_matrix(initializer_list)" ) { etl::fast_matrix<double, 2, 2> test_matrix = {1.0, 3.0, 5.0, 2.0}; REQUIRE(test_matrix.size() == 4); REQUIRE(test_matrix[0] == 1.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 5.0); } //}}} Init tests //{{{ Binary operators test TEST_CASE( "fast_matrix/add_scalar_1", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = 1.0 + test_matrix; REQUIRE(test_matrix[0] == 0.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 6.5); } TEST_CASE( "fast_matrix/add_scalar_2", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = test_matrix + 1.0; REQUIRE(test_matrix[0] == 0.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 6.5); } TEST_CASE( "fast_matrix/add", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a + b; REQUIRE(c[0] == 1.5); REQUIRE(c[1] == 5.0); REQUIRE(c[2] == 9.0); } TEST_CASE( "fast_matrix/sub_scalar_1", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = 1.0 - test_matrix; REQUIRE(test_matrix[0] == 2.0); REQUIRE(test_matrix[1] == -1.0); REQUIRE(test_matrix[2] == -4.5); } TEST_CASE( "fast_matrix/sub_scalar_2", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = test_matrix - 1.0; REQUIRE(test_matrix[0] == -2.0); REQUIRE(test_matrix[1] == 1.0); REQUIRE(test_matrix[2] == 4.5); } TEST_CASE( "fast_matrix/sub", "fast_matrix::operator-" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a - b; REQUIRE(c[0] == -3.5); REQUIRE(c[1] == -1.0); REQUIRE(c[2] == 1.0); } TEST_CASE( "fast_matrix/mul_scalar_1", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = 2.5 * test_matrix; REQUIRE(test_matrix[0] == -2.5); REQUIRE(test_matrix[1] == 5.0); REQUIRE(test_matrix[2] == 12.5); } TEST_CASE( "fast_matrix/mul_scalar_2", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = test_matrix * 2.5; REQUIRE(test_matrix[0] == -2.5); REQUIRE(test_matrix[1] == 5.0); REQUIRE(test_matrix[2] == 12.5); } TEST_CASE( "fast_matrix/mul", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a * b; REQUIRE(c[0] == -2.5); REQUIRE(c[1] == 6.0); REQUIRE(c[2] == 20.0); } TEST_CASE( "fast_matrix/div_scalar_1", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = test_matrix / 2.5; REQUIRE(test_matrix[0] == -1.0 / 2.5); REQUIRE(test_matrix[1] == 2.0 / 2.5); REQUIRE(test_matrix[2] == 5.0 / 2.5); } TEST_CASE( "fast_matrix/div_scalar_2", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = 2.5 / test_matrix; REQUIRE(test_matrix[0] == 2.5 / -1.0); REQUIRE(test_matrix[1] == 2.5 / 2.0); REQUIRE(test_matrix[2] == 2.5 / 5.0); } TEST_CASE( "fast_matrix/div", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a / b; REQUIRE(c[0] == -1.0 / 2.5); REQUIRE(c[1] == 2.0 / 3.0); REQUIRE(c[2] == 5.0 / 4.0); } TEST_CASE( "fast_matrix/mod_scalar_1", "fast_matrix::operator%" ) { etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1}; test_matrix = test_matrix % 2; REQUIRE(test_matrix[0] == -1 % 2); REQUIRE(test_matrix[1] == 2 % 2); REQUIRE(test_matrix[2] == 5 % 2); } TEST_CASE( "fast_matrix/mod_scalar_2", "fast_matrix::operator%" ) { etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1}; test_matrix = 2 % test_matrix; REQUIRE(test_matrix[0] == 2 % -1); REQUIRE(test_matrix[1] == 2 % 2); REQUIRE(test_matrix[2] == 2 % 5); } TEST_CASE( "fast_matrix/mod", "fast_matrix::operator*" ) { etl::fast_matrix<int, 2, 2> a = {-1, 2, 5, 1}; etl::fast_matrix<int, 2, 2> b = {2, 3, 4, 1}; etl::fast_matrix<int, 2, 2> c = a % b; REQUIRE(c[0] == -1 % 2); REQUIRE(c[1] == 2 % 3); REQUIRE(c[2] == 5 % 4); } //}}} Binary operator tests //{{{ Unary operator tests TEST_CASE( "fast_matrix/log", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> d = log(a); REQUIRE(d[0] == log(-1.0)); REQUIRE(d[1] == log(2.0)); REQUIRE(d[2] == log(5.0)); } TEST_CASE( "fast_matrix/abs", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 2.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/sign", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = sign(a); REQUIRE(d[0] == -1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_unary", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0}; etl::fast_matrix<double, 2, 2> d = abs(sign(a)); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_binary_1", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a + a); REQUIRE(d[0] == 2.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_binary_2", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a) + a; REQUIRE(d[0] == 0.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } //}}} Unary operators test //{{{ Complex tests TEST_CASE( "fast_matrix/complex", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c); REQUIRE(d[0] == Approx(10.0)); REQUIRE(d[1] == Approx(5.0)); REQUIRE(d[2] == Approx(0.68627)); } TEST_CASE( "fast_matrix/complex_2", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c); REQUIRE(d[0] == Approx(10.0)); REQUIRE(d[1] == Approx(5.0)); REQUIRE(d[2] == Approx(5.8273)); } TEST_CASE( "fast_matrix/complex_3", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 / (a * b); REQUIRE(d[0] == Approx(-1.0)); REQUIRE(d[1] == Approx(0.416666)); REQUIRE(d[2] == Approx(0.125)); } //}}} Complex tests<commit_msg>Fix test<commit_after>#include "catch.hpp" #include "etl/fast_matrix.hpp" //{{{ Init tests TEST_CASE( "fast_matrix/init_1", "fast_matrix::fast_matrix(T)" ) { etl::fast_matrix<double, 2, 2> test_matrix(3.3); REQUIRE(test_matrix.size() == 4); for(std::size_t i = 0; i < test_matrix.size(); ++i){ REQUIRE(test_matrix[i] == 3.3); } } TEST_CASE( "fast_matrix/init_2", "fast_matrix::operator=(T)" ) { etl::fast_matrix<double, 2, 2> test_matrix; test_matrix = 3.3; REQUIRE(test_matrix.size() == 4); for(std::size_t i = 0; i < test_matrix.size(); ++i){ REQUIRE(test_matrix[i] == 3.3); } } TEST_CASE( "fast_matrix/init_3", "fast_matrix::fast_matrix(initializer_list)" ) { etl::fast_matrix<double, 2, 2> test_matrix = {1.0, 3.0, 5.0, 2.0}; REQUIRE(test_matrix.size() == 4); REQUIRE(test_matrix[0] == 1.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 5.0); } //}}} Init tests //{{{ Binary operators test TEST_CASE( "fast_matrix/add_scalar_1", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = 1.0 + test_matrix; REQUIRE(test_matrix[0] == 0.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 6.5); } TEST_CASE( "fast_matrix/add_scalar_2", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = test_matrix + 1.0; REQUIRE(test_matrix[0] == 0.0); REQUIRE(test_matrix[1] == 3.0); REQUIRE(test_matrix[2] == 6.5); } TEST_CASE( "fast_matrix/add", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a + b; REQUIRE(c[0] == 1.5); REQUIRE(c[1] == 5.0); REQUIRE(c[2] == 9.0); } TEST_CASE( "fast_matrix/sub_scalar_1", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = 1.0 - test_matrix; REQUIRE(test_matrix[0] == 2.0); REQUIRE(test_matrix[1] == -1.0); REQUIRE(test_matrix[2] == -4.5); } TEST_CASE( "fast_matrix/sub_scalar_2", "fast_matrix::operator+" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0}; test_matrix = test_matrix - 1.0; REQUIRE(test_matrix[0] == -2.0); REQUIRE(test_matrix[1] == 1.0); REQUIRE(test_matrix[2] == 4.5); } TEST_CASE( "fast_matrix/sub", "fast_matrix::operator-" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a - b; REQUIRE(c[0] == -3.5); REQUIRE(c[1] == -1.0); REQUIRE(c[2] == 1.0); } TEST_CASE( "fast_matrix/mul_scalar_1", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = 2.5 * test_matrix; REQUIRE(test_matrix[0] == -2.5); REQUIRE(test_matrix[1] == 5.0); REQUIRE(test_matrix[2] == 12.5); } TEST_CASE( "fast_matrix/mul_scalar_2", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = test_matrix * 2.5; REQUIRE(test_matrix[0] == -2.5); REQUIRE(test_matrix[1] == 5.0); REQUIRE(test_matrix[2] == 12.5); } TEST_CASE( "fast_matrix/mul", "fast_matrix::operator*" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a * b; REQUIRE(c[0] == -2.5); REQUIRE(c[1] == 6.0); REQUIRE(c[2] == 20.0); } TEST_CASE( "fast_matrix/div_scalar_1", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = test_matrix / 2.5; REQUIRE(test_matrix[0] == -1.0 / 2.5); REQUIRE(test_matrix[1] == 2.0 / 2.5); REQUIRE(test_matrix[2] == 5.0 / 2.5); } TEST_CASE( "fast_matrix/div_scalar_2", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0}; test_matrix = 2.5 / test_matrix; REQUIRE(test_matrix[0] == 2.5 / -1.0); REQUIRE(test_matrix[1] == 2.5 / 2.0); REQUIRE(test_matrix[2] == 2.5 / 5.0); } TEST_CASE( "fast_matrix/div", "fast_matrix::operator/" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = a / b; REQUIRE(c[0] == -1.0 / 2.5); REQUIRE(c[1] == 2.0 / 3.0); REQUIRE(c[2] == 5.0 / 4.0); } TEST_CASE( "fast_matrix/mod_scalar_1", "fast_matrix::operator%" ) { etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1}; test_matrix = test_matrix % 2; REQUIRE(test_matrix[0] == -1 % 2); REQUIRE(test_matrix[1] == 2 % 2); REQUIRE(test_matrix[2] == 5 % 2); } TEST_CASE( "fast_matrix/mod_scalar_2", "fast_matrix::operator%" ) { etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1}; test_matrix = 2 % test_matrix; REQUIRE(test_matrix[0] == 2 % -1); REQUIRE(test_matrix[1] == 2 % 2); REQUIRE(test_matrix[2] == 2 % 5); } TEST_CASE( "fast_matrix/mod", "fast_matrix::operator*" ) { etl::fast_matrix<int, 2, 2> a = {-1, 2, 5, 1}; etl::fast_matrix<int, 2, 2> b = {2, 3, 4, 1}; etl::fast_matrix<int, 2, 2> c = a % b; REQUIRE(c[0] == -1 % 2); REQUIRE(c[1] == 2 % 3); REQUIRE(c[2] == 5 % 4); } //}}} Binary operator tests //{{{ Unary operator tests TEST_CASE( "fast_matrix/log", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> d = log(a); REQUIRE(d[0] == log(-1.0)); REQUIRE(d[1] == log(2.0)); REQUIRE(d[2] == log(5.0)); } TEST_CASE( "fast_matrix/abs", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 2.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/sign", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = sign(a); REQUIRE(d[0] == -1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_unary", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 3.0}; etl::fast_matrix<double, 2, 2> d = abs(sign(a)); REQUIRE(d[0] == 1.0); REQUIRE(d[1] == 1.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_binary_1", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a + a); REQUIRE(d[0] == 2.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } TEST_CASE( "fast_matrix/unary_binary_2", "fast_matrix::abs" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<double, 2, 2> d = abs(a) + a; REQUIRE(d[0] == 0.0); REQUIRE(d[1] == 4.0); REQUIRE(d[2] == 0.0); } //}}} Unary operators test //{{{ Complex tests TEST_CASE( "fast_matrix/complex", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c); REQUIRE(d[0] == Approx(10.0)); REQUIRE(d[1] == Approx(5.0)); REQUIRE(d[2] == Approx(0.68627)); } TEST_CASE( "fast_matrix/complex_2", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c); REQUIRE(d[0] == Approx(10.0)); REQUIRE(d[1] == Approx(5.0)); REQUIRE(d[2] == Approx(5.8273)); } TEST_CASE( "fast_matrix/complex_3", "fast_matrix::complex" ) { etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0}; etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0}; etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0}; etl::fast_matrix<double, 2, 2> d = 2.5 / (a * b); REQUIRE(d[0] == Approx(-1.0)); REQUIRE(d[1] == Approx(0.416666)); REQUIRE(d[2] == Approx(0.125)); } //}}} Complex tests<|endoftext|>
<commit_before>#include "../include/process.h" #include "../include/sandbox.h" #include <gtest/gtest.h> #include <sys/syscall.h> TEST (Sandbox, run) { Sandbox sandbox; constexpr size_t MEM_LIMIT = 16 << 20; // 16 MB (in bytes) constexpr timespec REAL_TIME_LIMIT = {0, (int)0.5e9}; // 0.5 s constexpr timespec CPU_TIME_LIMIT = {0, (int)0.2e9}; // 0.2 s Sandbox::Options opts { -1, -1, -1, REAL_TIME_LIMIT, MEM_LIMIT, CPU_TIME_LIMIT }; // Compiled test case executable InplaceBuff<40> exec("/tmp/simlib.test.sandbox.XXXXXX"); { int fd = mkstemp(exec.data()); if (fd == -1) THROW("mkstemp()", errmsg()); sclose(fd); } FileRemover exec_remover(exec.to_cstr()); const auto test_cases_dir = concat(getExecDir(getpid()), "sandbox_test_cases/"); auto compile_test_case = [&] (StringView case_filename) { Spawner::ExitStat es = Spawner::run("cc", { "cc", concat_tostr(test_cases_dir, case_filename), "-o", exec.to_string(), "-static", }, {-1, STDOUT_FILENO, STDERR_FILENO}); // Compilation must be successful throw_assert(es.si.code == CLD_EXITED and es.si.status == 0); }; Sandbox::ExitStat es; compile_test_case("1.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGKILL); EXPECT_EQ(es.message, "Memory limit exceeded"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("2.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGSEGV); EXPECT_EQ(es.message, "killed by signal 11 - Segmentation fault"); EXPECT_EQ(es.cpu_runtime, (timespec{0, 0})); EXPECT_EQ(es.runtime, (timespec{0, 0})); EXPECT_EQ(es.vm_peak, 0); compile_test_case("3.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_EXITED); EXPECT_EQ(es.si.status, 37); EXPECT_EQ(es.message, "exited with 37"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("4.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGKILL); EXPECT_EQ(es.message, concat_tostr("forbidden syscall: ", SYS_socket, " - socket")); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("5.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_DUMPED); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("6.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_DUMPED); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); // compile_test_case("6.c"); // not needed es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", OpenAccess::RDONLY}}); EXPECT_EQ(es.si.code, CLD_EXITED); EXPECT_EQ(es.si.status, 0); EXPECT_EQ(es.message, ""); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); for (auto perm : {OpenAccess::NONE, OpenAccess::WRONLY, OpenAccess::RDWR}) { // compile_test_case("6.c"); // not needed es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", perm}}); EXPECT_EQ(es.si.code, CLD_DUMPED); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); } } <commit_msg>Updated the sandbox unit tests, so that they allow killing or dumping by SIGABRT<commit_after>#include "../include/process.h" #include "../include/sandbox.h" #include <gtest/gtest.h> #include <sys/syscall.h> TEST (Sandbox, run) { Sandbox sandbox; constexpr size_t MEM_LIMIT = 16 << 20; // 16 MB (in bytes) constexpr timespec REAL_TIME_LIMIT = {0, (int)0.5e9}; // 0.5 s constexpr timespec CPU_TIME_LIMIT = {0, (int)0.2e9}; // 0.2 s Sandbox::Options opts { -1, -1, -1, REAL_TIME_LIMIT, MEM_LIMIT, CPU_TIME_LIMIT }; // Compiled test case executable InplaceBuff<40> exec("/tmp/simlib.test.sandbox.XXXXXX"); { int fd = mkstemp(exec.data()); if (fd == -1) THROW("mkstemp()", errmsg()); sclose(fd); } FileRemover exec_remover(exec.to_cstr()); const auto test_cases_dir = concat(getExecDir(getpid()), "sandbox_test_cases/"); auto compile_test_case = [&] (StringView case_filename) { Spawner::ExitStat es = Spawner::run("cc", { "cc", concat_tostr(test_cases_dir, case_filename), "-o", exec.to_string(), "-static", }, {-1, STDOUT_FILENO, STDERR_FILENO}); // Compilation must be successful throw_assert(es.si.code == CLD_EXITED and es.si.status == 0); }; Sandbox::ExitStat es; auto killed_or_dumped_by_abort = [&](decltype(es.si.code) si_code, const decltype(es.message)& message) { return ((si_code == CLD_KILLED and message == "killed by signal 6 - Aborted") or (si_code == CLD_DUMPED and message == "killed and dumped by signal 6 - Aborted")); }; compile_test_case("1.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGKILL); EXPECT_EQ(es.message, "Memory limit exceeded"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("2.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGSEGV); EXPECT_EQ(es.message, "killed by signal 11 - Segmentation fault"); EXPECT_EQ(es.cpu_runtime, (timespec{0, 0})); EXPECT_EQ(es.runtime, (timespec{0, 0})); EXPECT_EQ(es.vm_peak, 0); compile_test_case("3.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_EXITED); EXPECT_EQ(es.si.status, 37); EXPECT_EQ(es.message, "exited with 37"); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("4.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_EQ(es.si.code, CLD_KILLED); EXPECT_EQ(es.si.status, SIGKILL); EXPECT_EQ(es.message, concat_tostr("forbidden syscall: ", SYS_socket, " - socket")); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("5.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); compile_test_case("6.c"); es = sandbox.run(exec.to_cstr(), {}, opts); EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); // compile_test_case("6.c"); // not needed es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", OpenAccess::RDONLY}}); EXPECT_EQ(es.si.code, CLD_EXITED); EXPECT_EQ(es.si.status, 0); EXPECT_EQ(es.message, ""); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); for (auto perm : {OpenAccess::NONE, OpenAccess::WRONLY, OpenAccess::RDWR}) { // compile_test_case("6.c"); // not needed es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", perm}}); EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message); EXPECT_EQ(es.si.status, SIGABRT); EXPECT_LT((timespec{0, 0}), es.cpu_runtime); EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT); EXPECT_LT((timespec{0, 0}), es.runtime); EXPECT_LT(es.runtime, REAL_TIME_LIMIT); EXPECT_LT(0, es.vm_peak); EXPECT_LT(es.vm_peak, MEM_LIMIT); } } <|endoftext|>
<commit_before>#include "test.h" int main() { rangetree<u16, const char> tree; tree.add(1, 1, "one"); tree.add(1, 2, "two"); tree.add(1, 3, "three"); tree.finalize(); u32 res = tree.count(0, 1, 0, 1); printf("The number of points in x (0, 1) and y (0, 1) is %u\n", res); if (res != 1) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 0, 0, 1); if (res != 0) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 800, 0, 1); if (res != 1) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 800, 0, 2); if (res != 2) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 80, 0, 81); if (res != 3) fail("Count wrong, got %u, expected 1\n", res); std::vector<const char *> *joo = tree.search(0,500,2,600); printf("(0,500) (2,600) search got %ld results\n", joo->size()); for (u32 i = 0; i < joo->size(); i++) { printf("Node %u name %s\n", i, (*joo)[i]); } if (joo->size() != 2) fail("Search count wrong, got %u expected 2\n", joo->size()); return 0; } <commit_msg>Simple's errors were wrong<commit_after>#include "test.h" int main() { rangetree<u16, const char> tree; tree.add(1, 1, "one"); tree.add(1, 2, "two"); tree.add(1, 3, "three"); tree.finalize(); u32 res = tree.count(0, 1, 0, 1); printf("The number of points in x (0, 1) and y (0, 1) is %u\n", res); if (res != 1) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 0, 0, 1); if (res != 0) fail("Count wrong, got %u, expected 0\n", res); res = tree.count(0, 800, 0, 1); if (res != 1) fail("Count wrong, got %u, expected 1\n", res); res = tree.count(0, 800, 0, 2); if (res != 2) fail("Count wrong, got %u, expected 2\n", res); res = tree.count(0, 80, 0, 81); if (res != 3) fail("Count wrong, got %u, expected 3\n", res); std::vector<const char *> *joo = tree.search(0,500,2,600); printf("(0,500) (2,600) search got %ld results\n", joo->size()); for (u32 i = 0; i < joo->size(); i++) { printf("Node %u name %s\n", i, (*joo)[i]); } if (joo->size() != 2) fail("Search count wrong, got %u expected 2\n", joo->size()); return 0; } <|endoftext|>
<commit_before>include "test.haha" <commit_msg>Updates<commit_after><|endoftext|>
<commit_before>/* * A little test program for md5 code which does a md5 on all the * bytes sent to stdin. */ #include <string.h> #include <cstdlib> #include <string> #include <iostream> #include <fstream> #include <vector> #include <sstream> #include "../src/md5.h" /* * Print a signature */ static void print_sig(const unsigned char *sig) { const unsigned char* sig_p; for (sig_p = sig; sig_p < sig + MD5_SIZE; sig_p++) { (void)printf("%02x", *sig_p); } } /* * Read in from stdin and run MD5 on the input */ static void read_file(const char* filename) { unsigned char sig[MD5_SIZE]; char buffer[4096]; md5::md5_t md5; bool useCin; std::ifstream file; if (filename[0] == '-') { useCin = true; } else { useCin = false; file.open(filename, std::ios::binary); if (!file.is_open()) { std::cerr << "failed to open file " << filename << std::endl; exit(1); } } /* iterate over file */ if (useCin) { const char* input = filename + 1; std::cout << "Processing: '" << input << "'\n"; md5.process(input, strlen(input)); } else { do { file.read(buffer, 4096); md5.process(buffer, file.gcount()); } while (file); } md5.finish(sig); (void)printf("%25s '", "Resulting signature:"); print_sig(sig); (void)printf("'\n"); /* convert to string to print */ md5::sig_to_string(sig, buffer, sizeof(buffer)); (void)printf("%25s '%s'\n", "Results of md5_to_string:", buffer); /* now we convert it from string back into the sig */ md5::sig_from_string(sig, buffer); (void)printf("%25s '", "After md5_from_string:"); print_sig(sig); (void)printf("'\n"); } static void run_tests(void) { unsigned char sig[MD5_SIZE], sig2[MD5_SIZE]; char str[33]; /* MD5 Test Suite from RFC1321 */ std::vector<std::pair<const char*, const char*> > tests; tests.push_back(std::pair<const char*, const char*>("", "d41d8cd98f00b204e9800998ecf8427e")); tests.push_back(std::pair<const char*, const char*>("a", "0cc175b9c0f1b6a831c399e269772661")); tests.push_back(std::pair<const char*, const char*>("abc", "900150983cd24fb0d6963f7d28e17f72")); tests.push_back(std::pair<const char*, const char*>("message digest", "f96b697d7cb7938d525a2f31aaf161d0")); tests.push_back(std::pair<const char*, const char*>("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b")); tests.push_back(std::pair<const char*, const char*>("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f")); tests.push_back(std::pair<const char*, const char*>("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a")); tests.push_back(std::pair<const char*, const char*>("This string is precisely 56 characters long for a reason", "93d268e9bef6608ff1a6a96adbeee106")); tests.push_back(std::pair<const char*, const char*>("This string is exactly 64 characters long for a very good reason", "655c37c2c8451a60306d09f2971e49ff")); tests.push_back(std::pair<const char*, const char*>("This string is also a specific length. It is exactly 128 characters long for a very good reason as well. We are testing bounds.", "2ac62baa5be7fa36587c55691c026b35")); int passed = 0; int passed_h = 0; int passed_c = 0; /* run our tests */ for (unsigned int i = 0; i < tests.size(); i++) { bool passed_hash = 0; bool passed_convert = 0; std::cout << "Test: " << i << ": '" << tests[i].first << "'" << std::endl; std::cout << "Length: " << strlen(tests[i].first) << std::endl; /* calculate the sig for our test string */ md5::md5_t md5(tests[i].first, strlen(tests[i].first), sig); /* convert from the sig to a string rep */ md5::sig_to_string(sig, str, sizeof(str)); if (strcmp(str, tests[i].second) == 0) { std::cout << "Sig for '" << tests[i].first << "' matches '" << tests[i].second << "'" << std::endl; passed_hash = true; passed_h++; } else { std::cout << "ERROR: Sig for '" << tests[i].first << "' is '" << tests[i].second << "' not '" << str << "'" << std::endl; } /* convert from the string back into a MD5 signature */ md5::sig_from_string(sig2, str); if (memcmp(sig, sig2, MD5_SIZE) == 0) { std::cout << " String conversion also matches\n"; passed_convert = true; passed_c++; } else { std::cout << " ERROR: String conversion for '" << tests[i].second << "' failed\n"; } if (passed_hash and passed_convert) { passed++; } } std::cout << std::endl << "*******************************" << std::endl << " " << passed << " of " << tests.size() << " tests passed" << std::endl; if (passed != tests.size()) { std::cout << std::endl << " Please notify developer" << std::endl; std::cout << " " << passed_h << " passed hashing check" << std::endl << " " << passed_h << " passed comparison check" << std::endl; } std::cout << "*******************************" << std::endl; } /* * print the usage message */ static void usage(void) { (void)fprintf(stderr, "Usage: md5_t [-r file]\n"); exit(1); } int main(int argc, char **argv) { char do_read = 0; char* infile = NULL; argc--; argv++; /* process the args */ for (; *argv != NULL; argc--, argv++) { if (**argv != '-') { continue; } switch (*(*argv + 1)) { case 'r': do_read = 1; argc--; argv++; if (argc == 0) { usage(); } infile = *argv; break; default: usage(); break; } } if (argc > 0) { usage(); } /* do we need to read in from stdin */ if (do_read) { read_file(infile); } else { run_tests(); } return 0; } <commit_msg>removes erroneous includes<commit_after>/* * A little test program for md5 code which does a md5 on all the * bytes sent to stdin. */ #include <string.h> #include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include "../src/md5.h" /* * Print a signature */ static void print_sig(const unsigned char *sig) { const unsigned char* sig_p; for (sig_p = sig; sig_p < sig + MD5_SIZE; sig_p++) { (void)printf("%02x", *sig_p); } } /* * Read in from stdin and run MD5 on the input */ static void read_file(const char* filename) { unsigned char sig[MD5_SIZE]; char buffer[4096]; md5::md5_t md5; bool useCin; std::ifstream file; if (filename[0] == '-') { useCin = true; } else { useCin = false; file.open(filename, std::ios::binary); if (!file.is_open()) { std::cerr << "failed to open file " << filename << std::endl; exit(1); } } /* iterate over file */ if (useCin) { const char* input = filename + 1; std::cout << "Processing: '" << input << "'\n"; md5.process(input, strlen(input)); } else { do { file.read(buffer, 4096); md5.process(buffer, file.gcount()); } while (file); } md5.finish(sig); (void)printf("%25s '", "Resulting signature:"); print_sig(sig); (void)printf("'\n"); /* convert to string to print */ md5::sig_to_string(sig, buffer, sizeof(buffer)); (void)printf("%25s '%s'\n", "Results of md5_to_string:", buffer); /* now we convert it from string back into the sig */ md5::sig_from_string(sig, buffer); (void)printf("%25s '", "After md5_from_string:"); print_sig(sig); (void)printf("'\n"); } static void run_tests(void) { unsigned char sig[MD5_SIZE], sig2[MD5_SIZE]; char str[33]; /* MD5 Test Suite from RFC1321 */ std::vector<std::pair<const char*, const char*> > tests; tests.push_back(std::pair<const char*, const char*>("", "d41d8cd98f00b204e9800998ecf8427e")); tests.push_back(std::pair<const char*, const char*>("a", "0cc175b9c0f1b6a831c399e269772661")); tests.push_back(std::pair<const char*, const char*>("abc", "900150983cd24fb0d6963f7d28e17f72")); tests.push_back(std::pair<const char*, const char*>("message digest", "f96b697d7cb7938d525a2f31aaf161d0")); tests.push_back(std::pair<const char*, const char*>("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b")); tests.push_back(std::pair<const char*, const char*>("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f")); tests.push_back(std::pair<const char*, const char*>("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a")); tests.push_back(std::pair<const char*, const char*>("This string is precisely 56 characters long for a reason", "93d268e9bef6608ff1a6a96adbeee106")); tests.push_back(std::pair<const char*, const char*>("This string is exactly 64 characters long for a very good reason", "655c37c2c8451a60306d09f2971e49ff")); tests.push_back(std::pair<const char*, const char*>("This string is also a specific length. It is exactly 128 characters long for a very good reason as well. We are testing bounds.", "2ac62baa5be7fa36587c55691c026b35")); int passed = 0; int passed_h = 0; int passed_c = 0; /* run our tests */ for (unsigned int i = 0; i < tests.size(); i++) { bool passed_hash = 0; bool passed_convert = 0; std::cout << "Test: " << i << ": '" << tests[i].first << "'" << std::endl; std::cout << "Length: " << strlen(tests[i].first) << std::endl; /* calculate the sig for our test string */ md5::md5_t md5(tests[i].first, strlen(tests[i].first), sig); /* convert from the sig to a string rep */ md5::sig_to_string(sig, str, sizeof(str)); if (strcmp(str, tests[i].second) == 0) { std::cout << "Sig for '" << tests[i].first << "' matches '" << tests[i].second << "'" << std::endl; passed_hash = true; passed_h++; } else { std::cout << "ERROR: Sig for '" << tests[i].first << "' is '" << tests[i].second << "' not '" << str << "'" << std::endl; } /* convert from the string back into a MD5 signature */ md5::sig_from_string(sig2, str); if (memcmp(sig, sig2, MD5_SIZE) == 0) { std::cout << " String conversion also matches\n"; passed_convert = true; passed_c++; } else { std::cout << " ERROR: String conversion for '" << tests[i].second << "' failed\n"; } if (passed_hash and passed_convert) { passed++; } } std::cout << std::endl << "*******************************" << std::endl << " " << passed << " of " << tests.size() << " tests passed" << std::endl; if (passed != tests.size()) { std::cout << std::endl << " Please notify developer" << std::endl; std::cout << " " << passed_h << " passed hashing check" << std::endl << " " << passed_h << " passed comparison check" << std::endl; } std::cout << "*******************************" << std::endl; } /* * print the usage message */ static void usage(void) { (void)fprintf(stderr, "Usage: md5_t [-r file]\n"); exit(1); } int main(int argc, char **argv) { char do_read = 0; char* infile = NULL; argc--; argv++; /* process the args */ for (; *argv != NULL; argc--, argv++) { if (**argv != '-') { continue; } switch (*(*argv + 1)) { case 'r': do_read = 1; argc--; argv++; if (argc == 0) { usage(); } infile = *argv; break; default: usage(); break; } } if (argc > 0) { usage(); } /* do we need to read in from stdin */ if (do_read) { read_file(infile); } else { run_tests(); } return 0; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/PathControl.h" #include "ompl/geometric/PathGeometric.h" #include "ompl/base/samplers/UniformValidStateSampler.h" #include "ompl/util/Exception.h" #include <numeric> #include <cmath> ompl::control::PathControl::PathControl(const base::SpaceInformationPtr &si) : base::Path(si) { if (!dynamic_cast<const SpaceInformation*>(si_.get())) throw Exception("Cannot create a path with controls from a space that does not support controls"); } ompl::control::PathControl::PathControl(const PathControl &path) : base::Path(path.si_) { copyFrom(path); } ompl::geometric::PathGeometric ompl::control::PathControl::asGeometric(void) const { PathControl pc(*this); pc.interpolate(); geometric::PathGeometric pg(si_); pg.states.swap(pc.states); return pg; } ompl::control::PathControl& ompl::control::PathControl::operator=(const PathControl& other) { freeMemory(); si_ = other.si_; copyFrom(other); return *this; } void ompl::control::PathControl::copyFrom(const PathControl& other) { states.resize(other.states.size()); controls.resize(other.controls.size()); for (unsigned int i = 0 ; i < states.size() ; ++i) states[i] = si_->cloneState(other.states[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls.size() ; ++i) controls[i] = si->cloneControl(other.controls[i]); controlDurations = other.controlDurations; } double ompl::control::PathControl::length(void) const { return std::accumulate(controlDurations.begin(), controlDurations.end(), 0.0); } void ompl::control::PathControl::print(std::ostream &out) const { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); out << "Control path with " << states.size() << " states" << std::endl; for (unsigned int i = 0 ; i < controls.size() ; ++i) { out << "At state "; si_->printState(states[i], out); out << " apply control "; si->printControl(controls[i], out); out << " for " << (int)floor(0.5 + controlDurations[i]/res) << " steps" << std::endl; } out << "Arrive at state "; si_->printState(states[controls.size()], out); out << std::endl; } void ompl::control::PathControl::interpolate(void) { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); std::vector<base::State*> newStates; std::vector<Control*> newControls; std::vector<double> newControlDurations; double res = si->getPropagationStepSize(); for (unsigned int i = 0 ; i < controls.size() ; ++i) { int steps = (int)floor(0.5 + controlDurations[i] / res); assert(steps >= 0); if (steps <= 1) { newStates.push_back(states[i]); newControls.push_back(controls[i]); newControlDurations.push_back(controlDurations[i]); continue; } std::vector<base::State*> istates; si->propagate(states[i], controls[i], steps, istates, true); // last state is already in the non-interpolated path if (!istates.empty()) { si_->freeState(istates.back()); istates.pop_back(); } newStates.push_back(states[i]); newStates.insert(newStates.end(), istates.begin(), istates.end()); newControls.push_back(controls[i]); newControlDurations.push_back(res); for (int j = 1 ; j < steps; ++j) { newControls.push_back(si->cloneControl(controls[i])); newControlDurations.push_back(res); } } newStates.push_back(states[controls.size()]); states.swap(newStates); controls.swap(newControls); controlDurations.swap(newControlDurations); } bool ompl::control::PathControl::check(void) const { bool valid = true; const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); base::State *dummy = si_->allocState(); for (unsigned int i = 0 ; i < controls.size() ; ++i) { unsigned int steps = (unsigned int)floor(0.5 + controlDurations[i] / res); if (si->propagateWhileValid(states[i], controls[i], steps, dummy) != steps) { valid = false; break; } } si_->freeState(dummy); if (valid) for (unsigned int j = 0 ; j < states.size() ; ++j) if (!si_->isValid(states[j])) throw Exception("Internal error. This should not ever happen. Please contact the developers."); return valid; } void ompl::control::PathControl::random(void) { freeMemory(); states.resize(2); controlDurations.resize(1); controls.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states[0] = si->allocState(); states[1] = si->allocState(); controls[0] = si->allocControl(); base::ManifoldStateSamplerPtr ss = si->allocManifoldStateSampler(); ss->sampleUniform(states[0]); ControlSamplerPtr cs = si->allocControlSampler(); cs->sample(controls[0], states[0]); controlDurations[0] = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); si->propagate(states[0], controls[0], controlDurations[0], states[1]); } bool ompl::control::PathControl::randomValid(unsigned int attempts) { freeMemory(); states.resize(2); controlDurations.resize(1); controls.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states[0] = si->allocState(); states[1] = si->allocState(); controls[0] = si->allocControl(); ControlSamplerPtr cs = si->allocControlSampler(); base::UniformValidStateSampler *uvss = new base::UniformValidStateSampler(si); uvss->setNrAttempts(attempts); bool ok = false; for (unsigned int i = 0 ; i < attempts ; ++i) if (uvss->sample(states[0])) { cs->sample(controls[0], states[0]); controlDurations[0] = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); if (si->propagateWhileValid(states[0], controls[0], controlDurations[0], states[1]) == controlDurations[0]) { ok = true; break; } } delete uvss; if (!ok) { freeMemory(); states.clear(); controls.clear(); controlDurations.clear(); } return ok; } void ompl::control::PathControl::freeMemory(void) { for (unsigned int i = 0 ; i < states.size() ; ++i) si_->freeState(states[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls.size() ; ++i) si->freeControl(controls[i]); } <commit_msg>bugfix for random path generation<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/PathControl.h" #include "ompl/geometric/PathGeometric.h" #include "ompl/base/samplers/UniformValidStateSampler.h" #include "ompl/util/Exception.h" #include <numeric> #include <cmath> ompl::control::PathControl::PathControl(const base::SpaceInformationPtr &si) : base::Path(si) { if (!dynamic_cast<const SpaceInformation*>(si_.get())) throw Exception("Cannot create a path with controls from a space that does not support controls"); } ompl::control::PathControl::PathControl(const PathControl &path) : base::Path(path.si_) { copyFrom(path); } ompl::geometric::PathGeometric ompl::control::PathControl::asGeometric(void) const { PathControl pc(*this); pc.interpolate(); geometric::PathGeometric pg(si_); pg.states.swap(pc.states); return pg; } ompl::control::PathControl& ompl::control::PathControl::operator=(const PathControl& other) { freeMemory(); si_ = other.si_; copyFrom(other); return *this; } void ompl::control::PathControl::copyFrom(const PathControl& other) { states.resize(other.states.size()); controls.resize(other.controls.size()); for (unsigned int i = 0 ; i < states.size() ; ++i) states[i] = si_->cloneState(other.states[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls.size() ; ++i) controls[i] = si->cloneControl(other.controls[i]); controlDurations = other.controlDurations; } double ompl::control::PathControl::length(void) const { return std::accumulate(controlDurations.begin(), controlDurations.end(), 0.0); } void ompl::control::PathControl::print(std::ostream &out) const { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); out << "Control path with " << states.size() << " states" << std::endl; for (unsigned int i = 0 ; i < controls.size() ; ++i) { out << "At state "; si_->printState(states[i], out); out << " apply control "; si->printControl(controls[i], out); out << " for " << (int)floor(0.5 + controlDurations[i]/res) << " steps" << std::endl; } out << "Arrive at state "; si_->printState(states[controls.size()], out); out << std::endl; } void ompl::control::PathControl::interpolate(void) { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); std::vector<base::State*> newStates; std::vector<Control*> newControls; std::vector<double> newControlDurations; double res = si->getPropagationStepSize(); for (unsigned int i = 0 ; i < controls.size() ; ++i) { int steps = (int)floor(0.5 + controlDurations[i] / res); assert(steps >= 0); if (steps <= 1) { newStates.push_back(states[i]); newControls.push_back(controls[i]); newControlDurations.push_back(controlDurations[i]); continue; } std::vector<base::State*> istates; si->propagate(states[i], controls[i], steps, istates, true); // last state is already in the non-interpolated path if (!istates.empty()) { si_->freeState(istates.back()); istates.pop_back(); } newStates.push_back(states[i]); newStates.insert(newStates.end(), istates.begin(), istates.end()); newControls.push_back(controls[i]); newControlDurations.push_back(res); for (int j = 1 ; j < steps; ++j) { newControls.push_back(si->cloneControl(controls[i])); newControlDurations.push_back(res); } } newStates.push_back(states[controls.size()]); states.swap(newStates); controls.swap(newControls); controlDurations.swap(newControlDurations); } bool ompl::control::PathControl::check(void) const { bool valid = true; const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); base::State *dummy = si_->allocState(); for (unsigned int i = 0 ; i < controls.size() ; ++i) { unsigned int steps = (unsigned int)floor(0.5 + controlDurations[i] / res); if (si->propagateWhileValid(states[i], controls[i], steps, dummy) != steps) { valid = false; break; } } si_->freeState(dummy); if (valid) for (unsigned int j = 0 ; j < states.size() ; ++j) if (!si_->isValid(states[j])) throw Exception("Internal error. This should not ever happen. Please contact the developers."); return valid; } void ompl::control::PathControl::random(void) { freeMemory(); states.resize(2); controlDurations.resize(1); controls.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states[0] = si->allocState(); states[1] = si->allocState(); controls[0] = si->allocControl(); base::ManifoldStateSamplerPtr ss = si->allocManifoldStateSampler(); ss->sampleUniform(states[0]); ControlSamplerPtr cs = si->allocControlSampler(); cs->sample(controls[0], states[0]); unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); controlDurations[0] = steps * si->getPropagationStepSize(); si->propagate(states[0], controls[0], steps, states[1]); } bool ompl::control::PathControl::randomValid(unsigned int attempts) { freeMemory(); states.resize(2); controlDurations.resize(1); controls.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states[0] = si->allocState(); states[1] = si->allocState(); controls[0] = si->allocControl(); ControlSamplerPtr cs = si->allocControlSampler(); base::UniformValidStateSampler *uvss = new base::UniformValidStateSampler(si); uvss->setNrAttempts(attempts); bool ok = false; for (unsigned int i = 0 ; i < attempts ; ++i) if (uvss->sample(states[0])) { cs->sample(controls[0], states[0]); unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); controlDurations[0] = steps * si->getPropagationStepSize(); if (si->propagateWhileValid(states[0], controls[0], steps, states[1]) == steps) { ok = true; break; } } delete uvss; if (!ok) { freeMemory(); states.clear(); controls.clear(); controlDurations.clear(); } return ok; } void ompl::control::PathControl::freeMemory(void) { for (unsigned int i = 0 ; i < states.size() ; ++i) si_->freeState(states[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls.size() ; ++i) si->freeControl(controls[i]); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestPLYReaderTextureUV.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME Test of vtkPLYReader // .SECTION Description // #include "vtkPLYReader.h" #include "vtkDebugLeaks.h" #include "vtkActor.h" #include "vtkPNGReader.h" #include "vtkPolyDataMapper.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRegressionTestImage.h" #include "vtkTestUtilities.h" #include "vtkTexture.h" #include "vtkWindowToImageFilter.h" int TestPLYReaderTextureUV( int argc, char *argv[] ) { // Read file name. const char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/squareTextured.ply"); const char* fnameImg = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/vtk.png"); // Test if the reader thinks it can open the file. int canRead = vtkPLYReader::CanReadFile(fname); canRead = vtkPLYReader::CanReadFile(fnameImg); (void)canRead; // Create the reader. vtkPLYReader* reader = vtkPLYReader::New(); reader->SetFileName(fname); reader->Update(); delete [] fname; vtkPNGReader* readerImg = vtkPNGReader::New(); readerImg->SetFileName(fnameImg); readerImg->Update(); delete[] fnameImg; // Create the texture. vtkTexture* texture = vtkTexture::New(); texture->SetInputConnection(readerImg->GetOutputPort()); // Create a mapper. vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection(reader->GetOutputPort()); mapper->ScalarVisibilityOn(); // Create the actor. vtkActor* actor = vtkActor::New(); actor->SetMapper(mapper); actor->SetTexture(texture); // Basic visualisation. vtkRenderWindow* renWin = vtkRenderWindow::New(); vtkRenderer* ren = vtkRenderer::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); ren->AddActor(actor); ren->SetBackground(0,0,0); renWin->SetSize(300,300); // interact with data renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } actor->Delete(); mapper->Delete(); reader->Delete(); readerImg->Delete(); texture->Delete(); renWin->Delete(); ren->Delete(); iren->Delete(); return !retVal; } <commit_msg>Add return value check in the unit test.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestPLYReaderTextureUV.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME Test of vtkPLYReader // .SECTION Description // #include "vtkPLYReader.h" #include "vtkActor.h" #include "vtkPNGReader.h" #include "vtkPolyDataMapper.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRegressionTestImage.h" #include "vtkTestUtilities.h" #include "vtkTexture.h" int TestPLYReaderTextureUV( int argc, char *argv[] ) { // Read file name. const char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/squareTextured.ply"); const char* fnameImg = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/vtk.png"); // Test if the reader thinks it can open the file. if (0 == vtkPLYReader::CanReadFile(fname)) { std::cout << "The PLY reader can not read the input file." << std::endl; return EXIT_FAILURE; } // Create the reader. vtkPLYReader* reader = vtkPLYReader::New(); reader->SetFileName(fname); reader->Update(); delete [] fname; vtkPNGReader* readerImg = vtkPNGReader::New(); if (0 == readerImg->CanReadFile(fnameImg)) { std::cout << "The PNG reader can not read the input file." << std::endl; return EXIT_FAILURE; } readerImg->SetFileName(fnameImg); readerImg->Update(); delete[] fnameImg; // Create the texture. vtkTexture* texture = vtkTexture::New(); texture->SetInputConnection(readerImg->GetOutputPort()); // Create a mapper. vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection(reader->GetOutputPort()); mapper->ScalarVisibilityOn(); // Create the actor. vtkActor* actor = vtkActor::New(); actor->SetMapper(mapper); actor->SetTexture(texture); // Basic visualisation. vtkRenderWindow* renWin = vtkRenderWindow::New(); vtkRenderer* ren = vtkRenderer::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); ren->AddActor(actor); ren->SetBackground(0,0,0); renWin->SetSize(300,300); // interact with data renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } actor->Delete(); mapper->Delete(); reader->Delete(); readerImg->Delete(); texture->Delete(); renWin->Delete(); ren->Delete(); iren->Delete(); return !retVal; } <|endoftext|>
<commit_before>// Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Translation/IREEVM.h" #include "iree/compiler/Bindings/Native/Transforms/Passes.h" #include "iree/compiler/Bindings/TFLite/Transforms/Passes.h" #include "iree/compiler/ConstEval/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/Dialect/HAL/Transforms/Passes.h" #include "iree/compiler/Dialect/Stream/Transforms/Passes.h" #include "iree/compiler/Dialect/Util/Transforms/Passes.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Utils/PassUtils.h" #include "iree/compiler/Utils/TracingUtils.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "mlir/Translation.h" #ifdef IREE_HAVE_EMITC_DIALECT #include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h" #include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h" #endif // IREE_HAVE_EMITC_DIALECT namespace mlir { namespace iree_compiler { void BindingOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory bindingOptionsCategory( "IREE translation binding support options."); binder.opt<bool>( "iree-native-bindings-support", native, llvm::cl::desc( "Include runtime support for native IREE ABI-compatible bindings."), llvm::cl::cat(bindingOptionsCategory)); binder.opt<bool>("iree-tflite-bindings-support", tflite, llvm::cl::desc("Include runtime support for the IREE TFLite " "compatibility bindings."), llvm::cl::cat(bindingOptionsCategory)); } void InputDialectOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory inputDialectOptions( "IREE options for controlling the input transformations to apply."); binder.opt<InputDialectOptions::Type>( "iree-input-type", type, llvm::cl::desc("Specifies the input program representation."), llvm::cl::values( clEnumValN(InputDialectOptions::Type::none, "none", "No input dialect transformation."), clEnumValN(InputDialectOptions::Type::tosa, "tosa", "Legalize from TOSA ops."), clEnumValN(InputDialectOptions::Type::mhlo, "mhlo", "Legalize from MHLO ops."), clEnumValN( InputDialectOptions::Type::xla, "xla", "Legalize from MHLO ops (with XLA cleanup preprocessing).")), llvm::cl::cat(inputDialectOptions)); } void HighLevelOptimizationOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory category( "IREE options for controlling high level optimizations."); binder.opt<bool>( "iree-opt-const-eval", constEval, llvm::cl::desc("Enables eager evaluation of constants using the full " "compiler and runtime."), llvm::cl::cat(category)); binder.opt<bool>( "iree-opt-const-expr-hoisting", constExprHoisting, llvm::cl::desc( "Hoists the results of latent constant expressions into immutable " "global initializers for evaluation at program load."), llvm::cl::cat(category)); binder.opt<bool>( "iree-opt-numeric-precision-reduction", numericPrecisionReduction, llvm::cl::desc( "Reduces numeric precision to lower bit depths where possible."), llvm::cl::cat(category)); binder.opt<bool>("iree-opt-strip-assertions", stripAssertions, llvm::cl::desc("Strips debug assertions after any useful " "information has been extracted."), llvm::cl::cat(category)); } void SchedulingOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory category( "IREE options for controlling host/device scheduling."); binder.opt<DumpOutputFormat>( "iree-scheduling-dump-statistics-format", dumpStatisticsFormat, llvm::cl::desc("Dumps statistics in the specified output format."), llvm::cl::cat(category), llvm::cl::values( clEnumValN(DumpOutputFormat::Pretty, "pretty", "Human-readable pretty printed output."), clEnumValN(DumpOutputFormat::Verbose, "verbose", "Pretty printed output with additional IR."), clEnumValN(DumpOutputFormat::CSV, "csv", "Comma separated values."))); binder.opt<std::string>("iree-scheduling-dump-statistics-file", dumpStatisticsFile, llvm::cl::desc("File path to write statistics to; or " "`` for stderr or `-` for stdout."), llvm::cl::cat(category)); } void buildIREEVMTransformPassPipeline( BindingOptions bindingOptions, InputDialectOptions inputOptions, HighLevelOptimizationOptions highLevelOptimizationOptions, SchedulingOptions schedulingOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) { // Input pipelines can result in changes to the exported functions and types // and must run before generating bindings. // After input processing, there should only be IREE legal types in // signatures. switch (inputOptions.type) { case InputDialectOptions::Type::none: break; case InputDialectOptions::Type::tosa: buildTOSAInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::mhlo: MHLO::buildMHLOInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::xla: MHLO::buildXLACleanupPassPipeline(passManager); MHLO::buildMHLOInputConversionPassPipeline(passManager); break; } buildCommonInputConversionPassPipeline(passManager); // Now that inputs are legalized, generate wrapper for entry functions. if (bindingOptions.native) { IREE::ABI::buildTransformPassPipeline(passManager); } if (bindingOptions.tflite) { IREE::TFLite::buildTransformPassPipeline(passManager); } IREE::Flow::TransformOptions flowOptions; flowOptions.constExprHoisting = highLevelOptimizationOptions.constExprHoisting; if (highLevelOptimizationOptions.constEval) { flowOptions.buildConstEvalPassPipeline = [](OpPassManager &passManager) { passManager.addPass(ConstEval::createJitGlobalsPass()); }; } flowOptions.numericPrecisionReduction = highLevelOptimizationOptions.numericPrecisionReduction; if (highLevelOptimizationOptions.stripAssertions) { // Strip std.assert & co after we perform optimizations; prior to this we // may use the assertions to derive information during analysis. passManager.addPass(IREE::Util::createStripDebugOpsPass()); } IREE::Stream::TransformOptions streamOptions; // TODO(benvanik): find a way to share the enums w/o circular deps. streamOptions.dumpStatisticsFormat = (IREE::Stream::DumpOutputFormat)schedulingOptions.dumpStatisticsFormat; streamOptions.dumpStatisticsFile = schedulingOptions.dumpStatisticsFile; IREE::Flow::buildFlowTransformPassPipeline(passManager, flowOptions); IREE::Stream::buildStreamTransformPassPipeline(passManager, streamOptions); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); passManager.addPass(IREE::Util::createDropCompilerHintsPass()); } void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) { buildIREEVMTransformPassPipeline( BindingOptions::FromFlags::get(), InputDialectOptions::FromFlags::get(), HighLevelOptimizationOptions::FromFlags::get(), SchedulingOptions::FromFlags::get(), IREE::HAL::TargetOptions::FromFlags::get(), IREE::VM::TargetOptions::FromFlags::get(), passManager); } void registerIREEVMTransformPassPipeline() { PassPipelineRegistration<> transformPassPipeline( "iree-transformation-pipeline", "Runs the full IREE input to VM transformation pipeline", [](OpPassManager &passManager) { buildDefaultIREEVMTransformPassPipeline(passManager); }); } // Converts from our source to a vm.module in canonical form. // After this completes we have a non-bytecode-specific vm.module that we // could lower to other forms (LLVM IR, C, etc). static LogicalResult translateFromMLIRToVM( ModuleOp moduleOp, BindingOptions bindingOptions, InputDialectOptions inputOptions, HighLevelOptimizationOptions highLevelOptimizationOptions, SchedulingOptions schedulingOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); buildIREEVMTransformPassPipeline( bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, executableOptions, targetOptions, passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "conversion from source -> vm failed"; } return success(); } // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM bytecode module for loading at runtime. // // See iree/schemas/bytecode_module_def.fbs for the description of the // serialized module format. // // Exposed via the --iree-mlir-to-vm-bytecode-module translation. static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = BindingOptions::FromFlags::get(); auto inputOptions = InputDialectOptions::FromFlags::get(); auto highLevelOptimizationOptions = HighLevelOptimizationOptions::FromFlags::get(); auto schedulingOptions = SchedulingOptions::FromFlags::get(); auto halTargetOptions = IREE::HAL::TargetOptions::FromFlags::get(); auto vmTargetOptions = IREE::VM::TargetOptions::FromFlags::get(); auto bytecodeTargetOptions = IREE::VM::BytecodeTargetOptions::FromFlags::get(); auto result = translateFromMLIRToVM( moduleOp, bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output); } #ifdef IREE_HAVE_EMITC_DIALECT // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM C module. // // Exposed via the --iree-mlir-to-vm-c-module translation. static LogicalResult translateFromMLIRToVMCModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = BindingOptions::FromFlags::get(); auto inputOptions = InputDialectOptions::FromFlags::get(); auto highLevelOptimizationOptions = HighLevelOptimizationOptions::FromFlags::get(); auto schedulingOptions = SchedulingOptions::FromFlags::get(); auto halTargetOptions = IREE::HAL::TargetOptions::FromFlags::get(); auto vmTargetOptions = IREE::VM::TargetOptions::FromFlags::get(); auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags(); auto result = translateFromMLIRToVM( moduleOp, bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } // Serialize to c code. return mlir::iree_compiler::IREE::VM::translateModuleToC( moduleOp, cTargetOptions, output); } #endif // IREE_HAVE_EMITC_DIALECT void registerIREEVMTranslationFlags() { BindingOptions::FromFlags::get(); InputDialectOptions::FromFlags::get(); HighLevelOptimizationOptions::FromFlags::get(); IREE::HAL::TargetOptions::FromFlags::get(); IREE::VM::TargetOptions::FromFlags::get(); IREE::VM::BytecodeTargetOptions::FromFlags::get(); } void registerIREEVMTranslation() { registerIREEVMTranslationFlags(); TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags( "iree-mlir-to-vm-bytecode-module", translateFromMLIRToVMBytecodeModuleWithFlags); #ifdef IREE_HAVE_EMITC_DIALECT TranslateFromMLIRRegistration toVMCModuleWithFlags( "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags); #endif // IREE_HAVE_EMITC_DIALECT } } // namespace iree_compiler } // namespace mlir <commit_msg>Register `-iree-scheduling-dump-statistics-*` flags. (#8182)<commit_after>// Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Translation/IREEVM.h" #include "iree/compiler/Bindings/Native/Transforms/Passes.h" #include "iree/compiler/Bindings/TFLite/Transforms/Passes.h" #include "iree/compiler/ConstEval/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/Dialect/HAL/Transforms/Passes.h" #include "iree/compiler/Dialect/Stream/Transforms/Passes.h" #include "iree/compiler/Dialect/Util/Transforms/Passes.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Utils/PassUtils.h" #include "iree/compiler/Utils/TracingUtils.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "mlir/Translation.h" #ifdef IREE_HAVE_EMITC_DIALECT #include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h" #include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h" #endif // IREE_HAVE_EMITC_DIALECT namespace mlir { namespace iree_compiler { void BindingOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory bindingOptionsCategory( "IREE translation binding support options."); binder.opt<bool>( "iree-native-bindings-support", native, llvm::cl::desc( "Include runtime support for native IREE ABI-compatible bindings."), llvm::cl::cat(bindingOptionsCategory)); binder.opt<bool>("iree-tflite-bindings-support", tflite, llvm::cl::desc("Include runtime support for the IREE TFLite " "compatibility bindings."), llvm::cl::cat(bindingOptionsCategory)); } void InputDialectOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory inputDialectOptions( "IREE options for controlling the input transformations to apply."); binder.opt<InputDialectOptions::Type>( "iree-input-type", type, llvm::cl::desc("Specifies the input program representation."), llvm::cl::values( clEnumValN(InputDialectOptions::Type::none, "none", "No input dialect transformation."), clEnumValN(InputDialectOptions::Type::tosa, "tosa", "Legalize from TOSA ops."), clEnumValN(InputDialectOptions::Type::mhlo, "mhlo", "Legalize from MHLO ops."), clEnumValN( InputDialectOptions::Type::xla, "xla", "Legalize from MHLO ops (with XLA cleanup preprocessing).")), llvm::cl::cat(inputDialectOptions)); } void HighLevelOptimizationOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory category( "IREE options for controlling high level optimizations."); binder.opt<bool>( "iree-opt-const-eval", constEval, llvm::cl::desc("Enables eager evaluation of constants using the full " "compiler and runtime."), llvm::cl::cat(category)); binder.opt<bool>( "iree-opt-const-expr-hoisting", constExprHoisting, llvm::cl::desc( "Hoists the results of latent constant expressions into immutable " "global initializers for evaluation at program load."), llvm::cl::cat(category)); binder.opt<bool>( "iree-opt-numeric-precision-reduction", numericPrecisionReduction, llvm::cl::desc( "Reduces numeric precision to lower bit depths where possible."), llvm::cl::cat(category)); binder.opt<bool>("iree-opt-strip-assertions", stripAssertions, llvm::cl::desc("Strips debug assertions after any useful " "information has been extracted."), llvm::cl::cat(category)); } void SchedulingOptions::bindOptions(OptionsBinder &binder) { static llvm::cl::OptionCategory category( "IREE options for controlling host/device scheduling."); binder.opt<DumpOutputFormat>( "iree-scheduling-dump-statistics-format", dumpStatisticsFormat, llvm::cl::desc("Dumps statistics in the specified output format."), llvm::cl::cat(category), llvm::cl::values( clEnumValN(DumpOutputFormat::Pretty, "pretty", "Human-readable pretty printed output."), clEnumValN(DumpOutputFormat::Verbose, "verbose", "Pretty printed output with additional IR."), clEnumValN(DumpOutputFormat::CSV, "csv", "Comma separated values."))); binder.opt<std::string>("iree-scheduling-dump-statistics-file", dumpStatisticsFile, llvm::cl::desc("File path to write statistics to; or " "`` for stderr or `-` for stdout."), llvm::cl::cat(category)); } void buildIREEVMTransformPassPipeline( BindingOptions bindingOptions, InputDialectOptions inputOptions, HighLevelOptimizationOptions highLevelOptimizationOptions, SchedulingOptions schedulingOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) { // Input pipelines can result in changes to the exported functions and types // and must run before generating bindings. // After input processing, there should only be IREE legal types in // signatures. switch (inputOptions.type) { case InputDialectOptions::Type::none: break; case InputDialectOptions::Type::tosa: buildTOSAInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::mhlo: MHLO::buildMHLOInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::xla: MHLO::buildXLACleanupPassPipeline(passManager); MHLO::buildMHLOInputConversionPassPipeline(passManager); break; } buildCommonInputConversionPassPipeline(passManager); // Now that inputs are legalized, generate wrapper for entry functions. if (bindingOptions.native) { IREE::ABI::buildTransformPassPipeline(passManager); } if (bindingOptions.tflite) { IREE::TFLite::buildTransformPassPipeline(passManager); } IREE::Flow::TransformOptions flowOptions; flowOptions.constExprHoisting = highLevelOptimizationOptions.constExprHoisting; if (highLevelOptimizationOptions.constEval) { flowOptions.buildConstEvalPassPipeline = [](OpPassManager &passManager) { passManager.addPass(ConstEval::createJitGlobalsPass()); }; } flowOptions.numericPrecisionReduction = highLevelOptimizationOptions.numericPrecisionReduction; if (highLevelOptimizationOptions.stripAssertions) { // Strip std.assert & co after we perform optimizations; prior to this we // may use the assertions to derive information during analysis. passManager.addPass(IREE::Util::createStripDebugOpsPass()); } IREE::Stream::TransformOptions streamOptions; // TODO(benvanik): find a way to share the enums w/o circular deps. streamOptions.dumpStatisticsFormat = (IREE::Stream::DumpOutputFormat)schedulingOptions.dumpStatisticsFormat; streamOptions.dumpStatisticsFile = schedulingOptions.dumpStatisticsFile; IREE::Flow::buildFlowTransformPassPipeline(passManager, flowOptions); IREE::Stream::buildStreamTransformPassPipeline(passManager, streamOptions); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); passManager.addPass(IREE::Util::createDropCompilerHintsPass()); } void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) { buildIREEVMTransformPassPipeline( BindingOptions::FromFlags::get(), InputDialectOptions::FromFlags::get(), HighLevelOptimizationOptions::FromFlags::get(), SchedulingOptions::FromFlags::get(), IREE::HAL::TargetOptions::FromFlags::get(), IREE::VM::TargetOptions::FromFlags::get(), passManager); } void registerIREEVMTransformPassPipeline() { PassPipelineRegistration<> transformPassPipeline( "iree-transformation-pipeline", "Runs the full IREE input to VM transformation pipeline", [](OpPassManager &passManager) { buildDefaultIREEVMTransformPassPipeline(passManager); }); } // Converts from our source to a vm.module in canonical form. // After this completes we have a non-bytecode-specific vm.module that we // could lower to other forms (LLVM IR, C, etc). static LogicalResult translateFromMLIRToVM( ModuleOp moduleOp, BindingOptions bindingOptions, InputDialectOptions inputOptions, HighLevelOptimizationOptions highLevelOptimizationOptions, SchedulingOptions schedulingOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); buildIREEVMTransformPassPipeline( bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, executableOptions, targetOptions, passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "conversion from source -> vm failed"; } return success(); } // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM bytecode module for loading at runtime. // // See iree/schemas/bytecode_module_def.fbs for the description of the // serialized module format. // // Exposed via the --iree-mlir-to-vm-bytecode-module translation. static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = BindingOptions::FromFlags::get(); auto inputOptions = InputDialectOptions::FromFlags::get(); auto highLevelOptimizationOptions = HighLevelOptimizationOptions::FromFlags::get(); auto schedulingOptions = SchedulingOptions::FromFlags::get(); auto halTargetOptions = IREE::HAL::TargetOptions::FromFlags::get(); auto vmTargetOptions = IREE::VM::TargetOptions::FromFlags::get(); auto bytecodeTargetOptions = IREE::VM::BytecodeTargetOptions::FromFlags::get(); auto result = translateFromMLIRToVM( moduleOp, bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output); } #ifdef IREE_HAVE_EMITC_DIALECT // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM C module. // // Exposed via the --iree-mlir-to-vm-c-module translation. static LogicalResult translateFromMLIRToVMCModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = BindingOptions::FromFlags::get(); auto inputOptions = InputDialectOptions::FromFlags::get(); auto highLevelOptimizationOptions = HighLevelOptimizationOptions::FromFlags::get(); auto schedulingOptions = SchedulingOptions::FromFlags::get(); auto halTargetOptions = IREE::HAL::TargetOptions::FromFlags::get(); auto vmTargetOptions = IREE::VM::TargetOptions::FromFlags::get(); auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags(); auto result = translateFromMLIRToVM( moduleOp, bindingOptions, inputOptions, highLevelOptimizationOptions, schedulingOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } // Serialize to c code. return mlir::iree_compiler::IREE::VM::translateModuleToC( moduleOp, cTargetOptions, output); } #endif // IREE_HAVE_EMITC_DIALECT void registerIREEVMTranslationFlags() { BindingOptions::FromFlags::get(); InputDialectOptions::FromFlags::get(); HighLevelOptimizationOptions::FromFlags::get(); IREE::HAL::TargetOptions::FromFlags::get(); IREE::VM::TargetOptions::FromFlags::get(); IREE::VM::BytecodeTargetOptions::FromFlags::get(); SchedulingOptions::FromFlags::get(); } void registerIREEVMTranslation() { registerIREEVMTranslationFlags(); TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags( "iree-mlir-to-vm-bytecode-module", translateFromMLIRToVMBytecodeModuleWithFlags); #ifdef IREE_HAVE_EMITC_DIALECT TranslateFromMLIRRegistration toVMCModuleWithFlags( "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags); #endif // IREE_HAVE_EMITC_DIALECT } } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before> #include "tablemodelanovamodel.h" #include <QMimeData> #include <QDebug> #include "qutils.h" #include <boost/foreach.hpp> #include "options/optionboolean.h" using namespace std; TableModelAnovaModel::TableModelAnovaModel(QObject *parent) : TableModel(parent) { _boundTo = NULL; _terms.setSortParent(_variables); } QVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const { if (_boundTo == NULL || index.isValid() == false) return QVariant(); if (role == Qt::DisplayRole) { int colNo = index.column(); int rowNo = index.row(); Options *row = _rows.at(rowNo); if (colNo == 0) { OptionTerms *termOption = static_cast<OptionTerms *>(row->get(0)); Term t(termOption->value().front()); return t.asQString(); } } else if (role == Qt::CheckStateRole) { int colNo = index.column(); int rowNo = index.row(); Options *row = _rows.at(rowNo); if (colNo == 1) { OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1)); return booleanOption->value() ? Qt::Checked : Qt::Unchecked; } } return QVariant(); } int TableModelAnovaModel::rowCount(const QModelIndex &) const { if (_boundTo == NULL) return 0; return _rows.size(); } int TableModelAnovaModel::columnCount(const QModelIndex &) const { if (_boundTo == NULL) return 0; return _boundTo->rowTemplate()->size(); } bool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() == false) return false; if (index.column() == 1 && role == Qt::CheckStateRole) { bool checked = value.toInt() == Qt::Checked; Options *row = _rows.at(index.row()); OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1)); booleanOption->setValue(checked); updateNuisances(checked); _boundTo->setValue(_rows); return true; } return false; } QStringList TableModelAnovaModel::mimeTypes() const { QStringList types; types << "application/vnd.list.term"; return types; } void TableModelAnovaModel::setVariables(const Terms &fixedFactors, const Terms &randomFactors, const Terms &covariates) { _fixedFactors = fixedFactors; _randomFactors = randomFactors; _covariates = covariates; Terms all; all.add(fixedFactors); all.add(randomFactors); all.add(covariates); _variables.set(all); emit variablesAvailableChanged(); } const Terms &TableModelAnovaModel::variables() const { return _variables; } void TableModelAnovaModel::bindTo(Option *option) { _boundTo = dynamic_cast<OptionsTable *>(option); beginResetModel(); _rows = _boundTo->value(); foreach (Options *row, _rows) { OptionTerm *nameOption = static_cast<OptionTerm*>(row->get(0)); vector<string> term = nameOption->term(); _terms.add(Term(term)); } endResetModel(); } void TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes) { // sort indices, and delete from end to beginning QModelIndexList sorted = indexes; qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>()); int lastRowDeleted = -1; Terms terms = _terms; foreach (const QModelIndex &index, sorted) { int rowNo = index.row(); if (rowNo != lastRowDeleted) terms.remove(index.row()); lastRowDeleted = rowNo; } setTerms(terms); } const Terms &TableModelAnovaModel::terms() const { return _terms; } void TableModelAnovaModel::addFixedFactors(const Terms &terms) { _fixedFactors.add(terms); _variables.add(terms); Terms existingTerms = _terms; Terms newTerms = _terms; newTerms.discardWhatDoesContainTheseComponents(_randomFactors); newTerms.discardWhatDoesContainTheseComponents(_covariates); existingTerms.add(newTerms.ffCombinations(terms)); setTerms(existingTerms); emit variablesAvailableChanged(); } void TableModelAnovaModel::addRandomFactors(const Terms &terms) { _randomFactors.add(terms); _variables.add(terms); Terms newTerms = _terms; newTerms.add(terms); setTerms(newTerms, true); emit variablesAvailableChanged(); } void TableModelAnovaModel::addCovariates(const Terms &terms) { _covariates.add(terms); _variables.add(terms); Terms newTerms = _terms; newTerms.add(terms); setTerms(newTerms); emit variablesAvailableChanged(); } void TableModelAnovaModel::removeVariables(const Terms &terms) { _variables.remove(terms); _fixedFactors.remove(terms); _randomFactors.remove(terms); _covariates.remove(terms); Terms newTerms = _terms; newTerms.discardWhatDoesContainTheseComponents(terms); setTerms(newTerms); emit variablesAvailableChanged(); } bool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_UNUSED(action); Q_UNUSED(row); Q_UNUSED(column); Q_UNUSED(parent); if (mimeTypes().contains("application/vnd.list.term")) { QByteArray encodedData = data->data("application/vnd.list.term"); QDataStream stream(&encodedData, QIODevice::ReadOnly); if (stream.atEnd()) return false; return true; } return false; } bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType) { if (action == Qt::IgnoreAction) return true; if ( ! canDropMimeData(data, action, row, column, parent)) return false; if ( ! data->hasFormat("application/vnd.list.term")) return false; QByteArray encodedData = data->data("application/vnd.list.term"); Terms dropped; dropped.setSortParent(_variables); dropped.set(encodedData); Terms newTerms; switch (assignType) { case Cross: newTerms = dropped.crossCombinations(); break; case Interaction: newTerms = dropped.wayCombinations(dropped.size()); break; case MainEffects: newTerms = dropped.wayCombinations(1); break; case All2Way: newTerms = dropped.wayCombinations(2); break; case All3Way: newTerms = dropped.wayCombinations(3); break; case All4Way: newTerms = dropped.wayCombinations(4); break; case All5Way: newTerms = dropped.wayCombinations(5); break; default: (void)newTerms; } assign(newTerms); return true; } bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { return dropMimeData(data, action, row, column, parent, Cross); } QMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const { /* returns dummy data. when the user drags entries away from this listbox * it means that they're deleting entries, so there's no point populating * this data object properly */ Q_UNUSED(indexes); QMimeData *mimeData = new QMimeData(); QByteArray encodedData; QDataStream dataStream(&encodedData, QIODevice::WriteOnly); dataStream << 0; mimeData->setData("application/vnd.list.term", encodedData); return mimeData; } Qt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const { if (index.isValid()) { if (index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled; else return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; } else { return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled; } } QVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { if (section == 0) return "Model Terms"; else if (section == 1) return "Is Nuisance"; } else { if (section == 1 && role == Qt::SizeHintRole) return QSize(50, -1); } } return QVariant(); } Qt::DropActions TableModelAnovaModel::supportedDropActions() const { return Qt::CopyAction; } Qt::DropActions TableModelAnovaModel::supportedDragActions() const { return Qt::MoveAction; } OptionTerm *TableModelAnovaModel::termOptionFromRow(Options *row) { return static_cast<OptionTerm *>(row->get(0)); } void TableModelAnovaModel::setTerms(const Terms &terms, bool newTermsAreNuisance) { _terms.set(terms); if (_boundTo == NULL) return; beginResetModel(); Terms::const_iterator itr; vector<Options *>::iterator otr; otr = _rows.begin(); while (otr != _rows.end()) { Options *row = *otr; OptionTerm *termCell = termOptionFromRow(row); Term existingTerm = Term(termCell->term()); bool shouldRemove = true; itr = terms.begin(); while (itr != terms.end()) { const Term &term = *itr; if (term == existingTerm) { shouldRemove = false; break; } itr++; } if (shouldRemove) { _rows.erase(otr); delete row; } else { otr++; } } itr = terms.begin(); for (int i = 0; i < terms.size(); i++) { const Term &term = *itr; if (i < _rows.size()) { otr = _rows.begin(); otr += i; Options *row = *otr; OptionTerm *termCell = termOptionFromRow(row); Term existingTerm = Term(termCell->term()); if (existingTerm != term) { Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone()); OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0)); termCell->setValue(term.scomponents()); if (row->size() > 1 && newTermsAreNuisance) { OptionBoolean *nuisance = static_cast<OptionBoolean *>(row->get(1)); nuisance->setValue(true); } _rows.insert(otr, row); } } else { Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone()); OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0)); termCell->setValue(term.scomponents()); if (row->size() > 1 && newTermsAreNuisance) { OptionBoolean *nuisance = static_cast<OptionBoolean *>(row->get(1)); nuisance->setValue(true); } _rows.push_back(row); } itr++; } updateNuisances(); _boundTo->setValue(_rows); endResetModel(); emit termsChanged(); } void TableModelAnovaModel::clear() { setTerms(Terms()); } void TableModelAnovaModel::assign(const Terms &terms) { Terms t = _terms; t.add(terms); setTerms(t); } void TableModelAnovaModel::updateNuisances(bool checked) { // if a higher order interaction is specified as nuisance, then all lower order terms should be changed to nuisance as well for (int i = 0; i < _rows.size(); i++) { Options *row = _rows.at(i); OptionTerm *termOption = static_cast<OptionTerm*>(row->get(0)); OptionBoolean *nuisanceOption = static_cast<OptionBoolean*>(row->get(1)); Term term = Term(termOption->term()); if (nuisanceOption->value() == checked) { for (int j = 0; j < _rows.size(); j++) { if (i == j) continue; Options *r = _rows.at(j); OptionTerm *tOption = static_cast<OptionTerm*>(r->get(0)); OptionBoolean *nOption = static_cast<OptionBoolean*>(r->get(1)); Term t = Term(tOption->term()); if (checked) { if (t.containsAny(term)) nOption->setValue(true); } else { if (t.containsAll(term)) nOption->setValue(false); } } } } emit dataChanged(this->index(0,1), this->index(_rows.size() - 1, 1)); } <commit_msg>B ANOVAs: Fix to nuisance checkbox behaviour<commit_after> #include "tablemodelanovamodel.h" #include <QMimeData> #include <QDebug> #include "qutils.h" #include <boost/foreach.hpp> #include "options/optionboolean.h" using namespace std; TableModelAnovaModel::TableModelAnovaModel(QObject *parent) : TableModel(parent) { _boundTo = NULL; _terms.setSortParent(_variables); } QVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const { if (_boundTo == NULL || index.isValid() == false) return QVariant(); if (role == Qt::DisplayRole) { int colNo = index.column(); int rowNo = index.row(); Options *row = _rows.at(rowNo); if (colNo == 0) { OptionTerms *termOption = static_cast<OptionTerms *>(row->get(0)); Term t(termOption->value().front()); return t.asQString(); } } else if (role == Qt::CheckStateRole) { int colNo = index.column(); int rowNo = index.row(); Options *row = _rows.at(rowNo); if (colNo == 1) { OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1)); return booleanOption->value() ? Qt::Checked : Qt::Unchecked; } } return QVariant(); } int TableModelAnovaModel::rowCount(const QModelIndex &) const { if (_boundTo == NULL) return 0; return _rows.size(); } int TableModelAnovaModel::columnCount(const QModelIndex &) const { if (_boundTo == NULL) return 0; return _boundTo->rowTemplate()->size(); } bool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() == false) return false; if (index.column() == 1 && role == Qt::CheckStateRole) { bool checked = value.toInt() == Qt::Checked; Options *row = _rows.at(index.row()); OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1)); booleanOption->setValue(checked); updateNuisances(checked); _boundTo->setValue(_rows); return true; } return false; } QStringList TableModelAnovaModel::mimeTypes() const { QStringList types; types << "application/vnd.list.term"; return types; } void TableModelAnovaModel::setVariables(const Terms &fixedFactors, const Terms &randomFactors, const Terms &covariates) { _fixedFactors = fixedFactors; _randomFactors = randomFactors; _covariates = covariates; Terms all; all.add(fixedFactors); all.add(randomFactors); all.add(covariates); _variables.set(all); emit variablesAvailableChanged(); } const Terms &TableModelAnovaModel::variables() const { return _variables; } void TableModelAnovaModel::bindTo(Option *option) { _boundTo = dynamic_cast<OptionsTable *>(option); beginResetModel(); _rows = _boundTo->value(); foreach (Options *row, _rows) { OptionTerm *nameOption = static_cast<OptionTerm*>(row->get(0)); vector<string> term = nameOption->term(); _terms.add(Term(term)); } endResetModel(); } void TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes) { // sort indices, and delete from end to beginning QModelIndexList sorted = indexes; qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>()); int lastRowDeleted = -1; Terms terms = _terms; foreach (const QModelIndex &index, sorted) { int rowNo = index.row(); if (rowNo != lastRowDeleted) terms.remove(index.row()); lastRowDeleted = rowNo; } setTerms(terms); } const Terms &TableModelAnovaModel::terms() const { return _terms; } void TableModelAnovaModel::addFixedFactors(const Terms &terms) { _fixedFactors.add(terms); _variables.add(terms); Terms existingTerms = _terms; Terms newTerms = _terms; newTerms.discardWhatDoesContainTheseComponents(_randomFactors); newTerms.discardWhatDoesContainTheseComponents(_covariates); existingTerms.add(newTerms.ffCombinations(terms)); setTerms(existingTerms); emit variablesAvailableChanged(); } void TableModelAnovaModel::addRandomFactors(const Terms &terms) { _randomFactors.add(terms); _variables.add(terms); Terms newTerms = _terms; newTerms.add(terms); setTerms(newTerms, true); emit variablesAvailableChanged(); } void TableModelAnovaModel::addCovariates(const Terms &terms) { _covariates.add(terms); _variables.add(terms); Terms newTerms = _terms; newTerms.add(terms); setTerms(newTerms); emit variablesAvailableChanged(); } void TableModelAnovaModel::removeVariables(const Terms &terms) { _variables.remove(terms); _fixedFactors.remove(terms); _randomFactors.remove(terms); _covariates.remove(terms); Terms newTerms = _terms; newTerms.discardWhatDoesContainTheseComponents(terms); setTerms(newTerms); emit variablesAvailableChanged(); } bool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_UNUSED(action); Q_UNUSED(row); Q_UNUSED(column); Q_UNUSED(parent); if (mimeTypes().contains("application/vnd.list.term")) { QByteArray encodedData = data->data("application/vnd.list.term"); QDataStream stream(&encodedData, QIODevice::ReadOnly); if (stream.atEnd()) return false; return true; } return false; } bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType) { if (action == Qt::IgnoreAction) return true; if ( ! canDropMimeData(data, action, row, column, parent)) return false; if ( ! data->hasFormat("application/vnd.list.term")) return false; QByteArray encodedData = data->data("application/vnd.list.term"); Terms dropped; dropped.setSortParent(_variables); dropped.set(encodedData); Terms newTerms; switch (assignType) { case Cross: newTerms = dropped.crossCombinations(); break; case Interaction: newTerms = dropped.wayCombinations(dropped.size()); break; case MainEffects: newTerms = dropped.wayCombinations(1); break; case All2Way: newTerms = dropped.wayCombinations(2); break; case All3Way: newTerms = dropped.wayCombinations(3); break; case All4Way: newTerms = dropped.wayCombinations(4); break; case All5Way: newTerms = dropped.wayCombinations(5); break; default: (void)newTerms; } assign(newTerms); return true; } bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { return dropMimeData(data, action, row, column, parent, Cross); } QMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const { /* returns dummy data. when the user drags entries away from this listbox * it means that they're deleting entries, so there's no point populating * this data object properly */ Q_UNUSED(indexes); QMimeData *mimeData = new QMimeData(); QByteArray encodedData; QDataStream dataStream(&encodedData, QIODevice::WriteOnly); dataStream << 0; mimeData->setData("application/vnd.list.term", encodedData); return mimeData; } Qt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const { if (index.isValid()) { if (index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled; else return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; } else { return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled; } } QVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { if (section == 0) return "Model Terms"; else if (section == 1) return "Is Nuisance"; } else { if (section == 1 && role == Qt::SizeHintRole) return QSize(50, -1); } } return QVariant(); } Qt::DropActions TableModelAnovaModel::supportedDropActions() const { return Qt::CopyAction; } Qt::DropActions TableModelAnovaModel::supportedDragActions() const { return Qt::MoveAction; } OptionTerm *TableModelAnovaModel::termOptionFromRow(Options *row) { return static_cast<OptionTerm *>(row->get(0)); } void TableModelAnovaModel::setTerms(const Terms &terms, bool newTermsAreNuisance) { _terms.set(terms); if (_boundTo == NULL) return; beginResetModel(); Terms::const_iterator itr; vector<Options *>::iterator otr; otr = _rows.begin(); while (otr != _rows.end()) { Options *row = *otr; OptionTerm *termCell = termOptionFromRow(row); Term existingTerm = Term(termCell->term()); bool shouldRemove = true; itr = terms.begin(); while (itr != terms.end()) { const Term &term = *itr; if (term == existingTerm) { shouldRemove = false; break; } itr++; } if (shouldRemove) { _rows.erase(otr); delete row; } else { otr++; } } itr = terms.begin(); for (int i = 0; i < terms.size(); i++) { const Term &term = *itr; if (i < _rows.size()) { otr = _rows.begin(); otr += i; Options *row = *otr; OptionTerm *termCell = termOptionFromRow(row); Term existingTerm = Term(termCell->term()); if (existingTerm != term) { Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone()); OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0)); termCell->setValue(term.scomponents()); if (row->size() > 1 && newTermsAreNuisance) { OptionBoolean *nuisance = static_cast<OptionBoolean *>(row->get(1)); nuisance->setValue(true); } _rows.insert(otr, row); } } else { Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone()); OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0)); termCell->setValue(term.scomponents()); if (row->size() > 1 && newTermsAreNuisance) { OptionBoolean *nuisance = static_cast<OptionBoolean *>(row->get(1)); nuisance->setValue(true); } _rows.push_back(row); } itr++; } updateNuisances(); _boundTo->setValue(_rows); endResetModel(); emit termsChanged(); } void TableModelAnovaModel::clear() { setTerms(Terms()); } void TableModelAnovaModel::assign(const Terms &terms) { Terms t = _terms; t.add(terms); setTerms(t); } void TableModelAnovaModel::updateNuisances(bool checked) { // if a higher order interaction is specified as nuisance, then all lower order terms should be changed to nuisance as well for (int i = 0; i < _rows.size(); i++) { Options *row = _rows.at(i); OptionTerm *termOption = static_cast<OptionTerm*>(row->get(0)); OptionBoolean *nuisanceOption = static_cast<OptionBoolean*>(row->get(1)); Term term = Term(termOption->term()); if (nuisanceOption->value() == checked) { for (int j = 0; j < _rows.size(); j++) { if (i == j) continue; Options *r = _rows.at(j); OptionTerm *tOption = static_cast<OptionTerm*>(r->get(0)); OptionBoolean *nOption = static_cast<OptionBoolean*>(r->get(1)); Term t = Term(tOption->term()); if (checked) { if (term.containsAll(t)) nOption->setValue(true); } else { if (t.containsAll(term)) nOption->setValue(false); } } } } emit dataChanged(this->index(0,1), this->index(_rows.size() - 1, 1)); } <|endoftext|>
<commit_before>/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageDecoder.h" #include "SkBitmap.h" #include "SkImagePriv.h" #include "SkPixelRef.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkCanvas.h" SkImageDecoder::SkImageDecoder() : fPeeker(NULL) #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER , fChooser(NULL) #endif , fAllocator(NULL) , fSampleSize(1) , fDefaultPref(kUnknown_SkColorType) , fDitherImage(true) #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG , fUsePrefTable(false) #endif , fSkipWritingZeroes(false) , fPreferQualityOverSpeed(false) , fRequireUnpremultipliedColors(false) { } SkImageDecoder::~SkImageDecoder() { SkSafeUnref(fPeeker); #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER SkSafeUnref(fChooser); #endif SkSafeUnref(fAllocator); } void SkImageDecoder::copyFieldsToOther(SkImageDecoder* other) { if (NULL == other) { return; } other->setPeeker(fPeeker); #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER other->setChooser(fChooser); #endif other->setAllocator(fAllocator); other->setSampleSize(fSampleSize); #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG if (fUsePrefTable) { other->setPrefConfigTable(fPrefTable); } else { other->fDefaultPref = fDefaultPref; } #endif other->setDitherImage(fDitherImage); other->setSkipWritingZeroes(fSkipWritingZeroes); other->setPreferQualityOverSpeed(fPreferQualityOverSpeed); other->setRequireUnpremultipliedColors(fRequireUnpremultipliedColors); } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } const char* SkImageDecoder::getFormatName() const { return GetFormatName(this->getFormat()); } const char* SkImageDecoder::GetFormatName(Format format) { switch (format) { case kUnknown_Format: return "Unknown Format"; case kBMP_Format: return "BMP"; case kGIF_Format: return "GIF"; case kICO_Format: return "ICO"; case kPKM_Format: return "PKM"; case kKTX_Format: return "KTX"; case kJPEG_Format: return "JPEG"; case kPNG_Format: return "PNG"; case kWBMP_Format: return "WBMP"; case kWEBP_Format: return "WEBP"; default: SkDEBUGFAIL("Invalid format type!"); } return "Unknown Format"; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) { SkRefCnt_SafeAssign(fPeeker, peeker); return peeker; } #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) { SkRefCnt_SafeAssign(fChooser, chooser); return chooser; } #endif SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) { SkRefCnt_SafeAssign(fAllocator, alloc); return alloc; } void SkImageDecoder::setSampleSize(int size) { if (size < 1) { size = 1; } fSampleSize = size; } #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER // TODO: change Chooser virtual to take colorType, so we can stop calling SkColorTypeToBitmapConfig // bool SkImageDecoder::chooseFromOneChoice(SkColorType colorType, int width, int height) const { Chooser* chooser = fChooser; if (NULL == chooser) { // no chooser, we just say YES to decoding :) return true; } chooser->begin(1); chooser->inspect(0, SkColorTypeToBitmapConfig(colorType), width, height); return chooser->choose() == 0; } #endif bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) const { return bitmap->allocPixels(fAllocator, ctable); } /////////////////////////////////////////////////////////////////////////////// #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG void SkImageDecoder::setPrefConfigTable(const PrefConfigTable& prefTable) { fUsePrefTable = true; fPrefTable = prefTable; } #endif // TODO: use colortype in fPrefTable, fDefaultPref so we can stop using SkBitmapConfigToColorType() // SkColorType SkImageDecoder::getPrefColorType(SrcDepth srcDepth, bool srcHasAlpha) const { SkColorType ct = fDefaultPref; #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG if (fUsePrefTable) { // Until we kill or change the PrefTable, we have to go into Config land for a moment. SkBitmap::Config config = SkBitmap::kNo_Config; switch (srcDepth) { case kIndex_SrcDepth: config = srcHasAlpha ? fPrefTable.fPrefFor_8Index_YesAlpha_src : fPrefTable.fPrefFor_8Index_NoAlpha_src; break; case k8BitGray_SrcDepth: config = fPrefTable.fPrefFor_8Gray_src; break; case k32Bit_SrcDepth: config = srcHasAlpha ? fPrefTable.fPrefFor_8bpc_YesAlpha_src : fPrefTable.fPrefFor_8bpc_NoAlpha_src; break; } // now return to SkColorType land ct = SkBitmapConfigToColorType(config); } #endif return ct; } SkImageDecoder::Result SkImageDecoder::decode(SkStream* stream, SkBitmap* bm, SkColorType pref, Mode mode) { // we reset this to false before calling onDecode fShouldCancelDecode = false; // assign this, for use by getPrefColorType(), in case fUsePrefTable is false fDefaultPref = pref; // pass a temporary bitmap, so that if we return false, we are assured of // leaving the caller's bitmap untouched. SkBitmap tmp; const Result result = this->onDecode(stream, &tmp, mode); if (kFailure != result) { bm->swap(tmp); } return result; } bool SkImageDecoder::decodeSubset(SkBitmap* bm, const SkIRect& rect, SkColorType pref) { // we reset this to false before calling onDecodeSubset fShouldCancelDecode = false; // assign this, for use by getPrefColorType(), in case fUsePrefTable is false fDefaultPref = pref; return this->onDecodeSubset(bm, rect); } bool SkImageDecoder::buildTileIndex(SkStreamRewindable* stream, int *width, int *height) { // we reset this to false before calling onBuildTileIndex fShouldCancelDecode = false; return this->onBuildTileIndex(stream, width, height); } bool SkImageDecoder::cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize, int dstX, int dstY, int width, int height, int srcX, int srcY) { int w = width / sampleSize; int h = height / sampleSize; if (src->colorType() == kIndex_8_SkColorType) { // kIndex8 does not allow drawing via an SkCanvas, as is done below. // Instead, use extractSubset. Note that this shares the SkPixelRef and // SkColorTable. // FIXME: Since src is discarded in practice, this holds on to more // pixels than is strictly necessary. Switch to a copy if memory // savings are more important than speed here. This also means // that the pixels in dst can not be reused (though there is no // allocation, which was already done on src). int x = (dstX - srcX) / sampleSize; int y = (dstY - srcY) / sampleSize; SkIRect subset = SkIRect::MakeXYWH(x, y, w, h); return src->extractSubset(dst, subset); } // if the destination has no pixels then we must allocate them. if (dst->isNull()) { dst->setInfo(src->info().makeWH(w, h)); if (!this->allocPixelRef(dst, NULL)) { SkDEBUGF(("failed to allocate pixels needed to crop the bitmap")); return false; } } // check to see if the destination is large enough to decode the desired // region. If this assert fails we will just draw as much of the source // into the destination that we can. if (dst->width() < w || dst->height() < h) { SkDEBUGF(("SkImageDecoder::cropBitmap does not have a large enough bitmap.\n")); } // Set the Src_Mode for the paint to prevent transparency issue in the // dest in the event that the dest was being re-used. SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); SkCanvas canvas(*dst); canvas.drawSprite(*src, (srcX - dstX) / sampleSize, (srcY - dstY) / sampleSize, &paint); return true; } /////////////////////////////////////////////////////////////////////////////// bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { SkASSERT(file); SkASSERT(bm); SkAutoTUnref<SkStreamRewindable> stream(SkStream::NewFromFile(file)); if (stream.get()) { if (SkImageDecoder::DecodeStream(stream, bm, pref, mode, format)) { bm->pixelRef()->setURI(file); return true; } } return false; } bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { if (0 == size) { return false; } SkASSERT(buffer); SkMemoryStream stream(buffer, size); return SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format); } bool SkImageDecoder::DecodeStream(SkStreamRewindable* stream, SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { SkASSERT(stream); SkASSERT(bm); bool success = false; SkImageDecoder* codec = SkImageDecoder::Factory(stream); if (NULL != codec) { success = codec->decode(stream, bm, pref, mode); if (success && format) { *format = codec->getFormat(); if (kUnknown_Format == *format) { if (stream->rewind()) { *format = GetStreamFormat(stream); } } } delete codec; } return success; } <commit_msg>skia: add compat SkImageDecoder::DecodeStream symbol<commit_after>/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageDecoder.h" #include "SkBitmap.h" #include "SkImagePriv.h" #include "SkPixelRef.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkCanvas.h" SkImageDecoder::SkImageDecoder() : fPeeker(NULL) #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER , fChooser(NULL) #endif , fAllocator(NULL) , fSampleSize(1) , fDefaultPref(kUnknown_SkColorType) , fDitherImage(true) #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG , fUsePrefTable(false) #endif , fSkipWritingZeroes(false) , fPreferQualityOverSpeed(false) , fRequireUnpremultipliedColors(false) { } SkImageDecoder::~SkImageDecoder() { SkSafeUnref(fPeeker); #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER SkSafeUnref(fChooser); #endif SkSafeUnref(fAllocator); } void SkImageDecoder::copyFieldsToOther(SkImageDecoder* other) { if (NULL == other) { return; } other->setPeeker(fPeeker); #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER other->setChooser(fChooser); #endif other->setAllocator(fAllocator); other->setSampleSize(fSampleSize); #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG if (fUsePrefTable) { other->setPrefConfigTable(fPrefTable); } else { other->fDefaultPref = fDefaultPref; } #endif other->setDitherImage(fDitherImage); other->setSkipWritingZeroes(fSkipWritingZeroes); other->setPreferQualityOverSpeed(fPreferQualityOverSpeed); other->setRequireUnpremultipliedColors(fRequireUnpremultipliedColors); } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } const char* SkImageDecoder::getFormatName() const { return GetFormatName(this->getFormat()); } const char* SkImageDecoder::GetFormatName(Format format) { switch (format) { case kUnknown_Format: return "Unknown Format"; case kBMP_Format: return "BMP"; case kGIF_Format: return "GIF"; case kICO_Format: return "ICO"; case kPKM_Format: return "PKM"; case kKTX_Format: return "KTX"; case kJPEG_Format: return "JPEG"; case kPNG_Format: return "PNG"; case kWBMP_Format: return "WBMP"; case kWEBP_Format: return "WEBP"; default: SkDEBUGFAIL("Invalid format type!"); } return "Unknown Format"; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) { SkRefCnt_SafeAssign(fPeeker, peeker); return peeker; } #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) { SkRefCnt_SafeAssign(fChooser, chooser); return chooser; } #endif SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) { SkRefCnt_SafeAssign(fAllocator, alloc); return alloc; } void SkImageDecoder::setSampleSize(int size) { if (size < 1) { size = 1; } fSampleSize = size; } #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER // TODO: change Chooser virtual to take colorType, so we can stop calling SkColorTypeToBitmapConfig // bool SkImageDecoder::chooseFromOneChoice(SkColorType colorType, int width, int height) const { Chooser* chooser = fChooser; if (NULL == chooser) { // no chooser, we just say YES to decoding :) return true; } chooser->begin(1); chooser->inspect(0, SkColorTypeToBitmapConfig(colorType), width, height); return chooser->choose() == 0; } #endif bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) const { return bitmap->allocPixels(fAllocator, ctable); } /////////////////////////////////////////////////////////////////////////////// #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG void SkImageDecoder::setPrefConfigTable(const PrefConfigTable& prefTable) { fUsePrefTable = true; fPrefTable = prefTable; } #endif // TODO: use colortype in fPrefTable, fDefaultPref so we can stop using SkBitmapConfigToColorType() // SkColorType SkImageDecoder::getPrefColorType(SrcDepth srcDepth, bool srcHasAlpha) const { SkColorType ct = fDefaultPref; #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG if (fUsePrefTable) { // Until we kill or change the PrefTable, we have to go into Config land for a moment. SkBitmap::Config config = SkBitmap::kNo_Config; switch (srcDepth) { case kIndex_SrcDepth: config = srcHasAlpha ? fPrefTable.fPrefFor_8Index_YesAlpha_src : fPrefTable.fPrefFor_8Index_NoAlpha_src; break; case k8BitGray_SrcDepth: config = fPrefTable.fPrefFor_8Gray_src; break; case k32Bit_SrcDepth: config = srcHasAlpha ? fPrefTable.fPrefFor_8bpc_YesAlpha_src : fPrefTable.fPrefFor_8bpc_NoAlpha_src; break; } // now return to SkColorType land ct = SkBitmapConfigToColorType(config); } #endif return ct; } SkImageDecoder::Result SkImageDecoder::decode(SkStream* stream, SkBitmap* bm, SkColorType pref, Mode mode) { // we reset this to false before calling onDecode fShouldCancelDecode = false; // assign this, for use by getPrefColorType(), in case fUsePrefTable is false fDefaultPref = pref; // pass a temporary bitmap, so that if we return false, we are assured of // leaving the caller's bitmap untouched. SkBitmap tmp; const Result result = this->onDecode(stream, &tmp, mode); if (kFailure != result) { bm->swap(tmp); } return result; } bool SkImageDecoder::decodeSubset(SkBitmap* bm, const SkIRect& rect, SkColorType pref) { // we reset this to false before calling onDecodeSubset fShouldCancelDecode = false; // assign this, for use by getPrefColorType(), in case fUsePrefTable is false fDefaultPref = pref; return this->onDecodeSubset(bm, rect); } bool SkImageDecoder::buildTileIndex(SkStreamRewindable* stream, int *width, int *height) { // we reset this to false before calling onBuildTileIndex fShouldCancelDecode = false; return this->onBuildTileIndex(stream, width, height); } bool SkImageDecoder::cropBitmap(SkBitmap *dst, SkBitmap *src, int sampleSize, int dstX, int dstY, int width, int height, int srcX, int srcY) { int w = width / sampleSize; int h = height / sampleSize; if (src->colorType() == kIndex_8_SkColorType) { // kIndex8 does not allow drawing via an SkCanvas, as is done below. // Instead, use extractSubset. Note that this shares the SkPixelRef and // SkColorTable. // FIXME: Since src is discarded in practice, this holds on to more // pixels than is strictly necessary. Switch to a copy if memory // savings are more important than speed here. This also means // that the pixels in dst can not be reused (though there is no // allocation, which was already done on src). int x = (dstX - srcX) / sampleSize; int y = (dstY - srcY) / sampleSize; SkIRect subset = SkIRect::MakeXYWH(x, y, w, h); return src->extractSubset(dst, subset); } // if the destination has no pixels then we must allocate them. if (dst->isNull()) { dst->setInfo(src->info().makeWH(w, h)); if (!this->allocPixelRef(dst, NULL)) { SkDEBUGF(("failed to allocate pixels needed to crop the bitmap")); return false; } } // check to see if the destination is large enough to decode the desired // region. If this assert fails we will just draw as much of the source // into the destination that we can. if (dst->width() < w || dst->height() < h) { SkDEBUGF(("SkImageDecoder::cropBitmap does not have a large enough bitmap.\n")); } // Set the Src_Mode for the paint to prevent transparency issue in the // dest in the event that the dest was being re-used. SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); SkCanvas canvas(*dst); canvas.drawSprite(*src, (srcX - dstX) / sampleSize, (srcY - dstY) / sampleSize, &paint); return true; } /////////////////////////////////////////////////////////////////////////////// #ifdef SK_SUPPORT_LEGACY_DECODEFILE extern "C" bool _ZN14SkImageDecoder10DecodeFileEPKcP8SkBitmapNS2_6ConfigENS_4ModeEPNS_6FormatE( const char file[], SkBitmap* bm, SkBitmap::Config pref, SkImageDecoder::Mode mode, SkImageDecoder::Format* format) { SkColorType ct = SkBitmapConfigToColorType(pref); return SkImageDecoder::DecodeFile(file, bm, ct, mode, format); } #endif bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { SkASSERT(file); SkASSERT(bm); SkAutoTUnref<SkStreamRewindable> stream(SkStream::NewFromFile(file)); if (stream.get()) { if (SkImageDecoder::DecodeStream(stream, bm, pref, mode, format)) { bm->pixelRef()->setURI(file); return true; } } return false; } bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { if (0 == size) { return false; } SkASSERT(buffer); SkMemoryStream stream(buffer, size); return SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format); } bool SkImageDecoder::DecodeStream(SkStreamRewindable* stream, SkBitmap* bm, SkColorType pref, Mode mode, Format* format) { SkASSERT(stream); SkASSERT(bm); bool success = false; SkImageDecoder* codec = SkImageDecoder::Factory(stream); if (NULL != codec) { success = codec->decode(stream, bm, pref, mode); if (success && format) { *format = codec->getFormat(); if (kUnknown_Format == *format) { if (stream->rewind()) { *format = GetStreamFormat(stream); } } } delete codec; } return success; } <|endoftext|>
<commit_before>#include "../include/oasis.h" #ifdef HAVE_PARQUET #include "../include/oasisparquet.h" #endif #include <cstring> #include <map> #include <vector> namespace katparquet { template<typename tableNameT> void DoKat(const std::vector<std::string> &inFiles, parquet::StreamWriter &osOut, std::vector<tableNameT> &rows) { rows.resize(inFiles.size()); std::vector<parquet::StreamReader> isIn; isIn.resize(inFiles.size()); std::map<int, int> event_to_file; // Read first row from each file for (int i = 0; i < (int)inFiles.size(); i++) { isIn[i] = OasisParquet::SetupParquetInputStream(inFiles[i]); tableNameT row; if (isIn[i].eof()) continue; // Ignore empty files isIn[i] >> row; rows[i] = row; event_to_file[rows[i].eventID] = i; } if (event_to_file.size() == 0) { fprintf(stderr, "ERROR: All input files are empty\n"); exit(EXIT_FAILURE); } // First entry should always have lowest event ID while(event_to_file.size() != 0) { auto iter = event_to_file.begin(); int currentEventID = iter->first; while (rows[iter->second].eventID == currentEventID) { osOut << rows[iter->second]; if (isIn[iter->second].eof()) break; isIn[iter->second] >> rows[iter->second]; } if (!isIn[iter->second].eof()) { event_to_file[rows[iter->second].eventID] = iter->second; } event_to_file.erase(iter); } } void doit(const std::vector<std::string> &inFiles, const std::string outFile, const int tableName) { parquet::StreamWriter osOut = OasisParquet::GetParquetStreamWriter(tableName, outFile); if (tableName == OasisParquet::MPLT) { std::vector<OasisParquet::MomentPLTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::QPLT) { std::vector<OasisParquet::QuantilePLTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::SPLT) { std::vector<OasisParquet::SamplePLTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::MELT) { std::vector<OasisParquet::MomentELTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::QELT) { std::vector<OasisParquet::QuantileELTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::SELT) { std::vector<OasisParquet::SampleELTEntry> rows; DoKat(inFiles, osOut, rows); } else if (tableName == OasisParquet::NONE) { fprintf(stderr, "FATAL: No table type selected - please select table " "type for files to be concatenated.\n"); exit(EXIT_FAILURE); } else { // Should never get here fprintf(stderr, "FATAL: Unknown table selected.\n"); exit(EXIT_FAILURE); } } } <commit_msg>Sort Period Loss Tables by period number and then event ID (#298)<commit_after>#include "../include/oasis.h" #ifdef HAVE_PARQUET #include "../include/oasisparquet.h" #endif #include <cstring> #include <map> #include <vector> namespace katparquet { struct period_event { int period; int eventID; }; bool operator<(const period_event &lhs, const period_event &rhs) { if (lhs.period != rhs.period) { return lhs.period < rhs.period; } else { return lhs.eventID < rhs.eventID; } } bool operator==(const period_event &lhs, const period_event &rhs) { return lhs.period == rhs.period && lhs.eventID == rhs.eventID; } template<typename tableNameT> void GetRow(std::map<int, int> &event_to_file, const tableNameT &row, const int i) { event_to_file[row.eventID] = i; } template<typename tableNameT> void GetRow(std::map<period_event, int> &period_to_file, const tableNameT &row, const int i) { period_event periodEventID; periodEventID.period = row.period; periodEventID.eventID = row.eventID; period_to_file[periodEventID] = i; } template<typename tableNameT, typename rowMapT> void ReadFirstRows(const std::vector<std::string> &inFiles, std::vector<parquet::StreamReader> &isIn, std::vector<tableNameT> &rows, rowMapT &rowMap_to_file) { // Read first row from each file for (int i = 0; i < (int)inFiles.size(); i++) { isIn[i] = OasisParquet::SetupParquetInputStream(inFiles[i]); tableNameT row; if (isIn[i].eof()) continue; // Ignore empty files isIn[i] >> row; rows[i] = row; GetRow(rowMap_to_file, rows[i], i); } } template<typename tableNameT> void WriteOutput(std::vector<tableNameT> &rows, std::map<int, int> &event_to_file, parquet::StreamWriter &osOut, std::vector<parquet::StreamReader> &isIn) { // First entry should always have lowest event ID while(event_to_file.size() != 0) { auto iter = event_to_file.begin(); int currentEventID = iter->first; while (rows[iter->second].eventID == currentEventID) { osOut << rows[iter->second]; if (isIn[iter->second].eof()) break; isIn[iter->second] >> rows[iter->second]; } if (!isIn[iter->second].eof()) { GetRow(event_to_file, rows[iter->second], iter->second); } event_to_file.erase(iter); } } template<typename tableNameT> void WriteOutput(std::vector<tableNameT> &rows, std::map<period_event, int> &period_to_file, parquet::StreamWriter &osOut, std::vector<parquet::StreamReader> &isIn) { // First entry should always have lowest period number followed by event ID while (period_to_file.size() != 0) { auto iter = period_to_file.begin(); period_event currentPeriodEvent = iter->first; period_event periodEventID; periodEventID.period = rows[iter->second].period; periodEventID.eventID = rows[iter->second].eventID; while (periodEventID == currentPeriodEvent) { osOut << rows[iter->second]; if (isIn[iter->second].eof()) break; isIn[iter->second] >> rows[iter->second]; periodEventID.period = rows[iter->second].period; periodEventID.eventID = rows[iter->second].eventID; } if (!isIn[iter->second].eof()) { GetRow(period_to_file, rows[iter->second], iter->second); } period_to_file.erase(iter); } } template<typename tableNameT, typename rowMapT> void DoKat(const std::vector<std::string> &inFiles, parquet::StreamWriter &osOut, std::vector<tableNameT> &rows, rowMapT &rowMap_to_file) { rows.resize(inFiles.size()); std::vector<parquet::StreamReader> isIn; isIn.resize(inFiles.size()); ReadFirstRows(inFiles, isIn, rows, rowMap_to_file); if (rowMap_to_file.size() == 0) { fprintf(stderr, "ERROR: All input files are empty\n"); exit(EXIT_FAILURE); } WriteOutput(rows, rowMap_to_file, osOut, isIn); } void doit(const std::vector<std::string> &inFiles, const std::string outFile, const int tableName) { parquet::StreamWriter osOut = OasisParquet::GetParquetStreamWriter(tableName, outFile); std::map<int, int> event_to_file; // Exceedance Loss Table std::map<period_event, int> period_to_file; // Period Loss Table if (tableName == OasisParquet::MPLT) { std::vector<OasisParquet::MomentPLTEntry> rows; DoKat(inFiles, osOut, rows, period_to_file); } else if (tableName == OasisParquet::QPLT) { std::vector<OasisParquet::QuantilePLTEntry> rows; DoKat(inFiles, osOut, rows, period_to_file); } else if (tableName == OasisParquet::SPLT) { std::vector<OasisParquet::SamplePLTEntry> rows; DoKat(inFiles, osOut, rows, period_to_file); } else if (tableName == OasisParquet::MELT) { std::vector<OasisParquet::MomentELTEntry> rows; DoKat(inFiles, osOut, rows, event_to_file); } else if (tableName == OasisParquet::QELT) { std::vector<OasisParquet::QuantileELTEntry> rows; DoKat(inFiles, osOut, rows, event_to_file); } else if (tableName == OasisParquet::SELT) { std::vector<OasisParquet::SampleELTEntry> rows; DoKat(inFiles, osOut, rows, event_to_file); } else if (tableName == OasisParquet::NONE) { fprintf(stderr, "FATAL: No table type selected - please select table " "type for files to be concatenated.\n"); exit(EXIT_FAILURE); } else { // Should never get here fprintf(stderr, "FATAL: Unknown table selected.\n"); exit(EXIT_FAILURE); } } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008 Larry Gritz // // 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 is the MIT license) ///////////////////////////////////////////////////////////////////////////// #include <cstdio> #include <cstdlib> #include <half.h> #include <boost/algorithm/string.hpp> using boost::algorithm::iequals; #include "dassert.h" #include "paramtype.h" #define DLL_EXPORT_PUBLIC /* Because we are implementing ImageIO */ #include "imageio.h" #undef DLL_EXPORT_PUBLIC using namespace OpenImageIO; // Generate the default quantization parameters, templated on the data // type. template <class T> static void set_default_quantize (int &quant_black, int &quant_white, int &quant_min, int &quant_max, float &quant_dither) { if (std::numeric_limits <T>::is_integer) { quant_black = 0; quant_white = (int) std::numeric_limits <T>::max(); quant_min = (int) std::numeric_limits <T>::min(); quant_max = (int) std::numeric_limits <T>::max(); quant_dither = 0.5f; } else { quant_black = 0; quant_white = 0; quant_min = 0; quant_max = 0; quant_dither = 0.0f; } } // Given the format, set the default quantization parameters. // Rely on the template version to make life easy. static void set_default_quantize (ParamBaseType format, int &quant_black, int &quant_white, int &quant_min, int &quant_max, float &quant_dither) { switch (format) { case PT_INT8: set_default_quantize <char> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UNKNOWN: case PT_UINT8: set_default_quantize <unsigned char> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_INT16: set_default_quantize <short> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UINT16: set_default_quantize <unsigned short> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_INT: set_default_quantize <int> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UINT: set_default_quantize <unsigned int> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_HALF: set_default_quantize <half> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_FLOAT: set_default_quantize <float> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_DOUBLE: set_default_quantize <double> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; default: ASSERT(0); } } QuantizationSpec QuantizationSpec::quantize_default (std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), 0); QuantizationSpec::QuantizationSpec (ParamBaseType _type) { set_default_quantize (_type, quant_black, quant_white, quant_min, quant_max, quant_dither); } ImageSpec::ImageSpec (ParamBaseType format) : x(0), y(0), z(0), width(0), height(0), depth(1), full_width(0), full_height(0), full_depth(0), tile_width(0), tile_height(0), tile_depth(1), format(format), nchannels(0), alpha_channel(-1), z_channel(-1), linearity(UnknownLinearity), gamma(1) { set_format (format); } ImageSpec::ImageSpec (int xres, int yres, int nchans, ParamBaseType format) : x(0), y(0), z(0), width(xres), height(yres), depth(1), full_width(xres), full_height(yres), full_depth(1), tile_width(0), tile_height(0), tile_depth(1), format(format), nchannels(nchans), alpha_channel(-1), z_channel(-1), linearity(UnknownLinearity), gamma(1) { set_format (format); default_channel_names (); } void ImageSpec::set_format (ParamBaseType fmt) { format = fmt; set_default_quantize (fmt, quant_black, quant_white, quant_min, quant_max, quant_dither); } ParamBaseType ImageSpec::format_from_quantize (int quant_black, int quant_white, int quant_min, int quant_max) { if (quant_black == 0 && quant_white == 0 && quant_min == 0 && quant_max == 0) { // Per RenderMan and Gelato heuristics, if all quantization // values are zero, assume they want a float output. return PT_FLOAT; } else if (quant_min >= std::numeric_limits <unsigned char>::min() && quant_max <= std::numeric_limits <unsigned char>::max()) { return PT_UINT8; } else if (quant_min >= std::numeric_limits <char>::min() && quant_max <= std::numeric_limits <char>::max()) { return PT_INT8; } else if (quant_min >= std::numeric_limits <unsigned short>::min() && quant_max <= std::numeric_limits <unsigned short>::max()) { return PT_UINT16; } else if (quant_min >= std::numeric_limits <short>::min() && quant_max <= std::numeric_limits <short>::max()) { return PT_INT16; } else if (quant_min >= std::numeric_limits <int>::min() && quant_max <= std::numeric_limits <int>::max()) { return PT_INT; } else if (quant_min >= std::numeric_limits <unsigned int>::min() && quant_max <= std::numeric_limits <unsigned int>::max()) { return PT_UINT; } else { return PT_UNKNOWN; } } void ImageSpec::default_channel_names () { channelnames.clear(); alpha_channel = -1; z_channel = -1; switch (nchannels) { case 1: channelnames.push_back ("A"); break; case 2: channelnames.push_back ("I"); channelnames.push_back ("A"); alpha_channel = 1; break; case 3: channelnames.push_back ("R"); channelnames.push_back ("G"); channelnames.push_back ("B"); break; default: if (nchannels >= 1) channelnames.push_back ("R"); if (nchannels >= 2) channelnames.push_back ("G"); if (nchannels >= 3) channelnames.push_back ("B"); if (nchannels >= 4) { channelnames.push_back ("A"); alpha_channel = 3; } for (int c = 4; c < nchannels; ++c) channelnames.push_back (Strutil::format("channel%d", c)); break; } } void ImageSpec::attribute (const std::string &name, ParamBaseType type, int nvalues, const void *value) { // Don't allow duplicates ImageIOParameter *f = find_attribute (name); if (! f) { extra_attribs.resize (extra_attribs.size() + 1); f = &extra_attribs.back(); } f->init (name, type, nvalues, value); } ImageIOParameter * ImageSpec::find_attribute (const std::string &name, ParamType searchtype, bool casesensitive) { if (casesensitive) { for (size_t i = 0; i < extra_attribs.size(); ++i) if (extra_attribs[i].name() == name && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } else { for (size_t i = 0; i < extra_attribs.size(); ++i) if (iequals (extra_attribs[i].name().string(), name) && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } return NULL; } const ImageIOParameter * ImageSpec::find_attribute (const std::string &name, ParamType searchtype, bool casesensitive) const { if (casesensitive) { for (size_t i = 0; i < extra_attribs.size(); ++i) if (extra_attribs[i].name() == name && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } else { for (size_t i = 0; i < extra_attribs.size(); ++i) if (iequals (extra_attribs[i].name().string(), name) && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } return NULL; } <commit_msg>Bug fix - needed to include strutil.h<commit_after>///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008 Larry Gritz // // 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 is the MIT license) ///////////////////////////////////////////////////////////////////////////// #include <cstdio> #include <cstdlib> #include <half.h> #include <boost/algorithm/string.hpp> using boost::algorithm::iequals; #include "dassert.h" #include "paramtype.h" #include "strutil.h" #define DLL_EXPORT_PUBLIC /* Because we are implementing ImageIO */ #include "imageio.h" #undef DLL_EXPORT_PUBLIC using namespace OpenImageIO; // Generate the default quantization parameters, templated on the data // type. template <class T> static void set_default_quantize (int &quant_black, int &quant_white, int &quant_min, int &quant_max, float &quant_dither) { if (std::numeric_limits <T>::is_integer) { quant_black = 0; quant_white = (int) std::numeric_limits <T>::max(); quant_min = (int) std::numeric_limits <T>::min(); quant_max = (int) std::numeric_limits <T>::max(); quant_dither = 0.5f; } else { quant_black = 0; quant_white = 0; quant_min = 0; quant_max = 0; quant_dither = 0.0f; } } // Given the format, set the default quantization parameters. // Rely on the template version to make life easy. static void set_default_quantize (ParamBaseType format, int &quant_black, int &quant_white, int &quant_min, int &quant_max, float &quant_dither) { switch (format) { case PT_INT8: set_default_quantize <char> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UNKNOWN: case PT_UINT8: set_default_quantize <unsigned char> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_INT16: set_default_quantize <short> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UINT16: set_default_quantize <unsigned short> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_INT: set_default_quantize <int> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_UINT: set_default_quantize <unsigned int> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_HALF: set_default_quantize <half> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_FLOAT: set_default_quantize <float> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; case PT_DOUBLE: set_default_quantize <double> (quant_black, quant_white, quant_min, quant_max, quant_dither); break; default: ASSERT(0); } } QuantizationSpec QuantizationSpec::quantize_default (std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), std::numeric_limits<stride_t>::min(), 0); QuantizationSpec::QuantizationSpec (ParamBaseType _type) { set_default_quantize (_type, quant_black, quant_white, quant_min, quant_max, quant_dither); } ImageSpec::ImageSpec (ParamBaseType format) : x(0), y(0), z(0), width(0), height(0), depth(1), full_width(0), full_height(0), full_depth(0), tile_width(0), tile_height(0), tile_depth(1), format(format), nchannels(0), alpha_channel(-1), z_channel(-1), linearity(UnknownLinearity), gamma(1) { set_format (format); } ImageSpec::ImageSpec (int xres, int yres, int nchans, ParamBaseType format) : x(0), y(0), z(0), width(xres), height(yres), depth(1), full_width(xres), full_height(yres), full_depth(1), tile_width(0), tile_height(0), tile_depth(1), format(format), nchannels(nchans), alpha_channel(-1), z_channel(-1), linearity(UnknownLinearity), gamma(1) { set_format (format); default_channel_names (); } void ImageSpec::set_format (ParamBaseType fmt) { format = fmt; set_default_quantize (fmt, quant_black, quant_white, quant_min, quant_max, quant_dither); } ParamBaseType ImageSpec::format_from_quantize (int quant_black, int quant_white, int quant_min, int quant_max) { if (quant_black == 0 && quant_white == 0 && quant_min == 0 && quant_max == 0) { // Per RenderMan and Gelato heuristics, if all quantization // values are zero, assume they want a float output. return PT_FLOAT; } else if (quant_min >= std::numeric_limits <unsigned char>::min() && quant_max <= std::numeric_limits <unsigned char>::max()) { return PT_UINT8; } else if (quant_min >= std::numeric_limits <char>::min() && quant_max <= std::numeric_limits <char>::max()) { return PT_INT8; } else if (quant_min >= std::numeric_limits <unsigned short>::min() && quant_max <= std::numeric_limits <unsigned short>::max()) { return PT_UINT16; } else if (quant_min >= std::numeric_limits <short>::min() && quant_max <= std::numeric_limits <short>::max()) { return PT_INT16; } else if (quant_min >= std::numeric_limits <int>::min() && quant_max <= std::numeric_limits <int>::max()) { return PT_INT; } else if (quant_min >= std::numeric_limits <unsigned int>::min() && quant_max <= std::numeric_limits <unsigned int>::max()) { return PT_UINT; } else { return PT_UNKNOWN; } } void ImageSpec::default_channel_names () { channelnames.clear(); alpha_channel = -1; z_channel = -1; switch (nchannels) { case 1: channelnames.push_back ("A"); break; case 2: channelnames.push_back ("I"); channelnames.push_back ("A"); alpha_channel = 1; break; case 3: channelnames.push_back ("R"); channelnames.push_back ("G"); channelnames.push_back ("B"); break; default: if (nchannels >= 1) channelnames.push_back ("R"); if (nchannels >= 2) channelnames.push_back ("G"); if (nchannels >= 3) channelnames.push_back ("B"); if (nchannels >= 4) { channelnames.push_back ("A"); alpha_channel = 3; } for (int c = 4; c < nchannels; ++c) channelnames.push_back (Strutil::format("channel%d", c)); break; } } void ImageSpec::attribute (const std::string &name, ParamBaseType type, int nvalues, const void *value) { // Don't allow duplicates ImageIOParameter *f = find_attribute (name); if (! f) { extra_attribs.resize (extra_attribs.size() + 1); f = &extra_attribs.back(); } f->init (name, type, nvalues, value); } ImageIOParameter * ImageSpec::find_attribute (const std::string &name, ParamType searchtype, bool casesensitive) { if (casesensitive) { for (size_t i = 0; i < extra_attribs.size(); ++i) if (extra_attribs[i].name() == name && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } else { for (size_t i = 0; i < extra_attribs.size(); ++i) if (iequals (extra_attribs[i].name().string(), name) && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } return NULL; } const ImageIOParameter * ImageSpec::find_attribute (const std::string &name, ParamType searchtype, bool casesensitive) const { if (casesensitive) { for (size_t i = 0; i < extra_attribs.size(); ++i) if (extra_attribs[i].name() == name && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } else { for (size_t i = 0; i < extra_attribs.size(); ++i) if (iequals (extra_attribs[i].name().string(), name) && (searchtype == PT_UNKNOWN || searchtype == extra_attribs[i].type())) return &extra_attribs[i]; } return NULL; } <|endoftext|>
<commit_before><commit_msg>Fix #1039 (#1040)<commit_after><|endoftext|>
<commit_before>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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 <boost/format.hpp> #include <votca/xtp/anderson_mixing.h> namespace votca { namespace xtp { void ANDERSON::UpdateOutput(const Eigen::VectorXd &newOutput) { // Check if max mixing history is reached and adding new step to history Index size = _output.size(); if (size > _max_history - 1) { _output.erase(_output.begin()); } _output.push_back(newOutput); } void ANDERSON::UpdateInput(const Eigen::VectorXd &newInput) { Index size = _output.size(); if (size > _max_history - 1) { _input.erase(_input.begin()); } _input.push_back(newInput); } Eigen::VectorXd ANDERSON::NPAndersonMixing(const double alpha) { _iteration++; Eigen::VectorXd OutMixed = _output.back(); Eigen::VectorXd InMixed = _input.back(); if (_iteration > 1 && _max_history > 1) { Eigen::VectorXd DeltaN = OutMixed - InMixed; // Building Linear System for Coefficients const Index used_history = _output.size()-1; Eigen::MatrixXd A = Eigen::MatrixXd::Zero(used_history, used_history); Eigen::VectorXd c = Eigen::VectorXd::Zero(used_history); for (Index m = 1; m <= used_history; m++) { c(m - 1) = (DeltaN - _output.at(used_history - m) + _input.at(used_history - m)) .cwiseProduct(DeltaN) .sum(); for (Index j = 1; j <= used_history; j++) { A(m - 1, j - 1) = (DeltaN - _output.at(used_history - m) + _input.at(used_history - m)) .cwiseProduct((DeltaN - _output.at(used_history - j) + _input.at(used_history - j))) .sum(); } } // Solving the System to obtain coefficients Eigen::VectorXd coefficients = A.fullPivHouseholderQr().solve(c); // Mixing the Potentials for (Index n = 1; n <= used_history; n++) { OutMixed += coefficients(n - 1) * (_output.at(used_history - n) - _output.at(used_history)); InMixed += coefficients(n - 1) * (_input.at(used_history - n) - _input.at(used_history)); } } // Returning the linear Mix of Input and Output return alpha * OutMixed + (1 - alpha) * InMixed; } } // namespace xtp } // namespace votca<commit_msg>format<commit_after>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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 <boost/format.hpp> #include <votca/xtp/anderson_mixing.h> namespace votca { namespace xtp { void ANDERSON::UpdateOutput(const Eigen::VectorXd &newOutput) { // Check if max mixing history is reached and adding new step to history Index size = _output.size(); if (size > _max_history - 1) { _output.erase(_output.begin()); } _output.push_back(newOutput); } void ANDERSON::UpdateInput(const Eigen::VectorXd &newInput) { Index size = _output.size(); if (size > _max_history - 1) { _input.erase(_input.begin()); } _input.push_back(newInput); } Eigen::VectorXd ANDERSON::NPAndersonMixing(const double alpha) { _iteration++; Eigen::VectorXd OutMixed = _output.back(); Eigen::VectorXd InMixed = _input.back(); if (_iteration > 1 && _max_history > 1) { Eigen::VectorXd DeltaN = OutMixed - InMixed; // Building Linear System for Coefficients const Index used_history = _output.size() - 1; Eigen::MatrixXd A = Eigen::MatrixXd::Zero(used_history, used_history); Eigen::VectorXd c = Eigen::VectorXd::Zero(used_history); for (Index m = 1; m <= used_history; m++) { c(m - 1) = (DeltaN - _output.at(used_history - m) + _input.at(used_history - m)) .cwiseProduct(DeltaN) .sum(); for (Index j = 1; j <= used_history; j++) { A(m - 1, j - 1) = (DeltaN - _output.at(used_history - m) + _input.at(used_history - m)) .cwiseProduct((DeltaN - _output.at(used_history - j) + _input.at(used_history - j))) .sum(); } } // Solving the System to obtain coefficients Eigen::VectorXd coefficients = A.fullPivHouseholderQr().solve(c); // Mixing the Potentials for (Index n = 1; n <= used_history; n++) { OutMixed += coefficients(n - 1) * (_output.at(used_history - n) - _output.at(used_history)); InMixed += coefficients(n - 1) * (_input.at(used_history - n) - _input.at(used_history)); } } // Returning the linear Mix of Input and Output return alpha * OutMixed + (1 - alpha) * InMixed; } } // namespace xtp } // namespace votca<|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack 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 * @brief Implementation of srpphat.h */ #include "srp_phat.h" #include <string> #include <tuple> #include <vector> #include "utils/fft_lib.h" namespace taylortrack { namespace localization { double SrpPhat::inter_microphone_time_delay(const RArray &point, const RArray &microphone1, const RArray &microphone2) { return (std::sqrt(std::pow(point - microphone1, 2).sum()) - std::sqrt(std::pow(point - microphone2, 2).sum())) / kSpeedOfSound; } int SrpPhat::point_to_degree(double x_coordinate, double y_coordinate) { return static_cast<int>(round(fmod(((atan2(y_coordinate, x_coordinate) * 180 / kPI) + 360), 360.0))); } std::vector<std::tuple<int, int>> SrpPhat::get_microphone_pairs() { std::vector<std::tuple<int, int>> pairs; // iterating over microphones for (int i = 0; i < static_cast<int>(x_dim_mics_.size()); i++) { for (int j = 0; j < static_cast<int>(x_dim_mics_.size()); j++) { // only append pairs once and don't consider pairs of the same microphone if (j > i) { pairs.push_back(std::make_tuple(i, j)); } } } return pairs; } RArray SrpPhat::generalized_cross_correlation(const RArray &signal1, const RArray &signal2) { size_t corr_length = signal1.size() + signal2.size() - 1; /* bringing the signals into the right shape to work with the fftlib first making them complex and pad with necessary zeros */ taylortrack::utils::FftLib fft_obj = taylortrack::utils::FftLib(); CArray tempsignal1 = fft_obj.convert_to_complex(signal1); CArray tempsignal2 = fft_obj.convert_to_complex(signal2); CArray csignal1 = fft_obj.zero_padding(tempsignal1, static_cast<int> (corr_length - signal1.size())); CArray csignal2 = fft_obj.zero_padding(tempsignal2, static_cast<int> (corr_length - signal2.size())); // perform FFT on the converted signals fft_obj.fft(csignal1); fft_obj.fft(csignal2); // computing nominator and denominator of the generalized cross correlation CArray nominator = csignal1 * csignal2.apply(std::conj); CArray denominator = std::pow(abs(nominator), static_cast<float>(beta_)); // reverse transfering to time domain CArray temp = nominator / denominator; fft_obj.ifft(temp); RArray result(temp.size()); RArray temp3 = fft_obj.convert_to_real(temp); fft_obj.fftshift(temp3, result); return result; } std::vector<double> SrpPhat::get_axis_values(bool xaxis) { std::vector<double> axisValues; int vectorSize = static_cast<int>( xaxis ? x_length_ / stepsize_ + 1 : y_length_ / stepsize_ + 1); double axStart = xaxis ? x_length_ / 2 * -1 : y_length_ / 2; while (static_cast<int>(axisValues.size()) < vectorSize) { axisValues.push_back(axStart); axStart = xaxis ? axStart + stepsize_ : axStart - stepsize_; } return axisValues; } RArray SrpPhat::get_position_distribution(const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) { for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) { int degree = point_to_degree(xAxisValues[i], yAxisValues[j]); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[i][j]; } } // get maximum for normalization of values double res = degree_values.sum(); return degree_values / res; } int SrpPhat::get_position(const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < 360; i++) { degree_values[i] = 0; } int vectorSize = static_cast<int> (x_length_ / stepsize_ + 1); for (int i = 0; i < vectorSize; i++) { for (int j = 0; j < vectorSize; j++) { int degree = point_to_degree(xAxisValues[j], static_cast<double> (yAxisValues[i])); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[j][i]; } } double res = degree_values.max(); return find_value(degree_values, res); } int SrpPhat::find_value(const RArray &in_vector, double value) { for (int i = 0; i < static_cast<int>(in_vector.size()); i++) { if (std::abs(in_vector[i] - value) < 0.0001) { return i; } } return -1; } std::vector<std::vector<double>> SrpPhat::get_generalized_cross_correlation(const std::vector<RArray> &signals) { std::vector<std::tuple<int, int>> pairs = get_microphone_pairs(); std::vector<std::vector<double>> generalized_cross_correlation_values; int64_t vectorSize = int64_t(x_length_ / stepsize_ + 1); // initializing the gcc grid generalized_cross_correlation_values.resize(static_cast<unsigned long>(vectorSize)); for (int i = 0; i < vectorSize; ++i) { generalized_cross_correlation_values[i].resize(static_cast<unsigned long>(vectorSize)); } std::vector<std::vector<std::vector<double>>> micDelays = delay_tensor_; // iterating over all microphone pairs for (int i = 0; i < static_cast<int>(pairs.size()); i++) { int index1 = std::get<0>(pairs[i]); int index2 = std::get<1>(pairs[i]); // assigning the corresponding signals RArray signal1 = signals[index1]; RArray signal2 = signals[index2]; // get the current frame from the complete signal RArray signalSlice1 = signal1[std::slice(0, static_cast<size_t>(steps_ + 1), 1)]; RArray signalSlice2 = signal2[std::slice(0, static_cast<size_t>(steps_), 1)]; // computing the cross correlation of both frames RArray generalized_cross_temp = generalized_cross_correlation(signalSlice1, signalSlice2); // iterating over the whole x-y grid for (int x = 0; x < vectorSize; x++) { for (int y = 0; y < vectorSize; y++) { double delay = micDelays[x][y][i]; // adding the corresponding cross correlation value to the grid generalized_cross_correlation_values[x][y] += generalized_cross_temp[(steps_ - 1) + round(delay / (1.0 / samplerate_))]; } } } return generalized_cross_correlation_values; } std::vector<std::vector<std::vector<double>>> SrpPhat::get_delay_tensor() { std::vector<std::vector<std::vector<double>>> delay_tensor; std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); std::vector<std::tuple<int, int>> pairs = get_microphone_pairs(); int vector_size = x_length_ / stepsize_ + 1; int depth = pairs.size(); delay_tensor.resize(vector_size); for (int i = 0; i < vector_size; ++i) { delay_tensor[i].resize(vector_size); for (int j = 0; j < vector_size; ++j) delay_tensor[i][j].resize(depth); } // iterating over the grid for (int x = 0; x < vector_size; x++) { for (int y = 0; y < vector_size; y++) { // iterating over microphone pairs for (int i = 0; i < static_cast<int>(pairs.size()); i++) { // RArray point(2); RArray microphone1(2); RArray microphone2(2); // assigning the current point in the grid point[0] = xAxisValues[x]; point[1] = yAxisValues[y]; // assigning the microphone values int index1 = std::get<0>(pairs[i]); int index2 = std::get<1>(pairs[i]); microphone1[0] = x_dim_mics_[index1]; microphone1[1] = y_dim_mics_[index1]; microphone2[0] = x_dim_mics_[index2]; microphone2[1] = y_dim_mics_[index2]; double delay = inter_microphone_time_delay(point, microphone1, microphone2); delay_tensor[x][y][i] = delay; } } } // iterating over all microphone pairs return delay_tensor; } RArray SrpPhat::get_microphone_signal(const std::string &filepath_name) { std::vector<double> temporary_vector; std::ifstream infile(filepath_name); std::string line = ""; while (std::getline(infile, line)) { std::istringstream string_stream(line); double temporary_value; if (!(string_stream >> temporary_value)) break; temporary_vector.push_back(temporary_value); } infile.close(); RArray signal(temporary_vector.size()); for (int i = 0; i < static_cast<int>(temporary_vector.size()); i++) { signal[i] = temporary_vector[i]; } return signal; } void SrpPhat::calculate_position_and_distribution(const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) { for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) { int degree = point_to_degree(xAxisValues[i], yAxisValues[j]); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[i][j]; } } // get maximum for normalization of values double normalization = degree_values.sum(); last_distribution_ = degree_values / normalization; double maximum_position = degree_values.max(); last_position_ = find_value(degree_values, maximum_position); } } // namespace localization } // namespace taylortrack <commit_msg>had to do the lint again<commit_after>/* The MIT License (MIT) Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack 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 * @brief Implementation of srpphat.h */ #include "localization/srp_phat.h" #include <string> #include <tuple> #include <vector> #include "utils/fft_lib.h" namespace taylortrack { namespace localization { double SrpPhat::inter_microphone_time_delay(const RArray &point, const RArray &microphone1, const RArray &microphone2) { return (std::sqrt(std::pow(point - microphone1, 2).sum()) - std::sqrt(std::pow(point - microphone2, 2).sum())) / kSpeedOfSound; } int SrpPhat::point_to_degree(double x_coordinate, double y_coordinate) { return static_cast<int>(round(fmod(((atan2(y_coordinate, x_coordinate) * 180 / kPI) + 360), 360.0))); } std::vector<std::tuple<int, int>> SrpPhat::get_microphone_pairs() { std::vector<std::tuple<int, int>> pairs; // iterating over microphones for (int i = 0; i < static_cast<int>(x_dim_mics_.size()); i++) { for (int j = 0; j < static_cast<int>(x_dim_mics_.size()); j++) { // only append pairs once and don't consider pairs of the same microphone if (j > i) { pairs.push_back(std::make_tuple(i, j)); } } } return pairs; } RArray SrpPhat::generalized_cross_correlation(const RArray &signal1, const RArray &signal2) { size_t corr_length = signal1.size() + signal2.size() - 1; /* bringing the signals into the right shape to work with the fftlib first making them complex and pad with necessary zeros */ taylortrack::utils::FftLib fft_obj = taylortrack::utils::FftLib(); CArray tempsignal1 = fft_obj.convert_to_complex(signal1); CArray tempsignal2 = fft_obj.convert_to_complex(signal2); CArray csignal1 = fft_obj.zero_padding(tempsignal1, static_cast<int> (corr_length - signal1.size())); CArray csignal2 = fft_obj.zero_padding(tempsignal2, static_cast<int> (corr_length - signal2.size())); // perform FFT on the converted signals fft_obj.fft(csignal1); fft_obj.fft(csignal2); // computing nominator and denominator of the generalized cross correlation CArray nominator = csignal1 * csignal2.apply(std::conj); CArray denominator = std::pow(abs(nominator), static_cast<float>(beta_)); // reverse transfering to time domain CArray temp = nominator / denominator; fft_obj.ifft(temp); RArray result(temp.size()); RArray temp3 = fft_obj.convert_to_real(temp); fft_obj.fftshift(temp3, result); return result; } std::vector<double> SrpPhat::get_axis_values(bool xaxis) { std::vector<double> axisValues; int vectorSize = static_cast<int>( xaxis ? x_length_ / stepsize_ + 1 : y_length_ / stepsize_ + 1); double axStart = xaxis ? x_length_ / 2 * -1 : y_length_ / 2; while (static_cast<int>(axisValues.size()) < vectorSize) { axisValues.push_back(axStart); axStart = xaxis ? axStart + stepsize_ : axStart - stepsize_; } return axisValues; } RArray SrpPhat::get_position_distribution(const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) { for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) { int degree = point_to_degree(xAxisValues[i], yAxisValues[j]); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[i][j]; } } // get maximum for normalization of values double res = degree_values.sum(); return degree_values / res; } int SrpPhat::get_position(const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < 360; i++) { degree_values[i] = 0; } int vectorSize = static_cast<int> (x_length_ / stepsize_ + 1); for (int i = 0; i < vectorSize; i++) { for (int j = 0; j < vectorSize; j++) { int degree = point_to_degree(xAxisValues[j], static_cast<double> (yAxisValues[i])); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[j][i]; } } double res = degree_values.max(); return find_value(degree_values, res); } int SrpPhat::find_value(const RArray &in_vector, double value) { for (int i = 0; i < static_cast<int>(in_vector.size()); i++) { if (std::abs(in_vector[i] - value) < 0.0001) { return i; } } return -1; } std::vector<std::vector<double>> SrpPhat::get_generalized_cross_correlation(const std::vector<RArray> &signals) { std::vector<std::tuple<int, int>> pairs = get_microphone_pairs(); std::vector<std::vector<double>> generalized_cross_correlation_values; int64_t vectorSize = int64_t(x_length_ / stepsize_ + 1); // initializing the gcc grid generalized_cross_correlation_values. resize(static_cast<int64_t>(vectorSize)); for (int i = 0; i < vectorSize; ++i) { generalized_cross_correlation_values[i]. resize(static_cast<int64_t>(vectorSize)); } std::vector<std::vector<std::vector<double>>> micDelays = delay_tensor_; // iterating over all microphone pairs for (int i = 0; i < static_cast<int>(pairs.size()); i++) { int index1 = std::get<0>(pairs[i]); int index2 = std::get<1>(pairs[i]); // assigning the corresponding signals RArray signal1 = signals[index1]; RArray signal2 = signals[index2]; // get the current frame from the complete signal RArray signalSlice1 = signal1[std::slice(0, static_cast<size_t>(steps_ + 1), 1)]; RArray signalSlice2 = signal2[std::slice(0, static_cast<size_t>(steps_), 1)]; // computing the cross correlation of both frames RArray generalized_cross_temp = generalized_cross_correlation(signalSlice1, signalSlice2); // iterating over the whole x-y grid for (int x = 0; x < vectorSize; x++) { for (int y = 0; y < vectorSize; y++) { double delay = micDelays[x][y][i]; // adding the corresponding cross correlation value to the grid generalized_cross_correlation_values[x][y] += generalized_cross_temp[(steps_ - 1) + round(delay / (1.0 / samplerate_))]; } } } return generalized_cross_correlation_values; } std::vector<std::vector<std::vector<double>>> SrpPhat::get_delay_tensor() { std::vector<std::vector<std::vector<double>>> delay_tensor; std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); std::vector<std::tuple<int, int>> pairs = get_microphone_pairs(); int vector_size = x_length_ / stepsize_ + 1; int depth = pairs.size(); delay_tensor.resize(vector_size); for (int i = 0; i < vector_size; ++i) { delay_tensor[i].resize(vector_size); for (int j = 0; j < vector_size; ++j) delay_tensor[i][j].resize(depth); } // iterating over the grid for (int x = 0; x < vector_size; x++) { for (int y = 0; y < vector_size; y++) { // iterating over microphone pairs for (int i = 0; i < static_cast<int>(pairs.size()); i++) { // RArray point(2); RArray microphone1(2); RArray microphone2(2); // assigning the current point in the grid point[0] = xAxisValues[x]; point[1] = yAxisValues[y]; // assigning the microphone values int index1 = std::get<0>(pairs[i]); int index2 = std::get<1>(pairs[i]); microphone1[0] = x_dim_mics_[index1]; microphone1[1] = y_dim_mics_[index1]; microphone2[0] = x_dim_mics_[index2]; microphone2[1] = y_dim_mics_[index2]; double delay = inter_microphone_time_delay(point, microphone1, microphone2); delay_tensor[x][y][i] = delay; } } } // iterating over all microphone pairs return delay_tensor; } RArray SrpPhat::get_microphone_signal(const std::string &filepath_name) { std::vector<double> temporary_vector; std::ifstream infile(filepath_name); std::string line = ""; while (std::getline(infile, line)) { std::istringstream string_stream(line); double temporary_value; if (!(string_stream >> temporary_value)) break; temporary_vector.push_back(temporary_value); } infile.close(); RArray signal(temporary_vector.size()); for (int i = 0; i < static_cast<int>(temporary_vector.size()); i++) { signal[i] = temporary_vector[i]; } return signal; } void SrpPhat::calculate_position_and_distribution( const std::vector<RArray> &signals) { std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals); RArray degree_values(360); std::vector<double> xAxisValues = get_axis_values(true); std::vector<double> yAxisValues = get_axis_values(false); for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) { for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) { int degree = point_to_degree(xAxisValues[i], yAxisValues[j]); if (degree == 360) degree = 0; degree_values[degree] += gcc_grid[i][j]; } } // get maximum for normalization of values double normalization = degree_values.sum(); last_distribution_ = degree_values / normalization; double maximum_position = degree_values.max(); last_position_ = find_value(degree_values, maximum_position); } } // namespace localization } // namespace taylortrack <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "buildjson.hpp" #include "file_handler.hpp" #include "firmware_handler.hpp" #include "flags.hpp" #include "general_systemd.hpp" #include "image_handler.hpp" #include "lpc_aspeed.hpp" #include "lpc_handler.hpp" #include "lpc_nuvoton.hpp" #include "net_handler.hpp" #include "pci_handler.hpp" #include "status.hpp" #include "util.hpp" #include <sdbusplus/bus.hpp> #include <cstdint> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace ipmi_flash { namespace { #ifdef NUVOTON_P2A_MBOX static constexpr std::size_t memoryRegionSize = 16 * 1024UL; #elif defined NUVOTON_P2A_VGA static constexpr std::size_t memoryRegionSize = 4 * 1024 * 1024UL; #else /* The maximum external buffer size we expect is 64KB. */ static constexpr std::size_t memoryRegionSize = 64 * 1024UL; #endif static constexpr const char* jsonConfigurationPath = "/usr/share/phosphor-ipmi-flash/"; #ifdef ENABLE_LPC_BRIDGE #if defined(ASPEED_LPC) LpcDataHandler lpcDataHandler( LpcMapperAspeed::createAspeedMapper(MAPPED_ADDRESS, memoryRegionSize)); #elif defined(NUVOTON_LPC) LpcDataHandler lpcDataHandler( LpcMapperNuvoton::createNuvotonMapper(MAPPED_ADDRESS, memoryRegionSize)); #else #error "You must specify a hardware implementation." #endif #endif #ifdef ENABLE_PCI_BRIDGE PciDataHandler pciDataHandler(MAPPED_ADDRESS, memoryRegionSize); #endif #ifdef ENABLE_NET_BRIDGE NetDataHandler netDataHandler; #endif std::vector<DataHandlerPack> supportedTransports = { {FirmwareFlags::UpdateFlags::ipmi, nullptr}, #ifdef ENABLE_PCI_BRIDGE {FirmwareFlags::UpdateFlags::p2a, &pciDataHandler}, #endif #ifdef ENABLE_LPC_BRIDGE {FirmwareFlags::UpdateFlags::lpc, &lpcDataHandler}, #endif #ifdef ENABLE_NET_BRIDGE {FirmwareFlags::UpdateFlags::net, &netDataHandler}, #endif }; /** * Given a name and path, create a HandlerPack. * * @param[in] name - the blob id path for this * @param[in] path - the file path to write the contents. * @return the HandlerPack. */ HandlerPack CreateFileHandlerPack(const std::string& name, const std::string& path) { return HandlerPack(name, std::make_unique<FileHandler>(path)); } } // namespace } // namespace ipmi_flash extern "C" { std::unique_ptr<blobs::GenericBlobInterface> createHandler(); } std::unique_ptr<blobs::GenericBlobInterface> createHandler() { ipmi_flash::ActionMap actionPacks = {}; std::vector<ipmi_flash::HandlerConfig> configsFromJson = ipmi_flash::BuildHandlerConfigs(ipmi_flash::jsonConfigurationPath); std::vector<ipmi_flash::HandlerPack> supportedFirmware; supportedFirmware.push_back(std::move(ipmi_flash::CreateFileHandlerPack( ipmi_flash::hashBlobId, HASH_FILENAME))); for (auto& config : configsFromJson) { supportedFirmware.push_back(std::move( ipmi_flash::HandlerPack(config.blobId, std::move(config.handler)))); actionPacks[config.blobId] = std::move(config.actions); std::fprintf(stderr, "config loaded: %s\n", config.blobId.c_str()); } auto handler = ipmi_flash::FirmwareBlobHandler::CreateFirmwareBlobHandler( std::move(supportedFirmware), std::move(ipmi_flash::supportedTransports), std::move(actionPacks)); if (!handler) { std::fprintf(stderr, "Firmware Handler has an invalid configuration"); return nullptr; } return handler; } <commit_msg>bmc: using namespace ipmi_flash simplifies reading<commit_after>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "buildjson.hpp" #include "file_handler.hpp" #include "firmware_handler.hpp" #include "flags.hpp" #include "general_systemd.hpp" #include "image_handler.hpp" #include "lpc_aspeed.hpp" #include "lpc_handler.hpp" #include "lpc_nuvoton.hpp" #include "net_handler.hpp" #include "pci_handler.hpp" #include "status.hpp" #include "util.hpp" #include <sdbusplus/bus.hpp> #include <cstdint> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace ipmi_flash { namespace { #ifdef NUVOTON_P2A_MBOX static constexpr std::size_t memoryRegionSize = 16 * 1024UL; #elif defined NUVOTON_P2A_VGA static constexpr std::size_t memoryRegionSize = 4 * 1024 * 1024UL; #else /* The maximum external buffer size we expect is 64KB. */ static constexpr std::size_t memoryRegionSize = 64 * 1024UL; #endif static constexpr const char* jsonConfigurationPath = "/usr/share/phosphor-ipmi-flash/"; #ifdef ENABLE_LPC_BRIDGE #if defined(ASPEED_LPC) LpcDataHandler lpcDataHandler( LpcMapperAspeed::createAspeedMapper(MAPPED_ADDRESS, memoryRegionSize)); #elif defined(NUVOTON_LPC) LpcDataHandler lpcDataHandler( LpcMapperNuvoton::createNuvotonMapper(MAPPED_ADDRESS, memoryRegionSize)); #else #error "You must specify a hardware implementation." #endif #endif #ifdef ENABLE_PCI_BRIDGE PciDataHandler pciDataHandler(MAPPED_ADDRESS, memoryRegionSize); #endif #ifdef ENABLE_NET_BRIDGE NetDataHandler netDataHandler; #endif std::vector<DataHandlerPack> supportedTransports = { {FirmwareFlags::UpdateFlags::ipmi, nullptr}, #ifdef ENABLE_PCI_BRIDGE {FirmwareFlags::UpdateFlags::p2a, &pciDataHandler}, #endif #ifdef ENABLE_LPC_BRIDGE {FirmwareFlags::UpdateFlags::lpc, &lpcDataHandler}, #endif #ifdef ENABLE_NET_BRIDGE {FirmwareFlags::UpdateFlags::net, &netDataHandler}, #endif }; /** * Given a name and path, create a HandlerPack. * * @param[in] name - the blob id path for this * @param[in] path - the file path to write the contents. * @return the HandlerPack. */ HandlerPack CreateFileHandlerPack(const std::string& name, const std::string& path) { return HandlerPack(name, std::make_unique<FileHandler>(path)); } } // namespace } // namespace ipmi_flash extern "C" { std::unique_ptr<blobs::GenericBlobInterface> createHandler(); } std::unique_ptr<blobs::GenericBlobInterface> createHandler() { using namespace ipmi_flash; ActionMap actionPacks = {}; std::vector<HandlerConfig> configsFromJson = BuildHandlerConfigs(jsonConfigurationPath); std::vector<HandlerPack> supportedFirmware; supportedFirmware.push_back( std::move(CreateFileHandlerPack(hashBlobId, HASH_FILENAME))); for (auto& config : configsFromJson) { supportedFirmware.push_back( std::move(HandlerPack(config.blobId, std::move(config.handler)))); actionPacks[config.blobId] = std::move(config.actions); std::fprintf(stderr, "config loaded: %s\n", config.blobId.c_str()); } auto handler = FirmwareBlobHandler::CreateFirmwareBlobHandler( std::move(supportedFirmware), std::move(supportedTransports), std::move(actionPacks)); if (!handler) { std::fprintf(stderr, "Firmware Handler has an invalid configuration"); return nullptr; } return handler; } <|endoftext|>
<commit_before>#include "ptreferential.h" #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_lit.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <iostream> #include "indexes2.h" #include "where.h" #include "reflexion.h" #include "proto/type.pb.h" #include <google/protobuf/descriptor.h> namespace qi = boost::spirit::qi; using namespace navitia::type; struct Column { std::string table; std::string column; }; BOOST_FUSION_ADAPT_STRUCT( Column, (std::string, table) (std::string, column) ) struct WhereClause{ Column col; std::string op; std::string value; }; BOOST_FUSION_ADAPT_STRUCT( WhereClause, (Column,col) (std::string, op) (std::string, value) ) struct Request { std::vector<Column> columns; std::vector<std::string> tables; std::vector<WhereClause> clauses; }; BOOST_FUSION_ADAPT_STRUCT( Request, (std::vector<Column>, columns) (std::vector<std::string>, tables) (std::vector<WhereClause>, clauses) ) template <typename Iterator> struct select_r : qi::grammar<Iterator, Request(), qi::space_type> { qi::rule<Iterator, std::string(), qi::space_type> txt; // Match une string qi::rule<Iterator, Column(), qi::space_type> table_col; // Match une colonne qi::rule<Iterator, std::vector<Column>(), qi::space_type> select; // Match toute la section SELECT qi::rule<Iterator, std::vector<std::string>(), qi::space_type> from; // Matche la section FROM qi::rule<Iterator, Request(), qi::space_type> request; // Toute la requête qi::rule<Iterator, std::vector<WhereClause>(), qi::space_type> where;// section Where qi::rule<Iterator, std::string(), qi::space_type> bin_op; // Match une operator binaire telle que <, =... select_r() : select_r::base_type(request) { txt %= qi::lexeme[+(qi::alnum|'_')]; // Match du texte bin_op %= qi::string("<=") | qi::string(">=") | qi::string("<>") | qi::string("<") | qi::string(">") | qi::string("=") ; table_col %= -(txt >> '.') // (Nom de la table suivit de point) optionnel (operateur -) >> txt; // Nom de la table obligatoire select %= qi::lexeme["select"] >> table_col % ',' ; // La liste de table_col séparée par des , from %= qi::lexeme["from"] >> txt % ','; where %= qi::lexeme["where"] >> (table_col >> bin_op >> txt) % qi::lexeme["and"]; request %= select >> from >> -where; } }; template<class T> WhereWrapper<T> build_clause(std::vector<WhereClause> clauses) { WhereWrapper<T> wh(new BaseWhere<T>()); Operator_e op; BOOST_FOREACH(auto clause, clauses) { if(clause.op == "=") op = EQ; else if(clause.op == "<") op = LT; else if(clause.op == "<=") op = LEQ; else if(clause.op == ">") op = GT; else if(clause.op == ">=") op = GEQ; else if(clause.op == "<>") op = NEQ; else throw "grrr"; if(clause.col.column == "id") wh = wh && WHERE(ptr_id<T>(), op, clause.value); else if(clause.col.column == "idx") wh = wh && WHERE(ptr_idx<T>(), op, clause.value); else if(clause.col.column == "external_code") wh = wh && WHERE(ptr_external_code<T>(), op, clause.value); } return wh; } std::string unpluralize_table(const std::string& table_name){ if(table_name == "cities"){ return "city"; }else{ return table_name.substr(0, table_name.length() - 1); } } template<class T> void set_value(google::protobuf::Message* message, const T& object, const std::string& column){ const google::protobuf::Reflection* reflection = message->GetReflection(); const google::protobuf::Descriptor* descriptor = message->GetDescriptor(); const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(column); if(field_descriptor == NULL){ throw unknown_member(); } if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING){ reflection->SetString(message, field_descriptor, get_string_value(object, column)); }else if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_INT32){ reflection->SetInt32(message, field_descriptor, get_int_value(object, column)); }else{ throw bad_type(); } } google::protobuf::Message* get_message(pbnavitia::PTreferential* row, const std::string& table){ const google::protobuf::Reflection* reflection = row->GetReflection(); const google::protobuf::Descriptor* descriptor = row->GetDescriptor(); std::string field = unpluralize_table(table); const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(field); return reflection->MutableMessage(row, field_descriptor); } template<class T> std::vector< std::vector<col_t> > extract_data(std::vector<T> & rows, const Request & r) { pbnavitia::PTRefResponse pb_response; std::vector< std::vector<col_t> > result; Index2<boost::fusion::vector<T> > filtered(rows, build_clause<T>(r.clauses)); BOOST_FOREACH(auto item, filtered){ std::vector<col_t> row; pbnavitia::PTreferential * pb_row = pb_response.add_item(); google::protobuf::Message* pb_message = get_message(pb_row, r.tables.at(0)); BOOST_FOREACH(const Column & col, r.columns){ row.push_back(get_value(*(boost::fusion::at_c<0>(item)), col.column)); set_value(pb_message, *(boost::fusion::at_c<0>(item)), col.column); } result.push_back(row); } std::cout << "J'ai généré un protocol buffer de taille " << pb_response.ByteSize() << std::endl; //std::cout << pb_response.SerializeToOstream(&std::cout) << std::endl; return result; } struct unknown_table{}; std::vector< std::vector<col_t> > query(std::string request, Data & data){ std::vector< std::vector<col_t> > result; std::string::iterator begin = request.begin(); Request r; select_r<std::string::iterator> s; if (qi::phrase_parse(begin, request.end(), s, qi::space, r)) { if(begin != request.end()) { std::cout << "Hrrrmmm on a pas tout parsé -_-'" << std::endl; } } else std::cout << "Parsage a échoué" << std::endl; if(r.tables.size() != 1){ std::cout << "Pour l'instant on ne supporte que exactement une table" << std::endl; return result; } else { std::cout << "Table : " << r.tables[0] << std::endl; } std::string table = r.tables[0]; /*if(table == "validity_pattern") { return extract_data(data.validity_patterns, r); } else*/ if(table == "lines") { return extract_data(data.lines, r); } else if(table == "routes") { return extract_data(data.routes, r); } /*else if(table == "vehicle_journey") { return extract_data(data.vehicle_journeys, r); }*/ else if(table == "stop_points") { return extract_data(data.stop_points, r); } else if(table == "stop_areas") { return extract_data(data.stop_areas, r); } /* else if(table == "stop_times"){ return extract_data(data.stop_times, r); }*/ throw unknown_table(); } int main(int argc, char** argv){ std::cout << "Chargement des données..." << std::flush; Data d; d.load_flz("data.nav.flz"); std::cout << " effectué" << std::endl << std::endl; std::cout << "Statistiques :" << std::endl << " Nombre de StopAreas : " << d.stop_areas.size() << std::endl << " Nombre de StopPoints : " << d.stop_points.size() << std::endl << " Nombre de lignes : " << d.lines.size() << std::endl << " Nombre d'horaires : " << d.stop_times.size() << std::endl << std::endl; if(argc != 2) std::cout << "Il faut exactement un paramètre" << std::endl; else { auto result = query(argv[1], d); std::cout << "Il y a " << result.size() << " lignes de résultat" << std::endl; BOOST_FOREACH(auto row, result){ BOOST_FOREACH(auto col, row){ std::cout << col << ",\t"; } std::cout << std::endl; } } return 0; } <commit_msg>correction d'un include suite a l'ajout de protobuff<commit_after>#include "ptreferential.h" #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_lit.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <iostream> #include "indexes2.h" #include "where.h" #include "reflexion.h" #include "type.pb.h" #include <google/protobuf/descriptor.h> namespace qi = boost::spirit::qi; using namespace navitia::type; struct Column { std::string table; std::string column; }; BOOST_FUSION_ADAPT_STRUCT( Column, (std::string, table) (std::string, column) ) struct WhereClause{ Column col; std::string op; std::string value; }; BOOST_FUSION_ADAPT_STRUCT( WhereClause, (Column,col) (std::string, op) (std::string, value) ) struct Request { std::vector<Column> columns; std::vector<std::string> tables; std::vector<WhereClause> clauses; }; BOOST_FUSION_ADAPT_STRUCT( Request, (std::vector<Column>, columns) (std::vector<std::string>, tables) (std::vector<WhereClause>, clauses) ) template <typename Iterator> struct select_r : qi::grammar<Iterator, Request(), qi::space_type> { qi::rule<Iterator, std::string(), qi::space_type> txt; // Match une string qi::rule<Iterator, Column(), qi::space_type> table_col; // Match une colonne qi::rule<Iterator, std::vector<Column>(), qi::space_type> select; // Match toute la section SELECT qi::rule<Iterator, std::vector<std::string>(), qi::space_type> from; // Matche la section FROM qi::rule<Iterator, Request(), qi::space_type> request; // Toute la requête qi::rule<Iterator, std::vector<WhereClause>(), qi::space_type> where;// section Where qi::rule<Iterator, std::string(), qi::space_type> bin_op; // Match une operator binaire telle que <, =... select_r() : select_r::base_type(request) { txt %= qi::lexeme[+(qi::alnum|'_')]; // Match du texte bin_op %= qi::string("<=") | qi::string(">=") | qi::string("<>") | qi::string("<") | qi::string(">") | qi::string("=") ; table_col %= -(txt >> '.') // (Nom de la table suivit de point) optionnel (operateur -) >> txt; // Nom de la table obligatoire select %= qi::lexeme["select"] >> table_col % ',' ; // La liste de table_col séparée par des , from %= qi::lexeme["from"] >> txt % ','; where %= qi::lexeme["where"] >> (table_col >> bin_op >> txt) % qi::lexeme["and"]; request %= select >> from >> -where; } }; template<class T> WhereWrapper<T> build_clause(std::vector<WhereClause> clauses) { WhereWrapper<T> wh(new BaseWhere<T>()); Operator_e op; BOOST_FOREACH(auto clause, clauses) { if(clause.op == "=") op = EQ; else if(clause.op == "<") op = LT; else if(clause.op == "<=") op = LEQ; else if(clause.op == ">") op = GT; else if(clause.op == ">=") op = GEQ; else if(clause.op == "<>") op = NEQ; else throw "grrr"; if(clause.col.column == "id") wh = wh && WHERE(ptr_id<T>(), op, clause.value); else if(clause.col.column == "idx") wh = wh && WHERE(ptr_idx<T>(), op, clause.value); else if(clause.col.column == "external_code") wh = wh && WHERE(ptr_external_code<T>(), op, clause.value); } return wh; } std::string unpluralize_table(const std::string& table_name){ if(table_name == "cities"){ return "city"; }else{ return table_name.substr(0, table_name.length() - 1); } } template<class T> void set_value(google::protobuf::Message* message, const T& object, const std::string& column){ const google::protobuf::Reflection* reflection = message->GetReflection(); const google::protobuf::Descriptor* descriptor = message->GetDescriptor(); const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(column); if(field_descriptor == NULL){ throw unknown_member(); } if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING){ reflection->SetString(message, field_descriptor, get_string_value(object, column)); }else if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_INT32){ reflection->SetInt32(message, field_descriptor, get_int_value(object, column)); }else{ throw bad_type(); } } google::protobuf::Message* get_message(pbnavitia::PTreferential* row, const std::string& table){ const google::protobuf::Reflection* reflection = row->GetReflection(); const google::protobuf::Descriptor* descriptor = row->GetDescriptor(); std::string field = unpluralize_table(table); const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(field); return reflection->MutableMessage(row, field_descriptor); } template<class T> std::vector< std::vector<col_t> > extract_data(std::vector<T> & rows, const Request & r) { pbnavitia::PTRefResponse pb_response; std::vector< std::vector<col_t> > result; Index2<boost::fusion::vector<T> > filtered(rows, build_clause<T>(r.clauses)); BOOST_FOREACH(auto item, filtered){ std::vector<col_t> row; pbnavitia::PTreferential * pb_row = pb_response.add_item(); google::protobuf::Message* pb_message = get_message(pb_row, r.tables.at(0)); BOOST_FOREACH(const Column & col, r.columns){ row.push_back(get_value(*(boost::fusion::at_c<0>(item)), col.column)); set_value(pb_message, *(boost::fusion::at_c<0>(item)), col.column); } result.push_back(row); } std::cout << "J'ai généré un protocol buffer de taille " << pb_response.ByteSize() << std::endl; //std::cout << pb_response.SerializeToOstream(&std::cout) << std::endl; return result; } struct unknown_table{}; std::vector< std::vector<col_t> > query(std::string request, Data & data){ std::vector< std::vector<col_t> > result; std::string::iterator begin = request.begin(); Request r; select_r<std::string::iterator> s; if (qi::phrase_parse(begin, request.end(), s, qi::space, r)) { if(begin != request.end()) { std::cout << "Hrrrmmm on a pas tout parsé -_-'" << std::endl; } } else std::cout << "Parsage a échoué" << std::endl; if(r.tables.size() != 1){ std::cout << "Pour l'instant on ne supporte que exactement une table" << std::endl; return result; } else { std::cout << "Table : " << r.tables[0] << std::endl; } std::string table = r.tables[0]; /*if(table == "validity_pattern") { return extract_data(data.validity_patterns, r); } else*/ if(table == "lines") { return extract_data(data.lines, r); } else if(table == "routes") { return extract_data(data.routes, r); } /*else if(table == "vehicle_journey") { return extract_data(data.vehicle_journeys, r); }*/ else if(table == "stop_points") { return extract_data(data.stop_points, r); } else if(table == "stop_areas") { return extract_data(data.stop_areas, r); } /* else if(table == "stop_times"){ return extract_data(data.stop_times, r); }*/ throw unknown_table(); } int main(int argc, char** argv){ std::cout << "Chargement des données..." << std::flush; Data d; d.load_flz("data.nav.flz"); std::cout << " effectué" << std::endl << std::endl; std::cout << "Statistiques :" << std::endl << " Nombre de StopAreas : " << d.stop_areas.size() << std::endl << " Nombre de StopPoints : " << d.stop_points.size() << std::endl << " Nombre de lignes : " << d.lines.size() << std::endl << " Nombre d'horaires : " << d.stop_times.size() << std::endl << std::endl; if(argc != 2) std::cout << "Il faut exactement un paramètre" << std::endl; else { auto result = query(argv[1], d); std::cout << "Il y a " << result.size() << " lignes de résultat" << std::endl; BOOST_FOREACH(auto row, result){ BOOST_FOREACH(auto col, row){ std::cout << col << ",\t"; } std::cout << std::endl; } } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Elasticity_test.h" #include <SofaBaseMechanics/MechanicalObject.h> #include <SofaDeformable/MeshSpringForceField.h> #include <SofaBoundaryCondition/AffineMovementConstraint.h> #include <sofa/defaulttype/VecTypes.h> namespace sofa { template <typename _DataTypes> struct AffineMovementConstraint_test : public Elasticity_test<_DataTypes> { typedef _DataTypes DataTypes; typedef typename DataTypes::Coord Coord; typedef typename DataTypes::VecCoord VecCoord; typedef typename DataTypes::VecDeriv VecDeriv; typedef typename DataTypes::Coord Coord; typedef typename DataTypes::Deriv Deriv; typedef typename DataTypes::CPos CPos; typedef typename Coord::value_type Real; typedef component::container::MechanicalObject<DataTypes> MechanicalObject; typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField; /// Root of the scene graph simulation::Node::SPtr root; /// Tested simulation simulation::Simulation* simulation; /// Structure which contains current node and pointers to the mechanical object and the affine constraint PatchTestStruct<DataTypes> patchStruct; /// Tested Rotation: random rotation matrix defaulttype::Mat<3,3,Real> testedRotation; /// Tested Translation: random translation Coord testedTranslation; /// Seed for random value long seed; // Random generator sofa::helper::RandomGenerator randomGenerator; // Create the context for the scene void SetUp() { // Init simulation sofa::component::init(); sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); // Init seed with a random value between 0 and 100 randomGenerator.initSeed( (long)time(0) ); seed = randomGenerator.random<long>(0,100); // Create a scene with a regular grid patchStruct = this->createRegularGridScene( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,0), // End point of regular grid 5,5,1, // Resolution of the regular grid Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // BoxRoi to find all mesh points Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi Vec<6,SReal>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; //Force field for 2D Grid typename MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField"); meshSpringForceField->setStiffness(10); // Init seed randomGenerator.initSeed(seed); // Random Rotation SReal x,y,z,w; x = 0; y = 0; z = 1; w = randomGenerator.random<SReal>(0.0,360.0); Quat quat(x,y,z,w); quat.normalize(); quat.toMatrix(testedRotation); patchStruct.affineConstraint->m_rotation.setValue(testedRotation); // Random Translation for(size_t i=0;i<Coord::total_size;++i) { testedTranslation[i]=randomGenerator.random<SReal>(-2.0,2.0); if(i==2) testedTranslation[i]=0; } patchStruct.affineConstraint->m_translation.setValue(testedTranslation); patchStruct.affineConstraint->m_endConstraintTime.setValue(0.1); } // After simulation compare the positions of points to the theoretical positions. bool projectPosition(double convergenceAccuracy, double diffMaxBetweenSimulatedAndTheoreticalPosition) { // Init simulation sofa::simulation::getSimulation()->init(root.get()); // Compute the theoretical final positions VecCoord finalPos; patchStruct.affineConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) ); // Initialize size_t numNodes = finalPos.size(); VecCoord xprev(numNodes); VecDeriv dx(numNodes); bool hasConverged = true; for (size_t i=0; i<numNodes; i++) { xprev[i] = CPos(0,0,0); } // Animate do { hasConverged = true; sofa::simulation::getSimulation()->animate(root.get(),0.5); typename MechanicalObject::ReadVecCoord x = patchStruct.dofs->readPositions(); // Compute dx for (size_t i=0; i<x.size(); i++) { dx[i] = x[i]-xprev[i]; // Test convergence if(dx[i].norm()>convergenceAccuracy) hasConverged = false; } // xprev = x for (size_t i=0; i<numNodes; i++) { xprev[i]=x[i]; } } while(!hasConverged); // not converged // Get simulated positions typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions(); // Compare the theoretical positions and the simulated positions bool succeed=true; for(size_t i=0; i<finalPos.size(); i++ ) { if((finalPos[i]-x[i]).norm()>diffMaxBetweenSimulatedAndTheoreticalPosition) { succeed = false; ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << std::endl << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl <<"rotation = " << testedRotation << std::endl << " translation = " << testedTranslation << std::endl << "seed =" << seed; } } return succeed; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< defaulttype::Vec3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(AffineMovementConstraint_test, DataTypes); // first test case TYPED_TEST( AffineMovementConstraint_test , testValue ) { ASSERT_TRUE( this->projectPosition(5e-6,5e-5)); } }// namespace sofa <commit_msg>FIX: Compilation on linux.<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Elasticity_test.h" #include <SofaBaseMechanics/MechanicalObject.h> #include <SofaDeformable/MeshSpringForceField.h> #include <SofaBoundaryCondition/AffineMovementConstraint.h> #include <sofa/defaulttype/VecTypes.h> namespace sofa { template <typename _DataTypes> struct AffineMovementConstraint_test : public Elasticity_test<_DataTypes> { typedef _DataTypes DataTypes; typedef typename DataTypes::Coord Coord; typedef typename DataTypes::VecCoord VecCoord; typedef typename DataTypes::VecDeriv VecDeriv; typedef typename DataTypes::Deriv Deriv; typedef typename DataTypes::CPos CPos; typedef typename Coord::value_type Real; typedef component::container::MechanicalObject<DataTypes> MechanicalObject; typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField; /// Root of the scene graph simulation::Node::SPtr root; /// Tested simulation simulation::Simulation* simulation; /// Structure which contains current node and pointers to the mechanical object and the affine constraint PatchTestStruct<DataTypes> patchStruct; /// Tested Rotation: random rotation matrix defaulttype::Mat<3,3,Real> testedRotation; /// Tested Translation: random translation Coord testedTranslation; /// Seed for random value long seed; // Random generator sofa::helper::RandomGenerator randomGenerator; // Create the context for the scene void SetUp() { // Init simulation sofa::component::init(); sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); // Init seed with a random value between 0 and 100 randomGenerator.initSeed( (long)time(0) ); seed = randomGenerator.random<long>(0,100); // Create a scene with a regular grid patchStruct = this->createRegularGridScene( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,0), // End point of regular grid 5,5,1, // Resolution of the regular grid Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // BoxRoi to find all mesh points Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi Vec<6,SReal>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; //Force field for 2D Grid typename MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField"); meshSpringForceField->setStiffness(10); // Init seed randomGenerator.initSeed(seed); // Random Rotation SReal x,y,z,w; x = 0; y = 0; z = 1; w = randomGenerator.random<SReal>(0.0,360.0); Quat quat(x,y,z,w); quat.normalize(); quat.toMatrix(testedRotation); patchStruct.affineConstraint->m_rotation.setValue(testedRotation); // Random Translation for(size_t i=0;i<Coord::total_size;++i) { testedTranslation[i]=randomGenerator.random<SReal>(-2.0,2.0); if(i==2) testedTranslation[i]=0; } patchStruct.affineConstraint->m_translation.setValue(testedTranslation); patchStruct.affineConstraint->m_endConstraintTime.setValue(0.1); } // After simulation compare the positions of points to the theoretical positions. bool projectPosition(double convergenceAccuracy, double diffMaxBetweenSimulatedAndTheoreticalPosition) { // Init simulation sofa::simulation::getSimulation()->init(root.get()); // Compute the theoretical final positions VecCoord finalPos; patchStruct.affineConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) ); // Initialize size_t numNodes = finalPos.size(); VecCoord xprev(numNodes); VecDeriv dx(numNodes); bool hasConverged = true; for (size_t i=0; i<numNodes; i++) { xprev[i] = CPos(0,0,0); } // Animate do { hasConverged = true; sofa::simulation::getSimulation()->animate(root.get(),0.5); typename MechanicalObject::ReadVecCoord x = patchStruct.dofs->readPositions(); // Compute dx for (size_t i=0; i<x.size(); i++) { dx[i] = x[i]-xprev[i]; // Test convergence if(dx[i].norm()>convergenceAccuracy) hasConverged = false; } // xprev = x for (size_t i=0; i<numNodes; i++) { xprev[i]=x[i]; } } while(!hasConverged); // not converged // Get simulated positions typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions(); // Compare the theoretical positions and the simulated positions bool succeed=true; for(size_t i=0; i<finalPos.size(); i++ ) { if((finalPos[i]-x[i]).norm()>diffMaxBetweenSimulatedAndTheoreticalPosition) { succeed = false; ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << std::endl << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl <<"rotation = " << testedRotation << std::endl << " translation = " << testedTranslation << std::endl << "seed =" << seed; } } return succeed; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< defaulttype::Vec3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(AffineMovementConstraint_test, DataTypes); // first test case TYPED_TEST( AffineMovementConstraint_test , testValue ) { ASSERT_TRUE( this->projectPosition(5e-6,5e-5)); } }// namespace sofa <|endoftext|>
<commit_before>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler 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 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 GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*}}}*/ // INCLUDES/*{{{*/ #include <string> #include "InputDummy.hxx" /*}}}*/ InputDummy::InputDummy(const std::string &filename)/*{{{*/ : _filename(filename) { } /*}}}*/ std::string InputDummy::_createPath() const/*{{{*/ { return _filename; } /*}}}*/ const std::string &InputDummy::getLastInput() const/*{{{*/ { return _lastInput; } /*}}}*/ void InputDummy::_handleInput(const std::string &input)/*{{{*/ { _lastInput = input; } /*}}}*/ // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <commit_msg>tests/File/InputDummy.cxx: Added debug in _handleInput().<commit_after>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler 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 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 GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*}}}*/ // INCLUDES/*{{{*/ #ifdef HAVE_CONFIG_H # include <config.hxx> # include <print.hxx> #endif #include <string> #include "InputDummy.hxx" /*}}}*/ InputDummy::InputDummy(const std::string &filename)/*{{{*/ : _filename(filename) { } /*}}}*/ std::string InputDummy::_createPath() const/*{{{*/ { return _filename; } /*}}}*/ const std::string &InputDummy::getLastInput() const/*{{{*/ { return _lastInput; } /*}}}*/ void InputDummy::_handleInput(const std::string &input)/*{{{*/ { #ifdef DEBUG printLog("INPUT: " + input); #endif _lastInput = input; } /*}}}*/ // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // 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) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include "hadesmem/write.hpp" #include <array> #include <string> #include <vector> #define BOOST_TEST_MODULE write #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/process.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(write_pod) { hadesmem::Process const process(::GetCurrentProcessId()); struct TestPODType { int a; char* b; wchar_t c; long long d; }; TestPODType test_pod_type = { 1, 0, L'a', 1234567812345678 }; TestPODType test_pod_type_2 = { -1, 0, L'x', 9876543210 }; Write(process, &test_pod_type, test_pod_type_2); BOOST_CHECK_EQUAL(std::memcmp(&test_pod_type, &test_pod_type_2, sizeof(test_pod_type)), 0); } BOOST_AUTO_TEST_CASE(write_string) { hadesmem::Process const process(::GetCurrentProcessId()); std::string const test_string = "Narrow test string."; std::vector<char> test_string_buf(test_string.size() + 1); using std::begin; using std::end; std::copy(begin(test_string), end(test_string), test_string_buf.data()); std::string const test_string_str(test_string_buf.data()); BOOST_CHECK_EQUAL_COLLECTIONS(begin(test_string), end(test_string), begin(test_string_str), end(test_string_str)); auto const test_string_rev = std::string(test_string.rbegin(), test_string.rend()); WriteString(process, test_string_buf.data(), test_string_rev); auto const new_test_string_rev = std::string(test_string_buf.data()); BOOST_CHECK_EQUAL_COLLECTIONS(new_test_string_rev.cbegin(), new_test_string_rev.cend(), test_string_rev.cbegin(), test_string_rev.cend()); } BOOST_AUTO_TEST_CASE(write_vector) { hadesmem::Process const process(::GetCurrentProcessId()); std::array<int, 10> int_list = {{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }}; std::vector<int> int_list_rev(int_list.crbegin(), int_list.crend()); WriteVector(process, &int_list, int_list_rev); BOOST_CHECK_EQUAL_COLLECTIONS(int_list.cbegin(), int_list.cend(), int_list_rev.cbegin(), int_list_rev.cend()); } <commit_msg>* Formatting.<commit_after>// Copyright Joshua Boyce 2010-2012. // 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) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include "hadesmem/write.hpp" #include <array> #include <string> #include <vector> #define BOOST_TEST_MODULE write #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/process.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(write_pod) { hadesmem::Process const process(::GetCurrentProcessId()); struct TestPODType { int a; char* b; wchar_t c; long long d; }; TestPODType test_pod_type = { 1, 0, L'a', 1234567812345678 }; TestPODType test_pod_type_2 = { -1, 0, L'x', 9876543210 }; Write(process, &test_pod_type, test_pod_type_2); BOOST_CHECK_EQUAL(std::memcmp(&test_pod_type, &test_pod_type_2, sizeof(test_pod_type)), 0); } BOOST_AUTO_TEST_CASE(write_string) { hadesmem::Process const process(::GetCurrentProcessId()); std::string const test_string = "Narrow test string."; std::vector<char> test_string_buf(test_string.size() + 1); using std::begin; using std::end; std::copy(begin(test_string), end(test_string), test_string_buf.data()); std::string const test_string_str(test_string_buf.data()); BOOST_CHECK_EQUAL_COLLECTIONS(begin(test_string), end(test_string), begin(test_string_str), end(test_string_str)); auto const test_string_rev = std::string(test_string.rbegin(), test_string.rend()); WriteString(process, test_string_buf.data(), test_string_rev); auto const new_test_string_rev = std::string(test_string_buf.data()); BOOST_CHECK_EQUAL_COLLECTIONS(new_test_string_rev.cbegin(), new_test_string_rev.cend(), test_string_rev.cbegin(), test_string_rev.cend()); } BOOST_AUTO_TEST_CASE(write_vector) { hadesmem::Process const process(::GetCurrentProcessId()); std::array<int, 10> int_list = {{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }}; std::vector<int> int_list_rev(int_list.crbegin(), int_list.crend()); WriteVector(process, &int_list, int_list_rev); BOOST_CHECK_EQUAL_COLLECTIONS(int_list.cbegin(), int_list.cend(), int_list_rev.cbegin(), int_list_rev.cend()); } <|endoftext|>
<commit_before>// Compare numerically calculated C-V curves with analytic solution using namespace GeFiCa; const int n=2001; // get capacitance based on C=epsilon*A/d double GetCfromDepletionDepth(double voltage, double thickness) { // calculate fields Planar1D detector(n); detector.Thickness=thickness; detector.V0=voltage; // for bottom electrode detector.V1=0*volt; // for top electrode TF3 *fi = new TF3("f","-1e10"); // 1/cm3 detector.SetImpurity(fi); detector.Csor=1.999; detector.MaxIterations=20000; detector.CalculatePotential(kSOR2); delete fi; //search for depletion depth double up=thickness, down=0, depth=thickness; while(up-down>1e-3) { depth=(down+up)/2; if(detector.GetV(depth)>0) down=depth; if(detector.GetV(depth)<=0) up=depth; } double A = 1*cm*1*cm; return epsilon*A/depth; } //______________________________________________________________________________ // use GefiCa::X::GetC() double GetCfromGeFiCa(double voltage, double thickness) { // calculate fields Planar1D detector(n); detector.Thickness=thickness; detector.V0=voltage; // for bottom electrode detector.V1=0*volt; // for top electrode TF3 *fi = new TF3("f","-1e10"); // 1/cm3 detector.SetImpurity(fi); detector.Csor=1.999; detector.MaxIterations=20000; double c=detector.GetC(); delete fi; return c; } //______________________________________________________________________________ // double GetCanalytically(double voltage, double thickness) { //voltage=ax^2+c2x+c1 //c1=0, when voltage=0 at x=0 //c2=-ad, when E=dV/dx=0 at x=0, where just depleted //a is rho/epsilon //voltage=-ax^2/2, solve voltage when x=depth double rho=-1e10/cm3*Qe; double depth=TMath::Sqrt(-2*epsilon*voltage/rho); if (depth>thickness) depth=thickness; double A = 1*cm*1*cm; return epsilon*A/depth; } //______________________________________________________________________________ // void verifyCV() { double thickness=1*cm; const int np=16; Double_t V[np], Cn[np], Ca[np],Cg[np]; for (Int_t i=0;i<np;i++) { V[i] = (i+1)*50*volt; Printf("voltage: %.0f V", V[i]); Cn[i] = GetCfromDepletionDepth(V[i],thickness)/pF; Cg[i] = GetCfromGeFiCa(V[i],thickness)/pF; Ca[i] = GetCanalytically(V[i],thickness)/pF; } TGraph *gn = new TGraph(np,V,Cn); gn->SetMarkerStyle(22); TGraph *gg = new TGraph(np,V,Cg); gg->SetMarkerStyle(24); TGraph *ga = new TGraph(np,V,Ca); ga->SetMarkerStyle(25); gStyle->SetPadLeftMargin(0.08); gStyle->SetPadRightMargin(0.01); gStyle->SetTitleOffset(0.75,"y"); TMultiGraph *gs = new TMultiGraph; gs->Add(gn); gs->Add(gg); gs->Add(ga); gs->SetTitle(";Bias [V];Capacitance per cm^{2} [pF]"); gs->Draw("pal"); TLegend *l = new TLegend(0.5,0.6,0.97,0.97); l->AddEntry(ga,"#varepsilon A/d, analytically","pl"); l->AddEntry(gn,"#varepsilon A/d, numerically","pl"); l->AddEntry(gg,"GeFiCa::X::GetC()","pl"); l->Draw(); } <commit_msg>reduced number of grid points<commit_after>// Compare numerically calculated C-V curves with analytic solution using namespace GeFiCa; const int n=401; // get capacitance based on C=epsilon*A/d double GetCfromDepletionDepth(double voltage, double thickness) { // calculate fields Planar1D detector(n); detector.Thickness=thickness; detector.V0=voltage; // for bottom electrode detector.V1=0*volt; // for top electrode detector.SetAverageImpurity(-1e10/cm3); detector.CalculatePotential(); //search for depletion depth double up=thickness, down=0, depth=thickness; while(up-down>1e-3) { depth=(down+up)/2; if(detector.GetV(depth)>0) down=depth; if(detector.GetV(depth)<=0) up=depth; } double A = 1*cm*1*cm; return epsilon*A/depth; } //______________________________________________________________________________ // use GefiCa::X::GetC() double GetCfromGeFiCa(double voltage, double thickness) { // calculate fields Planar1D detector(n); detector.Thickness=thickness; detector.V0=voltage; // for bottom electrode detector.V1=0*volt; // for top electrode detector.SetAverageImpurity(-1e10/cm3); return detector.GetC(); } //______________________________________________________________________________ // double GetCanalytically(double voltage, double thickness) { //voltage=ax^2+c2x+c1 //c1=0, when voltage=0 at x=0 //c2=-ad, when E=dV/dx=0 at x=0, where just depleted //a is rho/epsilon //voltage=-ax^2/2, solve voltage when x=depth double rho=-1e10/cm3*Qe; double depth=TMath::Sqrt(-2*epsilon*voltage/rho); if (depth>thickness) depth=thickness; double A = 1*cm*1*cm; return epsilon*A/depth; } //______________________________________________________________________________ // void verifyCV() { double thickness=1*cm; const int np=16; Double_t V[np], Cn[np], Ca[np],Cg[np]; for (Int_t i=0;i<np;i++) { V[i] = (i+2)*50*volt; Printf("voltage: %.0f V", V[i]); Cn[i] = GetCfromDepletionDepth(V[i],thickness)/pF; Cg[i] = GetCfromGeFiCa(V[i],thickness)/pF; Ca[i] = GetCanalytically(V[i],thickness)/pF; } TGraph *gn = new TGraph(np,V,Cn); gn->SetMarkerStyle(22); TGraph *gg = new TGraph(np,V,Cg); gg->SetMarkerStyle(24); TGraph *ga = new TGraph(np,V,Ca); ga->SetMarkerStyle(25); gStyle->SetPadLeftMargin(0.09); gStyle->SetPadRightMargin(0.01); gStyle->SetTitleOffset(0.85,"y"); TMultiGraph *gs = new TMultiGraph; gs->Add(gn); gs->Add(gg); gs->Add(ga); gs->SetTitle(";Bias [V];Capacitance per cm^{2} [pF]"); gs->Draw("pal"); TLegend *l = new TLegend(0.5,0.6,0.97,0.97); l->AddEntry(ga,"#varepsilon A/d, analytically","pl"); l->AddEntry(gn,"#varepsilon A/d, numerically","pl"); l->AddEntry(gg,"GeFiCa::X::GetC()","pl"); l->Draw(); } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011-2012 Jose Fonseca * All Rights Reserved. * * 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 _RETRACE_HPP_ #define _RETRACE_HPP_ #include <assert.h> #include <string.h> #include <stdint.h> #include <list> #include <map> #include <ostream> #include "trace_model.hpp" #include "trace_parser.hpp" namespace retrace { extern trace::Parser parser; /** * Handle map. * * It is just like a regular std::map<T, T> container, but lookups of missing * keys return the key instead of default constructor. * * This is necessary for several GL named objects, where one can either request * the implementation to generate an unique name, or pick a value never used * before. * * XXX: In some cases, instead of returning the key, it would make more sense * to return an unused data value (e.g., container count). */ template <class T> class map { private: typedef std::map<T, T> base_type; base_type base; public: T & operator[] (const T &key) { typename base_type::iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } const T & operator[] (const T &key) const { typename base_type::const_iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } }; /** * Similar to alloca(), but implemented with malloc. */ class ScopedAllocator { private: uintptr_t next; public: ScopedAllocator() : next(0) { } inline void * alloc(size_t size) { if (!size) { return NULL; } uintptr_t * buf = static_cast<uintptr_t *>(malloc(sizeof(uintptr_t) + size)); if (!buf) { return NULL; } *buf = next; next = reinterpret_cast<uintptr_t>(buf); assert((next & 1) == 0); return static_cast<void *>(&buf[1]); } template< class T > inline T * alloc(size_t n = 1) { return static_cast<T *>(alloc(sizeof(T) * n)); } /** * Allocate an array with the same dimensions as the specified value. */ template< class T > inline T * alloc(const trace::Value *value) { const trace::Array *array = dynamic_cast<const trace::Array *>(value); if (array) { return alloc<T>(array->size()); } const trace::Null *null = dynamic_cast<const trace::Null *>(value); if (null) { return NULL; } assert(0); return NULL; } /** * Prevent this pointer from being automatically freed. */ template< class T > inline void bind(T *ptr) { if (ptr) { reinterpret_cast<uintptr_t *>(ptr)[-1] |= 1; } } inline ~ScopedAllocator() { while (next) { uintptr_t temp = *reinterpret_cast<uintptr_t *>(next); bool bind = temp & 1; temp &= ~1; if (!bind) { free(reinterpret_cast<void *>(next)); } next = temp; } } }; void addRegion(unsigned long long address, void *buffer, unsigned long long size); void delRegionByPointer(void *ptr); void * toPointer(trace::Value &value, bool bind = false); /** * Output verbosity when retracing files. */ extern int verbosity; /** * Add profiling data to the dump when retracing. */ extern bool profiling; std::ostream &warning(trace::Call &call); void ignore(trace::Call &call); void unsupported(trace::Call &call); typedef void (*Callback)(trace::Call &call); struct Entry { const char *name; Callback callback; }; struct stringComparer { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; extern const Entry stdc_callbacks[]; class Retracer { typedef std::map<const char *, Callback, stringComparer> Map; Map map; std::vector<Callback> callbacks; public: Retracer() { addCallbacks(stdc_callbacks); } virtual ~Retracer() {} void addCallback(const Entry *entry); void addCallbacks(const Entry *entries); void retrace(trace::Call &call); }; } /* namespace retrace */ #endif /* _RETRACE_HPP_ */ <commit_msg>Preserve non-NULL arrays, even when length is zero.<commit_after>/************************************************************************** * * Copyright 2011-2012 Jose Fonseca * All Rights Reserved. * * 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 _RETRACE_HPP_ #define _RETRACE_HPP_ #include <assert.h> #include <string.h> #include <stdint.h> #include <list> #include <map> #include <ostream> #include "trace_model.hpp" #include "trace_parser.hpp" namespace retrace { extern trace::Parser parser; /** * Handle map. * * It is just like a regular std::map<T, T> container, but lookups of missing * keys return the key instead of default constructor. * * This is necessary for several GL named objects, where one can either request * the implementation to generate an unique name, or pick a value never used * before. * * XXX: In some cases, instead of returning the key, it would make more sense * to return an unused data value (e.g., container count). */ template <class T> class map { private: typedef std::map<T, T> base_type; base_type base; public: T & operator[] (const T &key) { typename base_type::iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } const T & operator[] (const T &key) const { typename base_type::const_iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } }; /** * Similar to alloca(), but implemented with malloc. */ class ScopedAllocator { private: uintptr_t next; public: ScopedAllocator() : next(0) { } inline void * alloc(size_t size) { /* Always return valid address, even when size is zero */ size = std::max(size, sizeof(uintptr_t)); uintptr_t * buf = static_cast<uintptr_t *>(malloc(sizeof(uintptr_t) + size)); if (!buf) { return NULL; } *buf = next; next = reinterpret_cast<uintptr_t>(buf); assert((next & 1) == 0); return static_cast<void *>(&buf[1]); } template< class T > inline T * alloc(size_t n = 1) { return static_cast<T *>(alloc(sizeof(T) * n)); } /** * Allocate an array with the same dimensions as the specified value. */ template< class T > inline T * alloc(const trace::Value *value) { const trace::Array *array = dynamic_cast<const trace::Array *>(value); if (array) { return alloc<T>(array->size()); } const trace::Null *null = dynamic_cast<const trace::Null *>(value); if (null) { return NULL; } assert(0); return NULL; } /** * Prevent this pointer from being automatically freed. */ template< class T > inline void bind(T *ptr) { if (ptr) { reinterpret_cast<uintptr_t *>(ptr)[-1] |= 1; } } inline ~ScopedAllocator() { while (next) { uintptr_t temp = *reinterpret_cast<uintptr_t *>(next); bool bind = temp & 1; temp &= ~1; if (!bind) { free(reinterpret_cast<void *>(next)); } next = temp; } } }; void addRegion(unsigned long long address, void *buffer, unsigned long long size); void delRegionByPointer(void *ptr); void * toPointer(trace::Value &value, bool bind = false); /** * Output verbosity when retracing files. */ extern int verbosity; /** * Add profiling data to the dump when retracing. */ extern bool profiling; std::ostream &warning(trace::Call &call); void ignore(trace::Call &call); void unsupported(trace::Call &call); typedef void (*Callback)(trace::Call &call); struct Entry { const char *name; Callback callback; }; struct stringComparer { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; extern const Entry stdc_callbacks[]; class Retracer { typedef std::map<const char *, Callback, stringComparer> Map; Map map; std::vector<Callback> callbacks; public: Retracer() { addCallbacks(stdc_callbacks); } virtual ~Retracer() {} void addCallback(const Entry *entry); void addCallbacks(const Entry *entries); void retrace(trace::Call &call); }; } /* namespace retrace */ #endif /* _RETRACE_HPP_ */ <|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // Copyright (c) Geoff Norton. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: seh-unwind.cpp Abstract: Implementation of exception API functions based on the Unwind API. --*/ #ifndef FEATURE_PAL_SXS #error FEATURE_PAL_SXS needs to be defined for this file. #endif // !FEATURE_PAL_SXS #include "pal/context.h" #include <dlfcn.h> #include <exception> #if HAVE_LIBUNWIND_H #define UNW_LOCAL_ONLY #include <libunwind.h> #endif //---------------------------------------------------------------------- // Virtual Unwinding //---------------------------------------------------------------------- #if HAVE_LIBUNWIND_H #if UNWIND_CONTEXT_IS_UCONTEXT_T static void WinContextToUnwindContext(CONTEXT *winContext, unw_context_t *unwContext) { #if defined(_AMD64_) unwContext->uc_mcontext.gregs[REG_RIP] = winContext->Rip; unwContext->uc_mcontext.gregs[REG_RSP] = winContext->Rsp; unwContext->uc_mcontext.gregs[REG_RBP] = winContext->Rbp; unwContext->uc_mcontext.gregs[REG_RBX] = winContext->Rbx; unwContext->uc_mcontext.gregs[REG_R12] = winContext->R12; unwContext->uc_mcontext.gregs[REG_R13] = winContext->R13; unwContext->uc_mcontext.gregs[REG_R14] = winContext->R14; unwContext->uc_mcontext.gregs[REG_R15] = winContext->R15; #else #error unsupported architecture #endif } #else static void WinContextToUnwindCursor(CONTEXT *winContext, unw_cursor_t *cursor) { #if defined(_AMD64_) unw_set_reg(cursor, UNW_REG_IP, winContext->Rip); unw_set_reg(cursor, UNW_REG_SP, winContext->Rsp); unw_set_reg(cursor, UNW_X86_64_RBP, winContext->Rbp); unw_set_reg(cursor, UNW_X86_64_RBX, winContext->Rbx); unw_set_reg(cursor, UNW_X86_64_R12, winContext->R12); unw_set_reg(cursor, UNW_X86_64_R13, winContext->R13); unw_set_reg(cursor, UNW_X86_64_R14, winContext->R14); unw_set_reg(cursor, UNW_X86_64_R15, winContext->R15); #else #error unsupported architecture #endif } #endif static void UnwindContextToWinContext(unw_cursor_t *cursor, CONTEXT *winContext) { #if defined(_AMD64_) unw_get_reg(cursor, UNW_REG_IP, (unw_word_t *) &winContext->Rip); unw_get_reg(cursor, UNW_REG_SP, (unw_word_t *) &winContext->Rsp); unw_get_reg(cursor, UNW_X86_64_RBP, (unw_word_t *) &winContext->Rbp); unw_get_reg(cursor, UNW_X86_64_RBX, (unw_word_t *) &winContext->Rbx); unw_get_reg(cursor, UNW_X86_64_R12, (unw_word_t *) &winContext->R12); unw_get_reg(cursor, UNW_X86_64_R13, (unw_word_t *) &winContext->R13); unw_get_reg(cursor, UNW_X86_64_R14, (unw_word_t *) &winContext->R14); unw_get_reg(cursor, UNW_X86_64_R15, (unw_word_t *) &winContext->R15); #else #error unsupported architecture #endif } static void GetContextPointer(unw_cursor_t *cursor, int reg, PDWORD64 *contextPointer) { #if defined(__APPLE__) //OSXTODO #else unw_save_loc_t saveLoc; unw_get_save_loc(cursor, reg, &saveLoc); if (saveLoc.type == UNW_SLT_MEMORY) { *contextPointer = (PDWORD64)saveLoc.u.addr; } #endif } static void GetContextPointers(unw_cursor_t *cursor, KNONVOLATILE_CONTEXT_POINTERS *contextPointers) { #if defined(_AMD64_) GetContextPointer(cursor, UNW_X86_64_RBP, &contextPointers->Rbp); GetContextPointer(cursor, UNW_X86_64_RBX, &contextPointers->Rbx); GetContextPointer(cursor, UNW_X86_64_R12, &contextPointers->R12); GetContextPointer(cursor, UNW_X86_64_R13, &contextPointers->R13); GetContextPointer(cursor, UNW_X86_64_R14, &contextPointers->R14); GetContextPointer(cursor, UNW_X86_64_R15, &contextPointers->R15); #else #error unsupported architecture #endif } BOOL PAL_VirtualUnwind(CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *contextPointers) { int st; unw_context_t unwContext; unw_cursor_t cursor; #if UNWIND_CONTEXT_IS_UCONTEXT_T WinContextToUnwindContext(context, &unwContext); #else st = unw_getcontext(&unwContext); if (st < 0) { return FALSE; } #endif st = unw_init_local(&cursor, &unwContext); if (st < 0) { return FALSE; } #if !UNWIND_CONTEXT_IS_UCONTEXT_T // Set the unwind context to the specified windows context WinContextToUnwindCursor(context, &cursor); #endif st = unw_step(&cursor); if (st < 0) { return FALSE; } // Update the passed in windows context to reflect the unwind UnwindContextToWinContext(&cursor, context); if (contextPointers != NULL) { GetContextPointers(&cursor, contextPointers); } return TRUE; } #else #error don't know how to unwind on this platform #endif PAL_NORETURN static void RtlpRaiseException(EXCEPTION_RECORD *ExceptionRecord) { // Capture the context of RtlpRaiseException. CONTEXT ContextRecord; ZeroMemory(&ContextRecord, sizeof(CONTEXT)); ContextRecord.ContextFlags = CONTEXT_FULL; CONTEXT_CaptureContext(&ContextRecord); // Find the caller of RtlpRaiseException. PAL_VirtualUnwind(&ContextRecord, NULL); // The frame we're looking at now is RaiseException. We have to unwind one // level further to get the actual context user code could be resumed at. PAL_VirtualUnwind(&ContextRecord, NULL); #if defined(_X86_) ExceptionRecord->ExceptionAddress = (void *) ContextRecord.Eip; #elif defined(_AMD64_) ExceptionRecord->ExceptionAddress = (void *) ContextRecord.Rip; #else #error unsupported architecture #endif EXCEPTION_POINTERS pointers; pointers.ExceptionRecord = ExceptionRecord; pointers.ContextRecord = &ContextRecord; SEHRaiseException(InternalGetCurrentThread(), &pointers, 0); } PAL_NORETURN void SEHRaiseException(CPalThread *pthrCurrent, PEXCEPTION_POINTERS lpExceptionPointers, int signal_code) { throw PAL_SEHException(lpExceptionPointers->ExceptionRecord, lpExceptionPointers->ContextRecord); } /*++ Function: RaiseException See MSDN doc. --*/ // no PAL_NORETURN, as callers must assume this can return for continuable exceptions. VOID PALAPI RaiseException(IN DWORD dwExceptionCode, IN DWORD dwExceptionFlags, IN DWORD nNumberOfArguments, IN CONST ULONG_PTR *lpArguments) { // PERF_ENTRY_ONLY is used here because RaiseException may or may not // return. We can not get latency data without PERF_EXIT. For this reason, // PERF_ENTRY_ONLY is used to profile frequency only. PERF_ENTRY_ONLY(RaiseException); ENTRY("RaiseException(dwCode=%#x, dwFlags=%#x, nArgs=%u, lpArguments=%p)\n", dwExceptionCode, dwExceptionFlags, nNumberOfArguments, lpArguments); /* Validate parameters */ if (dwExceptionCode & RESERVED_SEH_BIT) { WARN("Exception code %08x has bit 28 set; clearing it.\n", dwExceptionCode); dwExceptionCode ^= RESERVED_SEH_BIT; } if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS) { WARN("Number of arguments (%d) exceeds the limit " "EXCEPTION_MAXIMUM_PARAMETERS (%d); ignoring extra parameters.\n", nNumberOfArguments, EXCEPTION_MAXIMUM_PARAMETERS); nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS; } EXCEPTION_RECORD exceptionRecord; ZeroMemory(&exceptionRecord, sizeof(EXCEPTION_RECORD)); exceptionRecord.ExceptionCode = dwExceptionCode; exceptionRecord.ExceptionFlags = dwExceptionFlags; exceptionRecord.ExceptionRecord = NULL; exceptionRecord.ExceptionAddress = NULL; // will be set by RtlpRaiseException exceptionRecord.NumberParameters = nNumberOfArguments; if (nNumberOfArguments) { CopyMemory(exceptionRecord.ExceptionInformation, lpArguments, nNumberOfArguments * sizeof(ULONG_PTR)); } RtlpRaiseException(&exceptionRecord); LOGEXIT("RaiseException returns\n"); } <commit_msg>Filter out faked save locations returned by libunwind<commit_after>// // Copyright (c) Microsoft. All rights reserved. // Copyright (c) Geoff Norton. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: seh-unwind.cpp Abstract: Implementation of exception API functions based on the Unwind API. --*/ #ifndef FEATURE_PAL_SXS #error FEATURE_PAL_SXS needs to be defined for this file. #endif // !FEATURE_PAL_SXS #include "pal/context.h" #include <dlfcn.h> #include <exception> #if HAVE_LIBUNWIND_H #define UNW_LOCAL_ONLY #include <libunwind.h> #endif //---------------------------------------------------------------------- // Virtual Unwinding //---------------------------------------------------------------------- #if HAVE_LIBUNWIND_H #if UNWIND_CONTEXT_IS_UCONTEXT_T static void WinContextToUnwindContext(CONTEXT *winContext, unw_context_t *unwContext) { #if defined(_AMD64_) unwContext->uc_mcontext.gregs[REG_RIP] = winContext->Rip; unwContext->uc_mcontext.gregs[REG_RSP] = winContext->Rsp; unwContext->uc_mcontext.gregs[REG_RBP] = winContext->Rbp; unwContext->uc_mcontext.gregs[REG_RBX] = winContext->Rbx; unwContext->uc_mcontext.gregs[REG_R12] = winContext->R12; unwContext->uc_mcontext.gregs[REG_R13] = winContext->R13; unwContext->uc_mcontext.gregs[REG_R14] = winContext->R14; unwContext->uc_mcontext.gregs[REG_R15] = winContext->R15; #else #error unsupported architecture #endif } #else static void WinContextToUnwindCursor(CONTEXT *winContext, unw_cursor_t *cursor) { #if defined(_AMD64_) unw_set_reg(cursor, UNW_REG_IP, winContext->Rip); unw_set_reg(cursor, UNW_REG_SP, winContext->Rsp); unw_set_reg(cursor, UNW_X86_64_RBP, winContext->Rbp); unw_set_reg(cursor, UNW_X86_64_RBX, winContext->Rbx); unw_set_reg(cursor, UNW_X86_64_R12, winContext->R12); unw_set_reg(cursor, UNW_X86_64_R13, winContext->R13); unw_set_reg(cursor, UNW_X86_64_R14, winContext->R14); unw_set_reg(cursor, UNW_X86_64_R15, winContext->R15); #else #error unsupported architecture #endif } #endif static void UnwindContextToWinContext(unw_cursor_t *cursor, CONTEXT *winContext) { #if defined(_AMD64_) unw_get_reg(cursor, UNW_REG_IP, (unw_word_t *) &winContext->Rip); unw_get_reg(cursor, UNW_REG_SP, (unw_word_t *) &winContext->Rsp); unw_get_reg(cursor, UNW_X86_64_RBP, (unw_word_t *) &winContext->Rbp); unw_get_reg(cursor, UNW_X86_64_RBX, (unw_word_t *) &winContext->Rbx); unw_get_reg(cursor, UNW_X86_64_R12, (unw_word_t *) &winContext->R12); unw_get_reg(cursor, UNW_X86_64_R13, (unw_word_t *) &winContext->R13); unw_get_reg(cursor, UNW_X86_64_R14, (unw_word_t *) &winContext->R14); unw_get_reg(cursor, UNW_X86_64_R15, (unw_word_t *) &winContext->R15); #else #error unsupported architecture #endif } static void GetContextPointer(unw_cursor_t *cursor, unw_context_t *unwContext, int reg, PDWORD64 *contextPointer) { #if defined(__APPLE__) //OSXTODO #else unw_save_loc_t saveLoc; unw_get_save_loc(cursor, reg, &saveLoc); if (saveLoc.type == UNW_SLT_MEMORY) { PDWORD64 pLoc = (PDWORD64)saveLoc.u.addr; // Filter out fake save locations that point to unwContext if ((pLoc < (PDWORD64)unwContext) || ((PDWORD64)(unwContext + 1) <= pLoc)) *contextPointer = (PDWORD64)saveLoc.u.addr; } #endif } static void GetContextPointers(unw_cursor_t *cursor, unw_context_t *unwContext, KNONVOLATILE_CONTEXT_POINTERS *contextPointers) { #if defined(_AMD64_) GetContextPointer(cursor, unwContext, UNW_X86_64_RBP, &contextPointers->Rbp); GetContextPointer(cursor, unwContext, UNW_X86_64_RBX, &contextPointers->Rbx); GetContextPointer(cursor, unwContext, UNW_X86_64_R12, &contextPointers->R12); GetContextPointer(cursor, unwContext, UNW_X86_64_R13, &contextPointers->R13); GetContextPointer(cursor, unwContext, UNW_X86_64_R14, &contextPointers->R14); GetContextPointer(cursor, unwContext, UNW_X86_64_R15, &contextPointers->R15); #else #error unsupported architecture #endif } BOOL PAL_VirtualUnwind(CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *contextPointers) { int st; unw_context_t unwContext; unw_cursor_t cursor; #if UNWIND_CONTEXT_IS_UCONTEXT_T WinContextToUnwindContext(context, &unwContext); #else st = unw_getcontext(&unwContext); if (st < 0) { return FALSE; } #endif st = unw_init_local(&cursor, &unwContext); if (st < 0) { return FALSE; } #if !UNWIND_CONTEXT_IS_UCONTEXT_T // Set the unwind context to the specified windows context WinContextToUnwindCursor(context, &cursor); #endif st = unw_step(&cursor); if (st < 0) { return FALSE; } // Update the passed in windows context to reflect the unwind UnwindContextToWinContext(&cursor, context); if (contextPointers != NULL) { GetContextPointers(&cursor, &unwContext, contextPointers); } return TRUE; } #else #error don't know how to unwind on this platform #endif PAL_NORETURN static void RtlpRaiseException(EXCEPTION_RECORD *ExceptionRecord) { // Capture the context of RtlpRaiseException. CONTEXT ContextRecord; ZeroMemory(&ContextRecord, sizeof(CONTEXT)); ContextRecord.ContextFlags = CONTEXT_FULL; CONTEXT_CaptureContext(&ContextRecord); // Find the caller of RtlpRaiseException. PAL_VirtualUnwind(&ContextRecord, NULL); // The frame we're looking at now is RaiseException. We have to unwind one // level further to get the actual context user code could be resumed at. PAL_VirtualUnwind(&ContextRecord, NULL); #if defined(_X86_) ExceptionRecord->ExceptionAddress = (void *) ContextRecord.Eip; #elif defined(_AMD64_) ExceptionRecord->ExceptionAddress = (void *) ContextRecord.Rip; #else #error unsupported architecture #endif EXCEPTION_POINTERS pointers; pointers.ExceptionRecord = ExceptionRecord; pointers.ContextRecord = &ContextRecord; SEHRaiseException(InternalGetCurrentThread(), &pointers, 0); } PAL_NORETURN void SEHRaiseException(CPalThread *pthrCurrent, PEXCEPTION_POINTERS lpExceptionPointers, int signal_code) { throw PAL_SEHException(lpExceptionPointers->ExceptionRecord, lpExceptionPointers->ContextRecord); } /*++ Function: RaiseException See MSDN doc. --*/ // no PAL_NORETURN, as callers must assume this can return for continuable exceptions. VOID PALAPI RaiseException(IN DWORD dwExceptionCode, IN DWORD dwExceptionFlags, IN DWORD nNumberOfArguments, IN CONST ULONG_PTR *lpArguments) { // PERF_ENTRY_ONLY is used here because RaiseException may or may not // return. We can not get latency data without PERF_EXIT. For this reason, // PERF_ENTRY_ONLY is used to profile frequency only. PERF_ENTRY_ONLY(RaiseException); ENTRY("RaiseException(dwCode=%#x, dwFlags=%#x, nArgs=%u, lpArguments=%p)\n", dwExceptionCode, dwExceptionFlags, nNumberOfArguments, lpArguments); /* Validate parameters */ if (dwExceptionCode & RESERVED_SEH_BIT) { WARN("Exception code %08x has bit 28 set; clearing it.\n", dwExceptionCode); dwExceptionCode ^= RESERVED_SEH_BIT; } if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS) { WARN("Number of arguments (%d) exceeds the limit " "EXCEPTION_MAXIMUM_PARAMETERS (%d); ignoring extra parameters.\n", nNumberOfArguments, EXCEPTION_MAXIMUM_PARAMETERS); nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS; } EXCEPTION_RECORD exceptionRecord; ZeroMemory(&exceptionRecord, sizeof(EXCEPTION_RECORD)); exceptionRecord.ExceptionCode = dwExceptionCode; exceptionRecord.ExceptionFlags = dwExceptionFlags; exceptionRecord.ExceptionRecord = NULL; exceptionRecord.ExceptionAddress = NULL; // will be set by RtlpRaiseException exceptionRecord.NumberParameters = nNumberOfArguments; if (nNumberOfArguments) { CopyMemory(exceptionRecord.ExceptionInformation, lpArguments, nNumberOfArguments * sizeof(ULONG_PTR)); } RtlpRaiseException(&exceptionRecord); LOGEXIT("RaiseException returns\n"); } <|endoftext|>
<commit_before>// // Copyright 2013 Jeff Bush // // 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 "output.h" volatile int foo = 0x5a5a5a5a; Output output; int main() { output << __sync_fetch_and_add(&foo, 1); // CHECK: 0x5a5a5a5a output << __sync_add_and_fetch(&foo, 1); // CHECK: 0x5a5a5a5c output << __sync_add_and_fetch(&foo, 1); // CHECK: 0x5a5a5a5d output << __sync_fetch_and_add(&foo, 1); // CHECK: 0x5a5a5a5d // Large constants. Ensure all operations generate proper code (which must // load from constant pool) output << __sync_add_and_fetch(&foo, 0x10000000); // CHECK: 0x6a5a5a5e output << __sync_sub_and_fetch(&foo, 0x20000000); // CHECK: 0x4a5a5a5e output << __sync_and_and_fetch(&foo, 0xf0ffffff); // CHECK: 0x405a5a5e output << __sync_or_and_fetch(&foo, 0x0f000000); // CHECK: 0x4f5a5a5e output << __sync_xor_and_fetch(&foo, 0x05000000); // CHECK: 0x4a5a5a5e // Small constants. These will generate immediate instructions. Test for all forms. output << __sync_sub_and_fetch(&foo, 1); // CHECK: 0x4a5a5a5d output << __sync_and_and_fetch(&foo, 1); // CHECK: 0x00000001 output << __sync_or_and_fetch(&foo, 2); // CHECK: 0x00000003 output << __sync_xor_and_fetch(&foo, 1); // CHECK: 0x00000002 // Compare and swap foo = 2; output << __sync_val_compare_and_swap(&foo, 2, 3); // CHECK: 0x00000002 output << __sync_val_compare_and_swap(&foo, 2, 4); // CHECK: 0x00000003 output << __sync_bool_compare_and_swap(&foo, 2, 10); // CHECK: 0x00000000 output << __sync_bool_compare_and_swap(&foo, 3, 10); // CHECK: 0x00000001 return 0; } <commit_msg>Add a few more checks for compare and swap tests<commit_after>// // Copyright 2013 Jeff Bush // // 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 "output.h" volatile int foo = 0x5a5a5a5a; Output output; int main() { output << __sync_fetch_and_add(&foo, 1); // CHECK: 0x5a5a5a5a output << __sync_add_and_fetch(&foo, 1); // CHECK: 0x5a5a5a5c output << __sync_add_and_fetch(&foo, 1); // CHECK: 0x5a5a5a5d output << __sync_fetch_and_add(&foo, 1); // CHECK: 0x5a5a5a5d // Large constants. Ensure all operations generate proper code (which must // load from constant pool) output << __sync_add_and_fetch(&foo, 0x10000000); // CHECK: 0x6a5a5a5e output << __sync_sub_and_fetch(&foo, 0x20000000); // CHECK: 0x4a5a5a5e output << __sync_and_and_fetch(&foo, 0xf0ffffff); // CHECK: 0x405a5a5e output << __sync_or_and_fetch(&foo, 0x0f000000); // CHECK: 0x4f5a5a5e output << __sync_xor_and_fetch(&foo, 0x05000000); // CHECK: 0x4a5a5a5e // Small constants. These will generate immediate instructions. Test for all forms. output << __sync_sub_and_fetch(&foo, 1); // CHECK: 0x4a5a5a5d output << __sync_and_and_fetch(&foo, 1); // CHECK: 0x00000001 output << __sync_or_and_fetch(&foo, 2); // CHECK: 0x00000003 output << __sync_xor_and_fetch(&foo, 1); // CHECK: 0x00000002 // Compare and swap foo = 2; // successful output << __sync_val_compare_and_swap(&foo, 2, 3); // CHECK: 0x00000002 output << foo; // CHECK: 0x00000003 // not successful output << __sync_val_compare_and_swap(&foo, 2, 4); // CHECK: 0x00000003 output << foo; // CHECK: 0x00000003 // not successful output << __sync_bool_compare_and_swap(&foo, 2, 10); // CHECK: 0x00000000 output << foo; // CHECK: 0x00000003 // successful output << __sync_bool_compare_and_swap(&foo, 3, 10); // CHECK: 0x00000001 output << foo; // CHECK: 0x0000000a return 0; } <|endoftext|>
<commit_before>// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -config="{CheckOptions: [{key: "cppcoreguidelines-pro-type-member-init.UseAssignment", value: 1}]}" -- -std=c++11 struct T { int i; }; struct S { bool b; // CHECK-FIXES: bool b = false; char c; // CHECK-FIXES: char c = 0; signed char sc; // CHECK-FIXES: signed char sc = 0; unsigned char uc; // CHECK-FIXES: unsigned char uc = 0U; int i; // CHECK-FIXES: int i = 0; unsigned u; // CHECK-FIXES: unsigned u = 0U; long l; // CHECK-FIXES: long l = 0L; unsigned long ul; // CHECK-FIXES: unsigned long ul = 0UL; long long ll; // CHECK-FIXES: long long ll = 0LL; unsigned long long ull; // CHECK-FIXES: unsigned long long ull = 0ULL; float f; // CHECK-FIXES: float f = 0.0F; double d; // CHECK-FIXES: double d = 0.0; long double ld; // CHECK-FIXES: double ld = 0.0L; int *ptr; // CHECK-FIXES: int *ptr = nullptr; T t; // CHECK-FIXES: T t{}; S() {} // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: }; <commit_msg>Made cppcoreguidelines-pro-type-member-init-use-assignment run in all language modes<commit_after>// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -config="{CheckOptions: [{key: "cppcoreguidelines-pro-type-member-init.UseAssignment", value: 1}]}" struct T { int i; }; struct S { bool b; // CHECK-FIXES: bool b = false; char c; // CHECK-FIXES: char c = 0; signed char sc; // CHECK-FIXES: signed char sc = 0; unsigned char uc; // CHECK-FIXES: unsigned char uc = 0U; int i; // CHECK-FIXES: int i = 0; unsigned u; // CHECK-FIXES: unsigned u = 0U; long l; // CHECK-FIXES: long l = 0L; unsigned long ul; // CHECK-FIXES: unsigned long ul = 0UL; long long ll; // CHECK-FIXES: long long ll = 0LL; unsigned long long ull; // CHECK-FIXES: unsigned long long ull = 0ULL; float f; // CHECK-FIXES: float f = 0.0F; double d; // CHECK-FIXES: double d = 0.0; long double ld; // CHECK-FIXES: double ld = 0.0L; int *ptr; // CHECK-FIXES: int *ptr = nullptr; T t; // CHECK-FIXES: T t{}; S() {} // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: }; <|endoftext|>
<commit_before>// compilation on OSX // $ g++ -std=c++11 main.cpp -o main #include <iostream> #include <fstream> #include <vector> #include <map> #include <cmath> #include <future> typedef std::string GameTitle; typedef int GameTime; typedef std::vector<GameTime> GameTimes; typedef std::map<GameTitle, GameTimes> GameMap; typedef std::pair<int, double> StatPair; typedef std::map<GameTitle, std::future<StatPair>> GameStat; int sum(const GameTimes& gameplays) { int result = 0; for (int n : gameplays) result += n; return result; } double avg(const GameTimes& gameplays) { return std::floor(sum(gameplays) / gameplays.size()); } StatPair processGame(const GameTimes& gameplays) { return std::make_pair(sum(gameplays), avg(gameplays)); } GameMap readFile(const std::string filename) { std::ifstream input(filename); unsigned int lineCount, gameCount; GameMap games; GameTitle title; GameTime seconds; std::string temp; input >> lineCount >> gameCount; for (int i = 0; i < lineCount; i++) { input >> temp >> title >> seconds; if (!games.count(title)) games[title]; games[title].push_back(seconds); } input.close(); return games; } void writeFile(const std::string filename, GameStat& results) { std::ofstream output(filename); for (auto& result : results) { GameTitle title = result.first; StatPair stat = result.second.get(); output << title << " " << stat.first << " " << stat.second << std::endl; } output.close(); } int main() { GameMap games = readFile("./tests/input_1.txt"); // Calculating sum and avg for every game GameStat results; for (auto const & game : games) { results.insert(std::make_pair(game.first, std::async(std::launch::async, processGame, game.second))); } writeFile("output.txt", results); return 0; } <commit_msg>bead1 refactor<commit_after>// compilation on OSX // $ g++ -std=c++11 main.cpp -o main #include <iostream> #include <fstream> #include <vector> #include <map> #include <cmath> #include <future> typedef std::string GameTitle; typedef int GameTime; typedef std::vector<GameTime> GameTimes; typedef std::map<GameTitle, GameTimes> GameMap; typedef std::pair<int, double> StatPair; typedef std::map<GameTitle, std::future<StatPair>> GameStat; int sum(const GameTimes& gameplays) { int result = 0; for (int n : gameplays) result += n; return result; } double avg(const GameTimes& gameplays) { return std::floor(sum(gameplays) / gameplays.size()); } StatPair calculateGameStats(const GameTimes& gameplays) { return std::make_pair(sum(gameplays), avg(gameplays)); } GameMap readFile(const std::string filename) { std::ifstream input(filename); unsigned int lineCount, gameCount; GameMap games; GameTitle title; GameTime seconds; std::string temp; input >> lineCount >> gameCount; for (int i = 0; i < lineCount; i++) { input >> temp >> title >> seconds; if (!games.count(title)) games[title]; games[title].push_back(seconds); } input.close(); return games; } void writeFile(const std::string filename, GameStat& results) { std::ofstream output(filename); for (auto& result : results) { GameTitle title = result.first; StatPair stat = result.second.get(); output << title << " " << stat.first << " " << stat.second << std::endl; } output.close(); } int main() { GameMap games = readFile("input.txt"); // Calculating sum and avg for every game GameStat results; for (auto const & game : games) { results.insert(std::make_pair(game.first, std::async(std::launch::async, calculateGameStats, game.second))); } writeFile("output.txt", results); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** Copyright 2015 Tatsuya Yatagawa (tatsy) 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 "gtest/gtest.h" #include "../../include/lime.hpp" using lime::Point2d; const int nSimpleLoop = 100; lime::Random rng = lime::Random::getRNG(); TEST(Point2d, DefaultConstructor) { const Point2d p; EXPECT_EQ(p.x, 0.0); EXPECT_EQ(p.y, 0.0); } TEST(Point2d, AddAndSubtract) { for (int i = 0; i < nSimpleLoop; i++) { const Point2d p(rng.randReal(), rng.randReal()); const Point2d q(rng.randReal(), rng.randReal()); EXPECT_EQ(p.x + q.x, (p + q).x) << "Add: x does not match"; EXPECT_EQ(p.y + q.y, (p + q).y) << "Add: y does not match"; EXPECT_EQ(p.x - q.x, (p - q).x) << "Subtract: x does not match"; EXPECT_EQ(p.y - q.y, (p - q).y) << "Subtract: x does not match"; } } TEST(Point2d, MultiplyAndDiv) { for (int i = 0; i < nSimpleLoop; i++) { const Point2d p(rng.randReal(), rng.randReal()); const double d = rng.randReal() + 1.0e-8; EXPECT_EQ(p.x * d, (p * d).x) << "Multiply: x does not match"; EXPECT_EQ(p.y * d, (p * d).y) << "Multiply: y does not match"; EXPECT_EQ(p.x / d, (p / d).x) << "Divide: x does not match"; EXPECT_EQ(p.y / d, (p / d).y) << "Divide: y does not match"; } Point2d p(1.0, 2.0); ASSERT_DEATH(p / 0.0, "Zero division") << "Divide: zero division"; } TEST(Point2d, Norm) { for (int i = 0; i < nSimpleLoop; i++) { double dx = rng.randReal(); double dy = rng.randReal(); const Point2d p(dx, dy); EXPECT_EQ(p.norm(), sqrt(dx * dx + dy * dy)) << "Norm: value does not match"; } } TEST(Point2d, Normalize) { for (int i = 0; i < nSimpleLoop; i++) { double dx = rng.randReal(); double dy = rng.randReal(); const Point2d p(dx, dy); double norm = p.norm(); EXPECT_EQ(p.normalize().x, dx / norm) << "Normalize: x does not match"; EXPECT_EQ(p.normalize().y, dy / norm) << "Normalize: y does not match"; } const Point2d p(0.0, 0.0); ASSERT_DEATH(p.normalize(), "Zero division") << "Normalize: zero division"; } TEST(Point2d, DotAndDet) { for (int i = 0; i < nSimpleLoop; i++) { double dx1 = rng.randReal(); double dy1 = rng.randReal(); double dx2 = rng.randReal(); double dy2 = rng.randReal(); const Point2d p1(dx1, dy1); const Point2d p2(dx2, dy2); EXPECT_EQ(p1.dot(p2), dx1 * dx2 + dy1 * dy2) << "Dot: value does not match"; EXPECT_EQ(p1.det(p2), dx1 * dy2 - dx2 * dy1) << "Det: value does not match"; } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fix unit tests for Point2d::norm()<commit_after>/****************************************************************************** Copyright 2015 Tatsuya Yatagawa (tatsy) 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 "gtest/gtest.h" #include "../../include/lime.hpp" using lime::Point2d; const int nSimpleLoop = 100; lime::Random rng = lime::Random::getRNG(); TEST(Point2d, DefaultConstructor) { const Point2d p; EXPECT_EQ(p.x, 0.0); EXPECT_EQ(p.y, 0.0); } TEST(Point2d, AddAndSubtract) { for (int i = 0; i < nSimpleLoop; i++) { const Point2d p(rng.randReal(), rng.randReal()); const Point2d q(rng.randReal(), rng.randReal()); EXPECT_EQ(p.x + q.x, (p + q).x) << "Add: x does not match"; EXPECT_EQ(p.y + q.y, (p + q).y) << "Add: y does not match"; EXPECT_EQ(p.x - q.x, (p - q).x) << "Subtract: x does not match"; EXPECT_EQ(p.y - q.y, (p - q).y) << "Subtract: x does not match"; } } TEST(Point2d, MultiplyAndDiv) { for (int i = 0; i < nSimpleLoop; i++) { const Point2d p(rng.randReal(), rng.randReal()); const double d = rng.randReal() + 1.0e-8; EXPECT_EQ(p.x * d, (p * d).x) << "Multiply: x does not match"; EXPECT_EQ(p.y * d, (p * d).y) << "Multiply: y does not match"; EXPECT_EQ(p.x / d, (p / d).x) << "Divide: x does not match"; EXPECT_EQ(p.y / d, (p / d).y) << "Divide: y does not match"; } Point2d p(1.0, 2.0); ASSERT_DEATH(p / 0.0, "Zero division") << "Divide: zero division"; } TEST(Point2d, Norm) { for (int i = 0; i < nSimpleLoop; i++) { double dx = rng.randReal(); double dy = rng.randReal(); const Point2d p(dx, dy); EXPECT_EQ(p.norm(), hypot(dx, dy)) << "Norm: value does not match"; } } TEST(Point2d, Normalize) { for (int i = 0; i < nSimpleLoop; i++) { double dx = rng.randReal(); double dy = rng.randReal(); const Point2d p(dx, dy); double norm = p.norm(); EXPECT_EQ(p.normalize().x, dx / norm) << "Normalize: x does not match"; EXPECT_EQ(p.normalize().y, dy / norm) << "Normalize: y does not match"; } const Point2d p(0.0, 0.0); ASSERT_DEATH(p.normalize(), "Zero division") << "Normalize: zero division"; } TEST(Point2d, DotAndDet) { for (int i = 0; i < nSimpleLoop; i++) { double dx1 = rng.randReal(); double dy1 = rng.randReal(); double dx2 = rng.randReal(); double dy2 = rng.randReal(); const Point2d p1(dx1, dy1); const Point2d p2(dx2, dy2); EXPECT_EQ(p1.dot(p2), dx1 * dx2 + dy1 * dy2) << "Dot: value does not match"; EXPECT_EQ(p1.det(p2), dx1 * dy2 - dx2 * dy1) << "Det: value does not match"; } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // cpp-compile-test.cc // Just check whether (most of) the sokol headers also comppile as C++. //------------------------------------------------------------------------------ #define SOKOL_IMPL #define SOKOL_WIN32_FORCE_MAIN #ifdef _MSC_VER #pragma warning(disable:4702) /* unreachable code */ /* don't complain about unused variables in MSVC at /W4 when assert() is a NOP */ #if defined(NDEBUG) #define SOKOL_ASSERT(x) ((void)(x)) #endif #endif #include "sokol_app.h" #include "sokol_args.h" #include "sokol_audio.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "sokol_fetch.h" #define SOKOL_GL_IMPL #include "sokol_gl.h" #define SOKOL_DEBUGTEXT_IMPL #include "sokol_debugtext.h" #include "imgui.h" #define SOKOL_IMGUI_IMPL #include "sokol_imgui.h" #define SOKOL_GFX_IMGUI_IMPL #include "sokol_gfx_imgui.h" #define FONTSTASH_IMPLEMENTATION #if defined(_MSC_VER ) #pragma warning(disable:4996) // strncpy use in fontstash.h #endif #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" #endif #include "fontstash/fontstash.h" #define SOKOL_FONTSTASH_IMPL #include "sokol_fontstash.h" static sapp_desc desc; sapp_desc sokol_main(int /*argc*/, char* /*argv*/[]) { /* just interested whether the compilation worked, so force-exit here */ exit(0); return desc; } <commit_msg>fix MSVC C++ warnings<commit_after>//------------------------------------------------------------------------------ // cpp-compile-test.cc // Just check whether (most of) the sokol headers also comppile as C++. //------------------------------------------------------------------------------ #define SOKOL_IMPL #define SOKOL_WIN32_FORCE_MAIN #ifdef _MSC_VER #pragma warning(disable:4702) /* unreachable code */ #pragma warning(disable:4505) /* unreferenced local function has been removed */ /* don't complain about unused variables in MSVC at /W4 when assert() is a NOP */ #if defined(NDEBUG) #define SOKOL_ASSERT(x) ((void)(x)) #endif #endif #include "sokol_app.h" #include "sokol_args.h" #include "sokol_audio.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "sokol_fetch.h" #define SOKOL_GL_IMPL #include "sokol_gl.h" #define SOKOL_DEBUGTEXT_IMPL #include "sokol_debugtext.h" #include "imgui.h" #define SOKOL_IMGUI_IMPL #include "sokol_imgui.h" #define SOKOL_GFX_IMGUI_IMPL #include "sokol_gfx_imgui.h" #define FONTSTASH_IMPLEMENTATION #if defined(_MSC_VER ) #pragma warning(disable:4996) // strncpy use in fontstash.h #endif #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" #endif #include "fontstash/fontstash.h" #define SOKOL_FONTSTASH_IMPL #include "sokol_fontstash.h" static sapp_desc desc; sapp_desc sokol_main(int /*argc*/, char* /*argv*/[]) { /* just interested whether the compilation worked, so force-exit here */ exit(0); return desc; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DELETER_HH_ #define DELETER_HH_ struct deleter { std::unique_ptr<deleter> next; deleter(std::unique_ptr<deleter> next) : next(std::move(next)) {} virtual ~deleter() {}; }; struct internal_deleter final : deleter { // FIXME: make buf an std::array<>? char* buf; unsigned free_head; internal_deleter(std::unique_ptr<deleter> next, char* buf, unsigned free_head) : deleter(std::move(next)), buf(buf), free_head(free_head) {} explicit internal_deleter(std::unique_ptr<deleter> next, size_t internal_data_size) : internal_deleter(std::move(next), new char[internal_data_size], internal_data_size) {} virtual ~internal_deleter() override { delete[] buf; } }; template <typename Deleter> struct lambda_deleter final : deleter { Deleter del; lambda_deleter(std::unique_ptr<deleter> next, Deleter&& del) : deleter(std::move(next)), del(std::move(del)) {} virtual ~lambda_deleter() override { del(); } }; template <typename Deleter> std::unique_ptr<deleter> make_deleter(std::unique_ptr<deleter> next, Deleter d) { return std::unique_ptr<deleter>(new lambda_deleter<Deleter>(std::move(next), std::move(d))); } struct shared_deleter : deleter { long* _count; deleter* _deleter; shared_deleter(std::unique_ptr<deleter> d) : deleter(nullptr), _count(new long(1)), _deleter(d.release()) {} shared_deleter(const shared_deleter& x) : deleter(nullptr), _count(x._count), _deleter(x._deleter) { if (_count) { ++*_count; } } shared_deleter(shared_deleter&& x) : deleter(nullptr), _count(x._count), _deleter(x._deleter) { x._count = nullptr; x._deleter = nullptr; } void operator=(const shared_deleter&) = delete; void operator=(shared_deleter&&) = delete; virtual ~shared_deleter() { if (_count && --*_count == 0) { delete _deleter; delete _count; } } bool owned() const { return *_count == 1; } }; #endif /* DELETER_HH_ */ <commit_msg>core: add a share() helper for deleter class<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DELETER_HH_ #define DELETER_HH_ struct deleter { std::unique_ptr<deleter> next; deleter(std::unique_ptr<deleter> next) : next(std::move(next)) {} virtual ~deleter() {}; }; struct internal_deleter final : deleter { // FIXME: make buf an std::array<>? char* buf; unsigned free_head; internal_deleter(std::unique_ptr<deleter> next, char* buf, unsigned free_head) : deleter(std::move(next)), buf(buf), free_head(free_head) {} explicit internal_deleter(std::unique_ptr<deleter> next, size_t internal_data_size) : internal_deleter(std::move(next), new char[internal_data_size], internal_data_size) {} virtual ~internal_deleter() override { delete[] buf; } }; template <typename Deleter> struct lambda_deleter final : deleter { Deleter del; lambda_deleter(std::unique_ptr<deleter> next, Deleter&& del) : deleter(std::move(next)), del(std::move(del)) {} virtual ~lambda_deleter() override { del(); } }; template <typename Deleter> std::unique_ptr<deleter> make_deleter(std::unique_ptr<deleter> next, Deleter d) { return std::unique_ptr<deleter>(new lambda_deleter<Deleter>(std::move(next), std::move(d))); } struct shared_deleter : deleter { long* _count; deleter* _deleter; shared_deleter(std::unique_ptr<deleter> d) : deleter(nullptr), _count(new long(1)), _deleter(d.release()) {} shared_deleter(const shared_deleter& x) : deleter(nullptr), _count(x._count), _deleter(x._deleter) { if (_count) { ++*_count; } } shared_deleter(shared_deleter&& x) : deleter(nullptr), _count(x._count), _deleter(x._deleter) { x._count = nullptr; x._deleter = nullptr; } void operator=(const shared_deleter&) = delete; void operator=(shared_deleter&&) = delete; virtual ~shared_deleter() { if (_count && --*_count == 0) { delete _deleter; delete _count; } } bool owned() const { return *_count == 1; } }; inline std::unique_ptr<deleter> share(std::unique_ptr<deleter>& d) { auto sd = dynamic_cast<shared_deleter*>(d.get()); if (!sd) { sd = new shared_deleter(std::move(d)); d.reset(sd); } return std::unique_ptr<deleter>(new shared_deleter(*sd)); } #endif /* DELETER_HH_ */ <|endoftext|>
<commit_before>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "berryHelpContentView.h" #include "berryHelpPluginActivator.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpWebView.h" #include "berryQHelpEngineWrapper.h" #include <berryIWorkbenchPage.h> #include <QSortFilterProxyModel> #include <QHelpContentWidget> #include <QLayout> #include <QMenu> #include <QHeaderView> #include <QDir> namespace berry { HelpContentWidget::HelpContentWidget() : QTreeView(0) , m_SortModel(new QSortFilterProxyModel(this)) , m_SourceModel(0) { header()->hide(); setUniformRowHeights(true); connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(showLink(QModelIndex))); m_SortModel->setDynamicSortFilter(true); QTreeView::setModel(m_SortModel); } QModelIndex HelpContentWidget::indexOf(const QUrl &link) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel || link.scheme() != QLatin1String("qthelp")) return QModelIndex(); m_syncIndex = QModelIndex(); for (int i=0; i<contentModel->rowCount(); ++i) { QHelpContentItem *itm = contentModel->contentItemAt(contentModel->index(i, 0)); if (itm && itm->url().host() == link.host()) { QString path = link.path(); if (path.startsWith(QLatin1Char('/'))) path = path.mid(1); if (searchContentItem(contentModel, contentModel->index(i, 0), path)) { return m_syncIndex; } } } return QModelIndex(); } void HelpContentWidget::setModel(QAbstractItemModel *model) { m_SourceModel = model; m_SortModel->setSourceModel(model); } bool HelpContentWidget::searchContentItem(QHelpContentModel *model, const QModelIndex &parent, const QString &path) { QHelpContentItem *parentItem = model->contentItemAt(parent); if (!parentItem) return false; if (QDir::cleanPath(parentItem->url().path()) == path) { m_syncIndex = m_SortModel->mapFromSource(parent); return true; } for (int i=0; i<parentItem->childCount(); ++i) { if (searchContentItem(model, model->index(i, 0, parent), path)) return true; } return false; } QUrl HelpContentWidget::GetUrl(const QModelIndex &index) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel) return 0; QHelpContentItem *item = contentModel->contentItemAt(m_SortModel->mapToSource(index)); if (!item) return 0; QUrl url = item->url(); if (url.isValid()) return url; return 0; } void HelpContentWidget::showLink(const QModelIndex &index) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel) return; QHelpContentItem *item = contentModel->contentItemAt(m_SortModel->mapToSource(index)); if (!item) return; QUrl url = item->url(); if (url.isValid()) emit linkActivated(url); } HelpContentView::HelpContentView() : m_ContentWidget(0) { } HelpContentView::~HelpContentView() { } void HelpContentView::CreateQtPartControl(QWidget* parent) { if (m_ContentWidget == 0) { QVBoxLayout* verticalLayout = new QVBoxLayout(parent); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(0, 0, 0, 0); QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); m_ContentWidget = new HelpContentWidget(); m_ContentWidget->setModel(helpEngine.contentModel()); m_ContentWidget->sortByColumn(0, Qt::AscendingOrder); connect(helpEngine.contentModel(), SIGNAL(contentsCreationStarted()), this, SLOT(setContentsWidgetBusy())); connect(helpEngine.contentModel(), SIGNAL(contentsCreated()), this, SLOT(unsetContentsWidgetBusy())); verticalLayout->addWidget(m_ContentWidget); m_ContentWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_ContentWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); connect(m_ContentWidget, SIGNAL(linkActivated(QUrl)), this, SLOT(linkActivated(QUrl))); } } void HelpContentView::linkActivated(const QUrl &link) { IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); HelpPluginActivator::linkActivated(page, link); } void HelpContentView::showContextMenu(const QPoint &pos) { if (!m_ContentWidget->indexAt(pos).isValid()) return; QModelIndex index = m_ContentWidget->indexAt(pos); QUrl url = m_ContentWidget->GetUrl(index); QMenu menu; QAction *curTab = menu.addAction(tr("Open Link")); QAction *newTab = menu.addAction(tr("Open Link in New Tab")); if (!HelpWebView::canOpenPage(url.path())) newTab->setEnabled(false); menu.move(m_ContentWidget->mapToGlobal(pos)); QAction *action = menu.exec(); if (curTab == action) { linkActivated(url); } else if (newTab == action) { IEditorInput::Pointer input(new HelpEditorInput(url)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } } void HelpContentView::SetFocus() { m_ContentWidget->setFocus(); } void HelpContentView::setContentsWidgetBusy() { m_ContentWidget->setCursor(Qt::WaitCursor); } void HelpContentView::unsetContentsWidgetBusy() { m_ContentWidget->unsetCursor(); } } <commit_msg>COMP: Removed non-standard-code<commit_after>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "berryHelpContentView.h" #include "berryHelpPluginActivator.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpWebView.h" #include "berryQHelpEngineWrapper.h" #include <berryIWorkbenchPage.h> #include <QSortFilterProxyModel> #include <QHelpContentWidget> #include <QLayout> #include <QMenu> #include <QHeaderView> #include <QDir> namespace berry { HelpContentWidget::HelpContentWidget() : QTreeView(0) , m_SortModel(new QSortFilterProxyModel(this)) , m_SourceModel(0) { header()->hide(); setUniformRowHeights(true); connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(showLink(QModelIndex))); m_SortModel->setDynamicSortFilter(true); QTreeView::setModel(m_SortModel); } QModelIndex HelpContentWidget::indexOf(const QUrl &link) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel || link.scheme() != QLatin1String("qthelp")) return QModelIndex(); m_syncIndex = QModelIndex(); for (int i=0; i<contentModel->rowCount(); ++i) { QHelpContentItem *itm = contentModel->contentItemAt(contentModel->index(i, 0)); if (itm && itm->url().host() == link.host()) { QString path = link.path(); if (path.startsWith(QLatin1Char('/'))) path = path.mid(1); if (searchContentItem(contentModel, contentModel->index(i, 0), path)) { return m_syncIndex; } } } return QModelIndex(); } void HelpContentWidget::setModel(QAbstractItemModel *model) { m_SourceModel = model; m_SortModel->setSourceModel(model); } bool HelpContentWidget::searchContentItem(QHelpContentModel *model, const QModelIndex &parent, const QString &path) { QHelpContentItem *parentItem = model->contentItemAt(parent); if (!parentItem) return false; if (QDir::cleanPath(parentItem->url().path()) == path) { m_syncIndex = m_SortModel->mapFromSource(parent); return true; } for (int i=0; i<parentItem->childCount(); ++i) { if (searchContentItem(model, model->index(i, 0, parent), path)) return true; } return false; } QUrl HelpContentWidget::GetUrl(const QModelIndex &index) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel) return QUrl(); QHelpContentItem *item = contentModel->contentItemAt(m_SortModel->mapToSource(index)); if (!item) return QUrl(); QUrl url = item->url(); if (url.isValid()) return url; return QUrl(); } void HelpContentWidget::showLink(const QModelIndex &index) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_SourceModel); if (!contentModel) return; QHelpContentItem *item = contentModel->contentItemAt(m_SortModel->mapToSource(index)); if (!item) return; QUrl url = item->url(); if (url.isValid()) emit linkActivated(url); } HelpContentView::HelpContentView() : m_ContentWidget(0) { } HelpContentView::~HelpContentView() { } void HelpContentView::CreateQtPartControl(QWidget* parent) { if (m_ContentWidget == 0) { QVBoxLayout* verticalLayout = new QVBoxLayout(parent); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(0, 0, 0, 0); QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); m_ContentWidget = new HelpContentWidget(); m_ContentWidget->setModel(helpEngine.contentModel()); m_ContentWidget->sortByColumn(0, Qt::AscendingOrder); connect(helpEngine.contentModel(), SIGNAL(contentsCreationStarted()), this, SLOT(setContentsWidgetBusy())); connect(helpEngine.contentModel(), SIGNAL(contentsCreated()), this, SLOT(unsetContentsWidgetBusy())); verticalLayout->addWidget(m_ContentWidget); m_ContentWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_ContentWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); connect(m_ContentWidget, SIGNAL(linkActivated(QUrl)), this, SLOT(linkActivated(QUrl))); } } void HelpContentView::linkActivated(const QUrl &link) { IWorkbenchPage::Pointer page = this->GetSite()->GetPage(); HelpPluginActivator::linkActivated(page, link); } void HelpContentView::showContextMenu(const QPoint &pos) { if (!m_ContentWidget->indexAt(pos).isValid()) return; QModelIndex index = m_ContentWidget->indexAt(pos); QUrl url = m_ContentWidget->GetUrl(index); QMenu menu; QAction *curTab = menu.addAction(tr("Open Link")); QAction *newTab = menu.addAction(tr("Open Link in New Tab")); if (!HelpWebView::canOpenPage(url.path())) newTab->setEnabled(false); menu.move(m_ContentWidget->mapToGlobal(pos)); QAction *action = menu.exec(); if (curTab == action) { linkActivated(url); } else if (newTab == action) { IEditorInput::Pointer input(new HelpEditorInput(url)); this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); } } void HelpContentView::SetFocus() { m_ContentWidget->setFocus(); } void HelpContentView::setContentsWidgetBusy() { m_ContentWidget->setCursor(Qt::WaitCursor); } void HelpContentView::unsetContentsWidgetBusy() { m_ContentWidget->unsetCursor(); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtTest/QSignalSpy> #include <QtDeclarative/qdeclarativeengine.h> #include <QtDeclarative/qdeclarativecomponent.h> #include <QtDeclarative/qdeclarativecontext.h> #include <QtQuick/private/qdeclarativefontloader_p.h> #include "../../shared/util.h" #include "../../shared/testhttpserver.h" #include <QtQuick/QQuickView> #include <QtQuick/QQuickItem> #define SERVER_PORT 14448 class tst_qdeclarativefontloader : public QDeclarativeDataTest { Q_OBJECT public: tst_qdeclarativefontloader(); private slots: void initTestCase(); void noFont(); void namedFont(); void localFont(); void failLocalFont(); void webFont(); void redirWebFont(); void failWebFont(); void changeFont(); void changeFontSourceViaState(); private: QDeclarativeEngine engine; TestHTTPServer server; }; tst_qdeclarativefontloader::tst_qdeclarativefontloader() : server(SERVER_PORT) { } void tst_qdeclarativefontloader::initTestCase() { QDeclarativeDataTest::initTestCase(); server.serveDirectory(dataDirectory()); QVERIFY(server.isValid()); } void tst_qdeclarativefontloader::noFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("")); QCOMPARE(fontObject->source(), QUrl("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Null); delete fontObject; } void tst_qdeclarativefontloader::namedFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { name: \"Helvetica\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->source(), QUrl("")); QCOMPARE(fontObject->name(), QString("Helvetica")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::localFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"" + testFile("tarzeau_ocr_a.ttf") + "\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::failLocalFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"" + testFileUrl("dummy.ttf").toString() + "\" }"; QTest::ignoreMessage(QtWarningMsg, QString("file::2:1: QML FontLoader: Cannot load font: \"" + testFileUrl("dummy.ttf").toString() + "\"").toUtf8().constData()); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Error); } void tst_qdeclarativefontloader::webFont() { #ifdef Q_OS_MAC QSKIP("QTBUG-23477"); #endif QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/tarzeau_ocr_a.ttf\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::redirWebFont() { #ifdef Q_OS_MAC QSKIP("QTBUG-23477"); #endif server.addRedirect("olddir/oldname.ttf","../tarzeau_ocr_a.ttf"); QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/olddir/oldname.ttf\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::failWebFont() { #ifdef Q_OS_MAC QSKIP("QTBUG-23477"); #endif QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/nonexist.ttf\" }"; QTest::ignoreMessage(QtWarningMsg, "file::2:1: QML FontLoader: Cannot load font: \"http://localhost:14448/nonexist.ttf\""); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Error); } void tst_qdeclarativefontloader::changeFont() { #ifdef Q_OS_MAC QSKIP("QTBUG-23477"); #endif QString componentStr = "import QtQuick 2.0\nFontLoader { source: font }"; QDeclarativeContext *ctxt = engine.rootContext(); ctxt->setContextProperty("font", testFileUrl("tarzeau_ocr_a.ttf")); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QSignalSpy nameSpy(fontObject, SIGNAL(nameChanged())); QSignalSpy statusSpy(fontObject, SIGNAL(statusChanged())); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 0); QCOMPARE(statusSpy.count(), 0); QTRY_COMPARE(fontObject->name(), QString("OCRA")); ctxt->setContextProperty("font", "http://localhost:14448/daniel.ttf"); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Loading); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 1); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("Daniel")); ctxt->setContextProperty("font", testFileUrl("tarzeau_ocr_a.ttf")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 2); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("OCRA")); ctxt->setContextProperty("font", "http://localhost:14448/daniel.ttf"); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 3); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("Daniel")); } void tst_qdeclarativefontloader::changeFontSourceViaState() { QQuickView canvas(testFileUrl("qtbug-20268.qml")); canvas.show(); canvas.requestActivateWindow(); QTest::qWaitForWindowShown(&canvas); QTRY_COMPARE(&canvas, qGuiApp->focusWindow()); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(qvariant_cast<QObject *>(canvas.rootObject()->property("fontloader"))); QVERIFY(fontObject != 0); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); canvas.rootObject()->setProperty("usename", true); // This warning should probably not be printed once QTBUG-20268 is fixed QString warning = QString(testFileUrl("qtbug-20268.qml").toString()) + QLatin1String(":13:5: QML FontLoader: Cannot load font: \"\""); QTest::ignoreMessage(QtWarningMsg, qPrintable(warning)); QEXPECT_FAIL("", "QTBUG-20268", Abort); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(canvas.rootObject()->property("name").toString(), QString("Tahoma")); } QTEST_MAIN(tst_qdeclarativefontloader) #include "tst_qdeclarativefontloader.moc" <commit_msg>Remove QSKIPs from font loader autotest.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtTest/QSignalSpy> #include <QtDeclarative/qdeclarativeengine.h> #include <QtDeclarative/qdeclarativecomponent.h> #include <QtDeclarative/qdeclarativecontext.h> #include <QtQuick/private/qdeclarativefontloader_p.h> #include "../../shared/util.h" #include "../../shared/testhttpserver.h" #include <QtQuick/QQuickView> #include <QtQuick/QQuickItem> #define SERVER_PORT 14448 class tst_qdeclarativefontloader : public QDeclarativeDataTest { Q_OBJECT public: tst_qdeclarativefontloader(); private slots: void initTestCase(); void noFont(); void namedFont(); void localFont(); void failLocalFont(); void webFont(); void redirWebFont(); void failWebFont(); void changeFont(); void changeFontSourceViaState(); private: QDeclarativeEngine engine; TestHTTPServer server; }; tst_qdeclarativefontloader::tst_qdeclarativefontloader() : server(SERVER_PORT) { } void tst_qdeclarativefontloader::initTestCase() { QDeclarativeDataTest::initTestCase(); server.serveDirectory(dataDirectory()); QVERIFY(server.isValid()); } void tst_qdeclarativefontloader::noFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->name(), QString("")); QCOMPARE(fontObject->source(), QUrl("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Null); delete fontObject; } void tst_qdeclarativefontloader::namedFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { name: \"Helvetica\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QCOMPARE(fontObject->source(), QUrl("")); QCOMPARE(fontObject->name(), QString("Helvetica")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::localFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"" + testFile("tarzeau_ocr_a.ttf") + "\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::failLocalFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"" + testFileUrl("dummy.ttf").toString() + "\" }"; QTest::ignoreMessage(QtWarningMsg, QString("file::2:1: QML FontLoader: Cannot load font: \"" + testFileUrl("dummy.ttf").toString() + "\"").toUtf8().constData()); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Error); } void tst_qdeclarativefontloader::webFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/tarzeau_ocr_a.ttf\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::redirWebFont() { server.addRedirect("olddir/oldname.ttf","../tarzeau_ocr_a.ttf"); QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/olddir/oldname.ttf\" }"; QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); } void tst_qdeclarativefontloader::failWebFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: \"http://localhost:14448/nonexist.ttf\" }"; QTest::ignoreMessage(QtWarningMsg, "file::2:1: QML FontLoader: Cannot load font: \"http://localhost:14448/nonexist.ttf\""); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Error); } void tst_qdeclarativefontloader::changeFont() { QString componentStr = "import QtQuick 2.0\nFontLoader { source: font }"; QDeclarativeContext *ctxt = engine.rootContext(); ctxt->setContextProperty("font", testFileUrl("tarzeau_ocr_a.ttf")); QDeclarativeComponent component(&engine); component.setData(componentStr.toLatin1(), QUrl::fromLocalFile("")); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(component.create()); QVERIFY(fontObject != 0); QSignalSpy nameSpy(fontObject, SIGNAL(nameChanged())); QSignalSpy statusSpy(fontObject, SIGNAL(statusChanged())); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 0); QCOMPARE(statusSpy.count(), 0); QTRY_COMPARE(fontObject->name(), QString("OCRA")); ctxt->setContextProperty("font", "http://localhost:14448/daniel.ttf"); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Loading); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 1); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("Daniel")); ctxt->setContextProperty("font", testFileUrl("tarzeau_ocr_a.ttf")); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 2); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("OCRA")); ctxt->setContextProperty("font", "http://localhost:14448/daniel.ttf"); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(nameSpy.count(), 3); QCOMPARE(statusSpy.count(), 2); QTRY_COMPARE(fontObject->name(), QString("Daniel")); } void tst_qdeclarativefontloader::changeFontSourceViaState() { QQuickView canvas(testFileUrl("qtbug-20268.qml")); canvas.show(); canvas.requestActivateWindow(); QTest::qWaitForWindowShown(&canvas); QTRY_COMPARE(&canvas, qGuiApp->focusWindow()); QDeclarativeFontLoader *fontObject = qobject_cast<QDeclarativeFontLoader*>(qvariant_cast<QObject *>(canvas.rootObject()->property("fontloader"))); QVERIFY(fontObject != 0); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QVERIFY(fontObject->source() != QUrl("")); QTRY_COMPARE(fontObject->name(), QString("OCRA")); canvas.rootObject()->setProperty("usename", true); // This warning should probably not be printed once QTBUG-20268 is fixed QString warning = QString(testFileUrl("qtbug-20268.qml").toString()) + QLatin1String(":13:5: QML FontLoader: Cannot load font: \"\""); QTest::ignoreMessage(QtWarningMsg, qPrintable(warning)); QEXPECT_FAIL("", "QTBUG-20268", Abort); QTRY_VERIFY(fontObject->status() == QDeclarativeFontLoader::Ready); QCOMPARE(canvas.rootObject()->property("name").toString(), QString("Tahoma")); } QTEST_MAIN(tst_qdeclarativefontloader) #include "tst_qdeclarativefontloader.moc" <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info * * This program 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, 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "cr_store.h" #include "seeks_proxy.h" #include "rank_estimators.h" #include "query_capture.h" #include "query_context.h" #include "user_db.h" #include "plugin_manager.h" #include "proxy_configuration.h" using namespace seeks_plugins; using namespace sp; std::string hosts[2] = { "seeks.node1", "seeks.node2" }; int ports[2] = { 8250, 8251 }; TEST(CRTest,cr_cache) { cr_store crs; cr_cache *crc = new cr_cache(cr_store::generate_peer(hosts[0],ports[0]),&crs); std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; db_record *rec = new db_record(); crc->add(key,rec); ASSERT_EQ(1,crc->_records.size()); ASSERT_EQ(1,seeks_proxy::_memory_dust.size()); // automatically registered through sweeper. time_t lu = (*crc->_records.begin()).second->_last_use; cached_record *cr = crc->find(key); ASSERT_TRUE(NULL != cr); ASSERT_EQ(rec,cr->_rec); ASSERT_TRUE(cr->_last_use >= lu); sweeper::sweep_all(); // delete cr and unregister from dust. ASSERT_TRUE(seeks_proxy::_memory_dust.empty()); ASSERT_TRUE(crc->_records.empty()); } TEST(CRTest,cr_record) { cr_store crs; std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; db_record *rec = new db_record(); crs.add(cr_store::generate_peer(hosts[0],ports[0]),key,rec); ASSERT_EQ(1,crs._store.size()); ASSERT_EQ(1,seeks_proxy::_memory_dust.size()); bool has_key = false; db_record *rec_f = crs.find(cr_store::generate_peer(hosts[0],ports[0]),key,has_key); ASSERT_TRUE(has_key); ASSERT_TRUE(rec == rec_f); sweeper::sweep_all(); // delete cr and unregister from dust. ASSERT_TRUE(crs._store.empty()); } TEST(CRTest,find_dbr) { std::string dbfile = "seeks_test.db"; unlink(dbfile.c_str()); // just in case. user_db udb(dbfile); udb.open_db(); seeks_proxy::_user_db = &udb; // load plugins. std::string basedir = "../../../"; seeks_proxy::_basedir = basedir.c_str(); seeks_proxy::_configfile = basedir + "config"; seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile); plugin_manager::_plugin_repository = basedir + "/plugins/"; plugin_manager::load_all_plugins(); plugin_manager::start_plugins(); // access to plugins. plugin *pl = plugin_manager::get_plugin("query-capture"); ASSERT_TRUE(NULL!=pl); query_capture *qcpl = static_cast<query_capture*>(pl); ASSERT_TRUE(NULL!=qcpl); query_capture_element *qcelt = qcpl->_qelt; // add a record to the db. std::string query = "seeks"; std::string url = "http://www.seeks-project.info/"; std::string host,path; query_capture::process_url(url,host,path); hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters = new hash_map<const char*,const char*,hash<const char*>,eqstr>(); miscutil::add_map_entry(parameters,"q",1,query.c_str(),1); std::list<const char*> headers; query_context *qc = new query_context(parameters,headers); try { qcelt->store_queries(qc->_lc_query,qc,url,host,"query-capture"); } catch (sp_exception &e) { ASSERT_EQ(SP_ERR_OK,e.code()); // would fail. } miscutil::free_map(parameters); // test find_dbr based on cr_store. std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; bool in_store = false; db_record *dbr = rank_estimator::find_dbr(&udb,key,"query-capture",in_store); ASSERT_TRUE(NULL!=dbr); db_query_record *dqr = dynamic_cast<db_query_record*>(dbr); ASSERT_TRUE(NULL!=dqr); ASSERT_EQ(1,dqr->_related_queries.size()); query_data *qd = (*dqr->_related_queries.begin()).second; ASSERT_TRUE(NULL!=qd); ASSERT_EQ("seeks",qd->_query); ASSERT_EQ(2,qd->_visited_urls->size()); std::string rkey = user_db::generate_rkey(key,"query-capture"); rank_estimator::_store.add(host,-1,"",rkey,dbr); user_db udbr(false,host,-1,"","sn"); db_record *dbr2 = rank_estimator::find_dbr(&udbr,key,"query-capture",in_store); ASSERT_EQ(dbr,dbr2); ASSERT_EQ(1,rank_estimator::_store._store.size()); // clear all. sweeper::sweep_all(); udb.close_db(); plugin_manager::close_all_plugins(); delete seeks_proxy::_config; unlink(dbfile.c_str()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>updated unit tests with new user_db main constructor signature<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info * * This program 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, 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "cr_store.h" #include "seeks_proxy.h" #include "rank_estimators.h" #include "query_capture.h" #include "query_context.h" #include "user_db.h" #include "plugin_manager.h" #include "proxy_configuration.h" using namespace seeks_plugins; using namespace sp; std::string hosts[2] = { "seeks.node1", "seeks.node2" }; int ports[2] = { 8250, 8251 }; TEST(CRTest,cr_cache) { cr_store crs; cr_cache *crc = new cr_cache(cr_store::generate_peer(hosts[0],ports[0]),&crs); std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; db_record *rec = new db_record(); crc->add(key,rec); ASSERT_EQ(1,crc->_records.size()); ASSERT_EQ(1,seeks_proxy::_memory_dust.size()); // automatically registered through sweeper. time_t lu = (*crc->_records.begin()).second->_last_use; cached_record *cr = crc->find(key); ASSERT_TRUE(NULL != cr); ASSERT_EQ(rec,cr->_rec); ASSERT_TRUE(cr->_last_use >= lu); sweeper::sweep_all(); // delete cr and unregister from dust. ASSERT_TRUE(seeks_proxy::_memory_dust.empty()); ASSERT_TRUE(crc->_records.empty()); } TEST(CRTest,cr_record) { cr_store crs; std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; db_record *rec = new db_record(); crs.add(cr_store::generate_peer(hosts[0],ports[0]),key,rec); ASSERT_EQ(1,crs._store.size()); ASSERT_EQ(1,seeks_proxy::_memory_dust.size()); bool has_key = false; db_record *rec_f = crs.find(cr_store::generate_peer(hosts[0],ports[0]),key,has_key); ASSERT_TRUE(has_key); ASSERT_TRUE(rec == rec_f); sweeper::sweep_all(); // delete cr and unregister from dust. ASSERT_TRUE(crs._store.empty()); } TEST(CRTest,find_dbr) { std::string dbfile = "seeks_test.db"; unlink(dbfile.c_str()); // just in case. user_db udb(dbfile); udb.open_db(); seeks_proxy::_user_db = &udb; // load plugins. std::string basedir = "../../../"; seeks_proxy::_basedir = basedir.c_str(); seeks_proxy::_configfile = basedir + "config"; seeks_proxy::_config = new proxy_configuration(seeks_proxy::_configfile); plugin_manager::_plugin_repository = basedir + "/plugins/"; plugin_manager::load_all_plugins(); plugin_manager::start_plugins(); // access to plugins. plugin *pl = plugin_manager::get_plugin("query-capture"); ASSERT_TRUE(NULL!=pl); query_capture *qcpl = static_cast<query_capture*>(pl); ASSERT_TRUE(NULL!=qcpl); query_capture_element *qcelt = qcpl->_qelt; // add a record to the db. std::string query = "seeks"; std::string url = "http://www.seeks-project.info/"; std::string host,path; query_capture::process_url(url,host,path); hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters = new hash_map<const char*,const char*,hash<const char*>,eqstr>(); miscutil::add_map_entry(parameters,"q",1,query.c_str(),1); std::list<const char*> headers; query_context *qc = new query_context(parameters,headers); try { qcelt->store_queries(qc->_lc_query,qc,url,host,"query-capture"); } catch (sp_exception &e) { ASSERT_EQ(SP_ERR_OK,e.code()); // would fail. } miscutil::free_map(parameters); // test find_dbr based on cr_store. std::string key = "1645a6897e62417931f26bcbdf4687c9c026b626"; bool in_store = false; db_record *dbr = rank_estimator::find_dbr(&udb,key,"query-capture",in_store); ASSERT_TRUE(NULL!=dbr); db_query_record *dqr = dynamic_cast<db_query_record*>(dbr); ASSERT_TRUE(NULL!=dqr); ASSERT_EQ(1,dqr->_related_queries.size()); query_data *qd = (*dqr->_related_queries.begin()).second; ASSERT_TRUE(NULL!=qd); ASSERT_EQ("seeks",qd->_query); ASSERT_EQ(2,qd->_visited_urls->size()); std::string rkey = user_db::generate_rkey(key,"query-capture"); rank_estimator::_store.add(host,-1,"",rkey,dbr); user_db udbr(false,"",host,-1,"","sn"); db_record *dbr2 = rank_estimator::find_dbr(&udbr,key,"query-capture",in_store); ASSERT_EQ(dbr,dbr2); ASSERT_EQ(1,rank_estimator::_store._store.size()); // clear all. sweeper::sweep_all(); udb.close_db(); plugin_manager::close_all_plugins(); delete seeks_proxy::_config; unlink(dbfile.c_str()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "dreal/dreal_main.h" #include <csignal> #include <cstdlib> #include <iostream> #include "dreal/dr/run.h" #include "dreal/smt2/run.h" #include "dreal/solver/context.h" #include "dreal/util/exception.h" #include "dreal/util/filesystem.h" #include "dreal/util/logging.h" namespace dreal { using std::cerr; using std::endl; using std::string; using std::vector; MainProgram::MainProgram(int argc, const char* argv[]) { AddOptions(); opt_.parse(argc, argv); // Parse Options is_options_all_valid_ = ValidateOptions(); } void MainProgram::PrintUsage() { string usage; opt_.getUsage(usage); cerr << usage; } void MainProgram::AddOptions() { #ifndef NDEBUG const string build_type{"Debug"}; #else const string build_type{"Release"}; #endif opt_.overview = fmt::format("dReal v{} ({} Build) : delta-complete SMT solver", Context::version(), build_type); opt_.syntax = "dreal [OPTIONS] <input file> (.smt2 or .dr)"; // NOTE: Make sure to match the default values specified here with the ones // specified in dreal/solver/config.h. opt_.add("" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Display usage instructions.", "-h", "-help", "--help", "--usage"); auto* const positive_double_option_validator = new ez::ezOptionValidator("d" /* double */, "gt", "0"); auto* const positive_int_option_validator = new ez::ezOptionValidator("s4" /* 4byte integer */, "gt", "0"); opt_.add("0.001" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Precision (default = 0.001)\n", "--precision", positive_double_option_validator); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Produce models if delta-sat\n", "--produce-models", "--model"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Debug scanning/lexing\n", "--debug-scanning"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Debug parsing\n", "--debug-parsing"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Read from standard input. Uses smt2 by default.\n", "--in"); auto* const format_option_validator = new ez::ezOptionValidator("t", "in", "auto,dr,smt2", false); opt_.add("auto" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "File format. Any one of these (default = auto):\n" "smt2, dr, auto (use file extension)\n", "--format", format_option_validator); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use polytope contractor.\n", "--polytope"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use polytope contractor in forall contractor.\n", "--forall-polytope"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use worklist fixpoint algorithm in ICP.\n", "--worklist-fixpoint"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use local optimization algorithm for exist-forall problems.\n", "--local-optimization"); opt_.add("1e-6" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Relative tolerance on function value (default = 1e-6)\n", "--nlopt-ftol-rel", positive_double_option_validator); opt_.add("1e-6" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Absolute tolerance on function value (default = 1e-6)\n", "--nlopt-ftol-abs", positive_double_option_validator); opt_.add("100" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Number of maximum function evaluations (default = 100)\n", "--nlopt-maxeval", positive_int_option_validator); opt_.add( "0.1" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Maximum optimization time (in second) (default = 0.01 sec)\n", "--nlopt-maxtime", positive_double_option_validator); auto* const verbose_option_validator = new ez::ezOptionValidator( "t", "in", "trace,debug,info,warning,error,critical,off", true); opt_.add( "error", // Default. 0, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "Verbosity level. Either one of these (default = error):\n" "trace, debug, info, warning, error, critical, off", // Help description. "--verbose", // Flag token. verbose_option_validator); opt_.add("2" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Set default initial phase for SAT solver.\n" " 0 = false\n" " 1 = true\n" " 2 = Jeroslow-Wang (default)\n" " 3 = random initial phase\n", "--sat-default-phase"); opt_.add("0" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Set a seed for the random number generator.", "--random-seed"); } bool MainProgram::ValidateOptions() { // Checks bad options and bad arguments. vector<string> bad_options; vector<string> bad_args; if (!opt_.gotRequired(bad_options)) { for (const auto& bad_option : bad_options) { cerr << "ERROR: Missing required option " << bad_option << ".\n\n"; } PrintUsage(); return false; } if (!opt_.gotExpected(bad_options)) { for (const auto& bad_option : bad_options) { cerr << "ERROR: Got unexpected number of arguments for option " << bad_option << ".\n\n"; } PrintUsage(); return false; } if (!opt_.gotValid(bad_options, bad_args)) { for (size_t i = 0; i < bad_options.size(); ++i) { cerr << "ERROR: Got invalid argument \"" << bad_args[i] << "\" for option " << bad_options[i] << ".\n\n"; } PrintUsage(); return false; } // After filtering out bad options/arguments, save the valid ones in `args_`. args_.insert(args_.end(), opt_.firstArgs.begin() + 1, opt_.firstArgs.end()); args_.insert(args_.end(), opt_.unknownArgs.begin(), opt_.unknownArgs.end()); args_.insert(args_.end(), opt_.lastArgs.begin(), opt_.lastArgs.end()); if (opt_.isSet("-h") || (args_.empty() && !opt_.isSet("--in")) || args_.size() > 1) { PrintUsage(); return false; } return true; } void MainProgram::ExtractOptions() { // Temporary variables used to set options. string verbosity; opt_.get("--verbose")->getString(verbosity); if (verbosity == "trace") { log()->set_level(spdlog::level::trace); } else if (verbosity == "debug") { log()->set_level(spdlog::level::debug); } else if (verbosity == "info") { log()->set_level(spdlog::level::info); } else if (verbosity == "warning") { log()->set_level(spdlog::level::warn); } else if (verbosity == "error") { log()->set_level(spdlog::level::err); } else if (verbosity == "critical") { log()->set_level(spdlog::level::critical); } else { log()->set_level(spdlog::level::off); } // --precision if (opt_.isSet("--precision")) { double precision{0.0}; opt_.get("--precision")->getDouble(precision); config_.mutable_precision().set_from_command_line(precision); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --precision = {}", config_.precision()); } // --produce-model if (opt_.isSet("--produce-models")) { config_.mutable_produce_models().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --produce-models = {}", config_.produce_models()); } // --polytope if (opt_.isSet("--polytope")) { config_.mutable_use_polytope().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --polytope = {}", config_.use_polytope()); } // --forall-polytope if (opt_.isSet("--forall-polytope")) { config_.mutable_use_polytope_in_forall().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --forall-polytope = {}", config_.use_polytope_in_forall()); } // --worklist-fixpoint if (opt_.isSet("--worklist-fixpoint")) { config_.mutable_use_worklist_fixpoint().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --worklist-fixpoint = {}", config_.use_worklist_fixpoint()); } // --local-optimization if (opt_.isSet("--local-optimization")) { config_.mutable_use_local_optimization().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --local-optimization = {}", config_.use_local_optimization()); } // --nlopt-ftol-rel double nlopt_ftol_rel{0.0}; if (opt_.isSet("--nlopt-ftol-rel")) { opt_.get("--nlopt-ftol-rel")->getDouble(nlopt_ftol_rel); config_.mutable_nlopt_ftol_rel().set_from_command_line(nlopt_ftol_rel); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-ftol-rel = {}", config_.nlopt_ftol_rel()); } // --nlopt-ftol-abs if (opt_.isSet("--nlopt-ftol-abs")) { double nlopt_ftol_abs{0.0}; opt_.get("--nlopt-ftol-abs")->getDouble(nlopt_ftol_abs); config_.mutable_nlopt_ftol_abs().set_from_command_line(nlopt_ftol_abs); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-ftol-abs = {}", config_.nlopt_ftol_abs()); } // --nlopt-maxeval if (opt_.isSet("--nlopt-maxeval")) { int nlopt_maxeval{0}; opt_.get("--nlopt-maxeval")->getInt(nlopt_maxeval); config_.mutable_nlopt_maxeval().set_from_command_line(nlopt_maxeval); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-maxeval = {}", config_.nlopt_maxeval()); } // --nlopt-maxtime if (opt_.isSet("--nlopt-maxtime")) { double nlopt_maxtime{0.0}; opt_.get("--nlopt-maxtime")->getDouble(nlopt_maxtime); config_.mutable_nlopt_maxtime().set_from_command_line(nlopt_maxtime); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-maxtime = {}", config_.nlopt_maxtime()); } // --sat-default-phase if (opt_.isSet("--sat-default-phase")) { int sat_default_phase{2}; opt_.get("--sat-default-phase")->getInt(sat_default_phase); config_.mutable_sat_default_phase().set_from_command_line( static_cast<Config::SatDefaultPhase>(sat_default_phase)); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --sat-default-phase = {}", config_.sat_default_phase()); } // --random-seed if (opt_.isSet("--random-seed")) { // NOLINTNEXTLINE(runtime/int) static_assert(sizeof(unsigned long) == sizeof(std::uint64_t), "sizeof(unsigned long) != sizeof(std::uint64_t)."); std::uint64_t random_seed{0}; opt_.get("--random-seed")->getULong(random_seed); config_.mutable_random_seed().set_from_command_line(random_seed); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --random-seed = {}", config_.random_seed()); } } int MainProgram::Run() { if (!is_options_all_valid_) { return 1; } ExtractOptions(); string filename; if (!args_.empty()) { filename = *args_[0]; if (filename.empty()) { PrintUsage(); return 1; } } if (!opt_.isSet("--in") && !file_exists(filename)) { cerr << "File not found: " << filename << "\n" << endl; PrintUsage(); return 1; } const string extension{get_extension(filename)}; string format_opt; opt_.get("--format")->getString(format_opt); if (format_opt == "smt2" || (format_opt == "auto" && (extension == "smt2" || opt_.isSet("--in")))) { RunSmt2(filename, config_, opt_.isSet("--debug-scanning"), opt_.isSet("--debug-parsing")); } else if (format_opt == "dr" || (format_opt == "auto" && extension == "dr")) { RunDr(filename, config_, opt_.isSet("--debug-scanning"), opt_.isSet("--debug-parsing")); } else { cerr << "Unknown extension: " << filename << "\n" << endl; PrintUsage(); return 1; } return 0; } } // namespace dreal namespace { void HandleSigInt(const int) { // Properly exit so that we can see stat information produced by destructors // even if a user press C-c. std::exit(1); } } // namespace int main(int argc, const char* argv[]) { std::signal(SIGINT, HandleSigInt); dreal::MainProgram main_program{argc, argv}; return main_program.Run(); } <commit_msg>fix(dreal_main.cc): Use unsigned long<commit_after>#include "dreal/dreal_main.h" #include <csignal> #include <cstdlib> #include <iostream> #include "dreal/dr/run.h" #include "dreal/smt2/run.h" #include "dreal/solver/context.h" #include "dreal/util/exception.h" #include "dreal/util/filesystem.h" #include "dreal/util/logging.h" namespace dreal { using std::cerr; using std::endl; using std::string; using std::vector; MainProgram::MainProgram(int argc, const char* argv[]) { AddOptions(); opt_.parse(argc, argv); // Parse Options is_options_all_valid_ = ValidateOptions(); } void MainProgram::PrintUsage() { string usage; opt_.getUsage(usage); cerr << usage; } void MainProgram::AddOptions() { #ifndef NDEBUG const string build_type{"Debug"}; #else const string build_type{"Release"}; #endif opt_.overview = fmt::format("dReal v{} ({} Build) : delta-complete SMT solver", Context::version(), build_type); opt_.syntax = "dreal [OPTIONS] <input file> (.smt2 or .dr)"; // NOTE: Make sure to match the default values specified here with the ones // specified in dreal/solver/config.h. opt_.add("" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Display usage instructions.", "-h", "-help", "--help", "--usage"); auto* const positive_double_option_validator = new ez::ezOptionValidator("d" /* double */, "gt", "0"); auto* const positive_int_option_validator = new ez::ezOptionValidator("s4" /* 4byte integer */, "gt", "0"); opt_.add("0.001" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Precision (default = 0.001)\n", "--precision", positive_double_option_validator); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Produce models if delta-sat\n", "--produce-models", "--model"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Debug scanning/lexing\n", "--debug-scanning"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Debug parsing\n", "--debug-parsing"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Read from standard input. Uses smt2 by default.\n", "--in"); auto* const format_option_validator = new ez::ezOptionValidator("t", "in", "auto,dr,smt2", false); opt_.add("auto" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "File format. Any one of these (default = auto):\n" "smt2, dr, auto (use file extension)\n", "--format", format_option_validator); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use polytope contractor.\n", "--polytope"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use polytope contractor in forall contractor.\n", "--forall-polytope"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use worklist fixpoint algorithm in ICP.\n", "--worklist-fixpoint"); opt_.add("false" /* Default */, false /* Required? */, 0 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Use local optimization algorithm for exist-forall problems.\n", "--local-optimization"); opt_.add("1e-6" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Relative tolerance on function value (default = 1e-6)\n", "--nlopt-ftol-rel", positive_double_option_validator); opt_.add("1e-6" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Absolute tolerance on function value (default = 1e-6)\n", "--nlopt-ftol-abs", positive_double_option_validator); opt_.add("100" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Number of maximum function evaluations (default = 100)\n", "--nlopt-maxeval", positive_int_option_validator); opt_.add( "0.1" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "[NLopt] Maximum optimization time (in second) (default = 0.01 sec)\n", "--nlopt-maxtime", positive_double_option_validator); auto* const verbose_option_validator = new ez::ezOptionValidator( "t", "in", "trace,debug,info,warning,error,critical,off", true); opt_.add( "error", // Default. 0, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "Verbosity level. Either one of these (default = error):\n" "trace, debug, info, warning, error, critical, off", // Help description. "--verbose", // Flag token. verbose_option_validator); opt_.add("2" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Set default initial phase for SAT solver.\n" " 0 = false\n" " 1 = true\n" " 2 = Jeroslow-Wang (default)\n" " 3 = random initial phase\n", "--sat-default-phase"); opt_.add("0" /* Default */, false /* Required? */, 1 /* Number of args expected. */, 0 /* Delimiter if expecting multiple args. */, "Set a seed for the random number generator.", "--random-seed"); } bool MainProgram::ValidateOptions() { // Checks bad options and bad arguments. vector<string> bad_options; vector<string> bad_args; if (!opt_.gotRequired(bad_options)) { for (const auto& bad_option : bad_options) { cerr << "ERROR: Missing required option " << bad_option << ".\n\n"; } PrintUsage(); return false; } if (!opt_.gotExpected(bad_options)) { for (const auto& bad_option : bad_options) { cerr << "ERROR: Got unexpected number of arguments for option " << bad_option << ".\n\n"; } PrintUsage(); return false; } if (!opt_.gotValid(bad_options, bad_args)) { for (size_t i = 0; i < bad_options.size(); ++i) { cerr << "ERROR: Got invalid argument \"" << bad_args[i] << "\" for option " << bad_options[i] << ".\n\n"; } PrintUsage(); return false; } // After filtering out bad options/arguments, save the valid ones in `args_`. args_.insert(args_.end(), opt_.firstArgs.begin() + 1, opt_.firstArgs.end()); args_.insert(args_.end(), opt_.unknownArgs.begin(), opt_.unknownArgs.end()); args_.insert(args_.end(), opt_.lastArgs.begin(), opt_.lastArgs.end()); if (opt_.isSet("-h") || (args_.empty() && !opt_.isSet("--in")) || args_.size() > 1) { PrintUsage(); return false; } return true; } void MainProgram::ExtractOptions() { // Temporary variables used to set options. string verbosity; opt_.get("--verbose")->getString(verbosity); if (verbosity == "trace") { log()->set_level(spdlog::level::trace); } else if (verbosity == "debug") { log()->set_level(spdlog::level::debug); } else if (verbosity == "info") { log()->set_level(spdlog::level::info); } else if (verbosity == "warning") { log()->set_level(spdlog::level::warn); } else if (verbosity == "error") { log()->set_level(spdlog::level::err); } else if (verbosity == "critical") { log()->set_level(spdlog::level::critical); } else { log()->set_level(spdlog::level::off); } // --precision if (opt_.isSet("--precision")) { double precision{0.0}; opt_.get("--precision")->getDouble(precision); config_.mutable_precision().set_from_command_line(precision); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --precision = {}", config_.precision()); } // --produce-model if (opt_.isSet("--produce-models")) { config_.mutable_produce_models().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --produce-models = {}", config_.produce_models()); } // --polytope if (opt_.isSet("--polytope")) { config_.mutable_use_polytope().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --polytope = {}", config_.use_polytope()); } // --forall-polytope if (opt_.isSet("--forall-polytope")) { config_.mutable_use_polytope_in_forall().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --forall-polytope = {}", config_.use_polytope_in_forall()); } // --worklist-fixpoint if (opt_.isSet("--worklist-fixpoint")) { config_.mutable_use_worklist_fixpoint().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --worklist-fixpoint = {}", config_.use_worklist_fixpoint()); } // --local-optimization if (opt_.isSet("--local-optimization")) { config_.mutable_use_local_optimization().set_from_command_line(true); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --local-optimization = {}", config_.use_local_optimization()); } // --nlopt-ftol-rel double nlopt_ftol_rel{0.0}; if (opt_.isSet("--nlopt-ftol-rel")) { opt_.get("--nlopt-ftol-rel")->getDouble(nlopt_ftol_rel); config_.mutable_nlopt_ftol_rel().set_from_command_line(nlopt_ftol_rel); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-ftol-rel = {}", config_.nlopt_ftol_rel()); } // --nlopt-ftol-abs if (opt_.isSet("--nlopt-ftol-abs")) { double nlopt_ftol_abs{0.0}; opt_.get("--nlopt-ftol-abs")->getDouble(nlopt_ftol_abs); config_.mutable_nlopt_ftol_abs().set_from_command_line(nlopt_ftol_abs); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-ftol-abs = {}", config_.nlopt_ftol_abs()); } // --nlopt-maxeval if (opt_.isSet("--nlopt-maxeval")) { int nlopt_maxeval{0}; opt_.get("--nlopt-maxeval")->getInt(nlopt_maxeval); config_.mutable_nlopt_maxeval().set_from_command_line(nlopt_maxeval); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-maxeval = {}", config_.nlopt_maxeval()); } // --nlopt-maxtime if (opt_.isSet("--nlopt-maxtime")) { double nlopt_maxtime{0.0}; opt_.get("--nlopt-maxtime")->getDouble(nlopt_maxtime); config_.mutable_nlopt_maxtime().set_from_command_line(nlopt_maxtime); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --nlopt-maxtime = {}", config_.nlopt_maxtime()); } // --sat-default-phase if (opt_.isSet("--sat-default-phase")) { int sat_default_phase{2}; opt_.get("--sat-default-phase")->getInt(sat_default_phase); config_.mutable_sat_default_phase().set_from_command_line( static_cast<Config::SatDefaultPhase>(sat_default_phase)); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --sat-default-phase = {}", config_.sat_default_phase()); } // --random-seed if (opt_.isSet("--random-seed")) { // NOLINTNEXTLINE(runtime/int) static_assert(sizeof(unsigned long) == sizeof(std::uint64_t), "sizeof(unsigned long) != sizeof(std::uint64_t)."); // NOLINTNEXTLINE(runtime/int) unsigned long random_seed{0}; opt_.get("--random-seed")->getULong(random_seed); config_.mutable_random_seed().set_from_command_line(random_seed); DREAL_LOG_DEBUG("MainProgram::ExtractOptions() --random-seed = {}", config_.random_seed()); } } int MainProgram::Run() { if (!is_options_all_valid_) { return 1; } ExtractOptions(); string filename; if (!args_.empty()) { filename = *args_[0]; if (filename.empty()) { PrintUsage(); return 1; } } if (!opt_.isSet("--in") && !file_exists(filename)) { cerr << "File not found: " << filename << "\n" << endl; PrintUsage(); return 1; } const string extension{get_extension(filename)}; string format_opt; opt_.get("--format")->getString(format_opt); if (format_opt == "smt2" || (format_opt == "auto" && (extension == "smt2" || opt_.isSet("--in")))) { RunSmt2(filename, config_, opt_.isSet("--debug-scanning"), opt_.isSet("--debug-parsing")); } else if (format_opt == "dr" || (format_opt == "auto" && extension == "dr")) { RunDr(filename, config_, opt_.isSet("--debug-scanning"), opt_.isSet("--debug-parsing")); } else { cerr << "Unknown extension: " << filename << "\n" << endl; PrintUsage(); return 1; } return 0; } } // namespace dreal namespace { void HandleSigInt(const int) { // Properly exit so that we can see stat information produced by destructors // even if a user press C-c. std::exit(1); } } // namespace int main(int argc, const char* argv[]) { std::signal(SIGINT, HandleSigInt); dreal::MainProgram main_program{argc, argv}; return main_program.Run(); } <|endoftext|>
<commit_before>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <random> #include <bitset> #include <boost/test/unit_test.hpp> #include <boost/range/irange.hpp> #include <seastar/core/semaphore.hh> #include <seastar/core/reactor.hh> #include <seastar/core/thread.hh> #include "seastarx.hh" #include "tests/test-utils.hh" #include "utils/flush_queue.hh" #include "log.hh" std::random_device rd; std::default_random_engine e1(rd()); SEASTAR_TEST_CASE(test_queue_ordering_random_ops) { struct env { env(size_t n) : promises(n) {} utils::flush_queue<int> queue; std::vector<promise<>> promises; std::vector<int> result; }; auto r = boost::irange(0, 100); return do_for_each(r, [](int) { constexpr size_t num_ops = 1000; auto e = make_lw_shared<env>(num_ops); int i = 0; for (auto& p : e->promises) { e->queue.run_with_ordered_post_op(i, [&p, i] { return p.get_future().then([i] { return make_ready_future<int>(i); }); }, [e](int i) { e->result.emplace_back(i); }); ++i; } auto res = e->queue.wait_for_pending(); std::uniform_int_distribution<size_t> dist(0, num_ops - 1); std::bitset<num_ops> set; while (!set.all()) { size_t i = dist(e1); if (!set.test(i)) { set[i] = true; e->promises[i].set_value(); } } return res.then([e] { BOOST_CHECK_EQUAL(e->result.size(), e->promises.size()); BOOST_REQUIRE(std::is_sorted(e->result.begin(), e->result.end())); }).finally([e] { return e->queue.close().finally([e] { }); }); }); } SEASTAR_TEST_CASE(test_queue_ordering_multi_ops) { struct env { env() : sem(0) {} utils::flush_queue<int> queue; std::vector<int> result; semaphore sem; size_t n = 0; }; auto r = boost::irange(0, 100); return do_for_each(r, [](int) { constexpr size_t num_ops = 1000; auto e = make_lw_shared<env>(); std::uniform_int_distribution<size_t> dist(0, num_ops - 1); for (size_t k = 0; k < num_ops*10; ++k) { int i = dist(e1); if (e->queue.has_operation(i) || (!e->queue.empty() && e->queue.highest_key() < i)) { e->queue.run_with_ordered_post_op(i, [e, i] { return e->sem.wait().then([i] { return make_ready_future<int>(i); }); }, [e](int i) { e->result.emplace_back(i); }); ++e->n; } } auto res = e->queue.wait_for_pending(); e->sem.signal(e->n); return res.then([e] { BOOST_CHECK_EQUAL(e->result.size(), e->n); BOOST_REQUIRE(std::is_sorted(e->result.begin(), e->result.end())); }).finally([e] { return e->queue.close().finally([e] { }); }); }); } template<typename Func, typename Post, typename Then> static future<> test_propagation(bool propagate, Func&& func, Post&& post, Then&& thn, bool want_except_in_run, bool want_except_in_wait) { auto queue = ::make_shared<utils::flush_queue<int>>(propagate); auto sem = ::make_shared<semaphore>(0); auto xr = ::make_shared<bool>(false); auto xw = ::make_shared<bool>(false); auto f1 = queue->run_with_ordered_post_op(0, [sem, func = std::forward<Func>(func)]() mutable { return sem->wait().then(std::forward<Func>(func)); }, std::forward<Post>(post)).handle_exception([xr](auto p) { *xr = true; }).discard_result(); auto f2 = queue->wait_for_pending(0).then(std::forward<Then>(thn)).handle_exception([xw](auto p) { *xw = true; }).discard_result(); sem->signal(); return seastar::when_all_succeed(std::move(f1), std::move(f2)).finally([sem, queue, want_except_in_run, want_except_in_wait, xr, xw] { BOOST_CHECK_EQUAL(want_except_in_run, *xr); BOOST_CHECK_EQUAL(want_except_in_wait, *xw); }).finally([queue] { return queue->close().finally([queue] { }); }); } SEASTAR_TEST_CASE(test_propagate_exception_in_op) { return test_propagation(true, // propagate exception to waiter [] { return make_exception_future(std::runtime_error("hej")); }, // ex in op [] { BOOST_FAIL("should not reach (1)"); }, // should not reach post [] { BOOST_FAIL("should not reach (2)"); }, // should not reach waiter "then" true, true ); } SEASTAR_TEST_CASE(test_propagate_exception_in_post) { return test_propagation(true, // propagate exception to waiter [] {}, // ok func [] { return make_exception_future(std::runtime_error("hej")); }, // ex in post [] { BOOST_FAIL("should not reach"); }, // should not reach waiter "then" true, true ); } SEASTAR_TEST_CASE(test_no_propagate_exception_in_op) { return test_propagation(false, // do not propagate exception to waiter [] { return make_exception_future(std::runtime_error("hej")); }, // ex in op [] { BOOST_FAIL("should not reach"); }, // should not reach post [] {}, // should reach waiter "then" true, false ); } SEASTAR_TEST_CASE(test_no_propagate_exception_in_post) { return test_propagation(false, // do not propagate exception to waiter [] {}, // ok func [] { return make_exception_future(std::runtime_error("hej")); }, // ex in post [] {}, // should reach waiter "then" true, false ); } <commit_msg>tests: flush_queue_test: de-template<commit_after>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <random> #include <bitset> #include <boost/test/unit_test.hpp> #include <boost/range/irange.hpp> #include <seastar/core/semaphore.hh> #include <seastar/core/reactor.hh> #include <seastar/core/thread.hh> #include "seastarx.hh" #include "tests/test-utils.hh" #include "utils/flush_queue.hh" #include "log.hh" std::random_device rd; std::default_random_engine e1(rd()); SEASTAR_TEST_CASE(test_queue_ordering_random_ops) { struct env { env(size_t n) : promises(n) {} utils::flush_queue<int> queue; std::vector<promise<>> promises; std::vector<int> result; }; auto r = boost::irange(0, 100); return do_for_each(r, [](int) { constexpr size_t num_ops = 1000; auto e = make_lw_shared<env>(num_ops); int i = 0; for (auto& p : e->promises) { e->queue.run_with_ordered_post_op(i, [&p, i] { return p.get_future().then([i] { return make_ready_future<int>(i); }); }, [e](int i) { e->result.emplace_back(i); }); ++i; } auto res = e->queue.wait_for_pending(); std::uniform_int_distribution<size_t> dist(0, num_ops - 1); std::bitset<num_ops> set; while (!set.all()) { size_t i = dist(e1); if (!set.test(i)) { set[i] = true; e->promises[i].set_value(); } } return res.then([e] { BOOST_CHECK_EQUAL(e->result.size(), e->promises.size()); BOOST_REQUIRE(std::is_sorted(e->result.begin(), e->result.end())); }).finally([e] { return e->queue.close().finally([e] { }); }); }); } SEASTAR_TEST_CASE(test_queue_ordering_multi_ops) { struct env { env() : sem(0) {} utils::flush_queue<int> queue; std::vector<int> result; semaphore sem; size_t n = 0; }; auto r = boost::irange(0, 100); return do_for_each(r, [](int) { constexpr size_t num_ops = 1000; auto e = make_lw_shared<env>(); std::uniform_int_distribution<size_t> dist(0, num_ops - 1); for (size_t k = 0; k < num_ops*10; ++k) { int i = dist(e1); if (e->queue.has_operation(i) || (!e->queue.empty() && e->queue.highest_key() < i)) { e->queue.run_with_ordered_post_op(i, [e, i] { return e->sem.wait().then([i] { return make_ready_future<int>(i); }); }, [e](int i) { e->result.emplace_back(i); }); ++e->n; } } auto res = e->queue.wait_for_pending(); e->sem.signal(e->n); return res.then([e] { BOOST_CHECK_EQUAL(e->result.size(), e->n); BOOST_REQUIRE(std::is_sorted(e->result.begin(), e->result.end())); }).finally([e] { return e->queue.close().finally([e] { }); }); }); } static future<> test_propagation(bool propagate, noncopyable_function<future<> ()> func, noncopyable_function<future<> ()> post, noncopyable_function<void ()> thn, bool want_except_in_run, bool want_except_in_wait) { auto queue = ::make_shared<utils::flush_queue<int>>(propagate); auto sem = ::make_shared<semaphore>(0); auto xr = ::make_shared<bool>(false); auto xw = ::make_shared<bool>(false); auto f1 = queue->run_with_ordered_post_op(0, [sem, func = std::move(func)]() mutable { return sem->wait().then(std::move(func)); }, std::move(post)).handle_exception([xr](auto p) { *xr = true; }).discard_result(); auto f2 = queue->wait_for_pending(0).then(std::move(thn)).handle_exception([xw](auto p) { *xw = true; }).discard_result(); sem->signal(); return seastar::when_all_succeed(std::move(f1), std::move(f2)).finally([sem, queue, want_except_in_run, want_except_in_wait, xr, xw] { BOOST_CHECK_EQUAL(want_except_in_run, *xr); BOOST_CHECK_EQUAL(want_except_in_wait, *xw); }).finally([queue] { return queue->close().finally([queue] { }); }); } SEASTAR_TEST_CASE(test_propagate_exception_in_op) { return test_propagation(true, // propagate exception to waiter [] { return make_exception_future(std::runtime_error("hej")); }, // ex in op [] { BOOST_FAIL("should not reach (1)"); return make_ready_future(); }, // should not reach post [] { BOOST_FAIL("should not reach (2)"); }, // should not reach waiter "then" true, true ); } SEASTAR_TEST_CASE(test_propagate_exception_in_post) { return test_propagation(true, // propagate exception to waiter [] { return make_ready_future(); }, // ok func [] { return make_exception_future(std::runtime_error("hej")); }, // ex in post [] { BOOST_FAIL("should not reach"); }, // should not reach waiter "then" true, true ); } SEASTAR_TEST_CASE(test_no_propagate_exception_in_op) { return test_propagation(false, // do not propagate exception to waiter [] { return make_exception_future(std::runtime_error("hej")); }, // ex in op [] { BOOST_FAIL("should not reach"); return make_ready_future(); }, // should not reach post [] {}, // should reach waiter "then" true, false ); } SEASTAR_TEST_CASE(test_no_propagate_exception_in_post) { return test_propagation(false, // do not propagate exception to waiter [] { return make_ready_future(); }, // ok func [] { return make_exception_future(std::runtime_error("hej")); }, // ex in post [] {}, // should reach waiter "then" true, false ); } <|endoftext|>
<commit_before>#include <LuaContext.hpp> #include <gtest/gtest.h> TEST(FunctionsWrite, NativeFunctions) { struct Foo { static int increment(int x) { return x + 1; } }; LuaContext context; context.writeVariable("f", &Foo::increment); context.writeFunction<int (int)>("g", &Foo::increment); context.writeFunction("h", &Foo::increment); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, FunctionObjects) { struct Foo { int operator()(int x) { return x + 1; } double operator()(double) { EXPECT_TRUE(false); return 0; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); } TEST(FunctionsWrite, FunctionObjectsConst) { struct Foo { int operator()(int x) { return x + 1; } int operator()(int x) const { return x + 1; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); } TEST(FunctionsWrite, FunctionObjectsAutodetect) { struct Foo { int operator()(int x) { return x + 1; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); context.writeFunction("h", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, Lambdas) { LuaContext context; const auto lambda = [](int x) { return x + 1; }; context.writeVariable("f", std::function<int (int)>(lambda)); context.writeFunction<int (int)>("g", lambda); context.writeFunction("h", lambda); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, DestructorCalled) { struct Foo { int operator()(int x) { return x + 1; } std::shared_ptr<char> dummy; }; auto foo = Foo{ std::make_shared<char>() }; std::weak_ptr<char> dummy = foo.dummy; auto context = std::make_shared<LuaContext>(); context->writeFunction("f", foo); foo.dummy.reset(); EXPECT_FALSE(dummy.expired()); context.reset(); EXPECT_TRUE(dummy.expired()); } TEST(FunctionsWrite, ReturningMultipleValues) { LuaContext context; context.writeFunction("f", [](int x) { return std::make_tuple(x, x+1, "hello"); }); context.executeCode("a, b, c = f(2)"); EXPECT_EQ(2, context.readVariable<int>("a")); EXPECT_EQ(3, context.readVariable<int>("b")); EXPECT_EQ("hello", context.readVariable<std::string>("c")); } <commit_msg>Added test for polymorphic functions<commit_after>#include <LuaContext.hpp> #include <gtest/gtest.h> TEST(FunctionsWrite, NativeFunctions) { struct Foo { static int increment(int x) { return x + 1; } }; LuaContext context; context.writeVariable("f", &Foo::increment); context.writeFunction<int (int)>("g", &Foo::increment); context.writeFunction("h", &Foo::increment); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, FunctionObjects) { struct Foo { int operator()(int x) { return x + 1; } double operator()(double) { EXPECT_TRUE(false); return 0; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); } TEST(FunctionsWrite, FunctionObjectsConst) { struct Foo { int operator()(int x) { return x + 1; } int operator()(int x) const { return x + 1; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); } TEST(FunctionsWrite, FunctionObjectsAutodetect) { struct Foo { int operator()(int x) { return x + 1; } }; LuaContext context; context.writeVariable("f", std::function<int (int)>(Foo{})); context.writeFunction<int (int)>("g", Foo{}); context.writeFunction("h", Foo{}); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, Lambdas) { LuaContext context; const auto lambda = [](int x) { return x + 1; }; context.writeVariable("f", std::function<int (int)>(lambda)); context.writeFunction<int (int)>("g", lambda); context.writeFunction("h", lambda); EXPECT_EQ(3, context.executeCode<int>("return f(2)")); EXPECT_EQ(13, context.executeCode<int>("return g(12)")); EXPECT_EQ(9, context.executeCode<int>("return h(8)")); } TEST(FunctionsWrite, DestructorCalled) { struct Foo { int operator()(int x) { return x + 1; } std::shared_ptr<char> dummy; }; auto foo = Foo{ std::make_shared<char>() }; std::weak_ptr<char> dummy = foo.dummy; auto context = std::make_shared<LuaContext>(); context->writeFunction("f", foo); foo.dummy.reset(); EXPECT_FALSE(dummy.expired()); context.reset(); EXPECT_TRUE(dummy.expired()); } TEST(FunctionsWrite, ReturningMultipleValues) { LuaContext context; context.writeFunction("f", [](int x) { return std::make_tuple(x, x+1, "hello"); }); context.executeCode("a, b, c = f(2)"); EXPECT_EQ(2, context.readVariable<int>("a")); EXPECT_EQ(3, context.readVariable<int>("b")); EXPECT_EQ("hello", context.readVariable<std::string>("c")); } TEST(FunctionsWrite, PolymorphicFunctions) { LuaContext context; context.writeFunction("f", [](boost::variant<int,bool,std::string> x) -> std::string { if (x.which() == 0) return "int"; else if (x.which() == 1) return "bool"; else return "string"; } ); EXPECT_EQ("int", context.executeCode<std::string>("return f(2)")); EXPECT_EQ("bool", context.executeCode<std::string>("return f(true)")); EXPECT_EQ("string", context.executeCode<std::string>("return f('test')")); } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/log/log.h> LOG_SETUP(".proton.server.searchabledocsubdb"); #include "searchabledocsubdb.h" #include <vespa/searchcore/proton/attribute/attribute_writer.h> #include <vespa/searchcore/proton/flushengine/threadedflushtarget.h> #include <vespa/searchcore/proton/index/index_manager_initializer.h> #include <vespa/searchcore/proton/index/index_writer.h> #include <vespa/searchcore/proton/metrics/legacy_documentdb_metrics.h> #include <vespa/searchcore/proton/metrics/metricswireservice.h> #include <vespa/searchcorespi/plugin/iindexmanagerfactory.h> #include <vespa/searchlib/common/indexmetainfo.h> #include <vespa/vespalib/io/fileutil.h> #include <vespa/vespalib/util/closuretask.h> using vespa::config::search::AttributesConfig; using vespa::config::search::RankProfilesConfig; using vespa::config::search::core::ProtonConfig; using proton::matching::MatchingStats; using proton::matching::SessionManager; using search::AttributeGuard; using search::AttributeVector; using search::GrowStrategy; using search::TuneFileDocumentDB; using search::index::Schema; using search::SerialNum; using searchcorespi::IndexManagerConfig; using searchcorespi::index::IndexMaintainerConfig; using searchcorespi::index::IndexMaintainerContext; using vespalib::IllegalStateException; using vespalib::ThreadStackExecutorBase; using namespace searchcorespi; namespace proton { SearchableDocSubDB::SearchableDocSubDB(const Config &cfg, const Context &ctx) : FastAccessDocSubDB(cfg._fastUpdCfg, ctx._fastUpdCtx), IIndexManager::Reconfigurer(), _indexMgr(), _indexWriter(), _rSearchView(), _rFeedView(), _configurer(_iSummaryMgr, _rSearchView, _rFeedView, ctx._queryLimiter, ctx._clock, getSubDbName(), ctx._fastUpdCtx._storeOnlyCtx._owner.getDistributionKey()), _numSearcherThreads(cfg._numSearcherThreads), _warmupExecutor(ctx._warmupExecutor) { } SearchableDocSubDB::~SearchableDocSubDB() { // XXX: Disk index wrappers should not live longer than index manager // which owns map of active disk indexes. clearViews(); } void SearchableDocSubDB::syncViews() { _iSearchView.set(_rSearchView.get()); _iFeedView.set(_rFeedView.get()); _owner.syncFeedView(); } SerialNum SearchableDocSubDB::getOldestFlushedSerial() { SerialNum lowest(Parent::getOldestFlushedSerial()); lowest = std::min(lowest, _indexMgr->getFlushedSerialNum()); return lowest; } SerialNum SearchableDocSubDB::getNewestFlushedSerial() { SerialNum highest(Parent::getNewestFlushedSerial()); highest = std::max(highest, _indexMgr->getFlushedSerialNum()); return highest; } initializer::InitializerTask::SP SearchableDocSubDB:: createIndexManagerInitializer(const DocumentDBConfig &configSnapshot, const Schema::SP &unionSchema, const ProtonConfig::Index &indexCfg, std::shared_ptr<searchcorespi::IIndexManager::SP> indexManager) const { Schema::SP schema(configSnapshot.getSchemaSP()); vespalib::string vespaIndexDir(_baseDir + "/index"); // Note: const_cast for reconfigurer role return std::make_shared<IndexManagerInitializer> (vespaIndexDir, indexCfg.warmup.time, indexCfg.maxflushed, indexCfg.cache.size, *schema, *unionSchema, const_cast<SearchableDocSubDB &>(*this), _writeService, _warmupExecutor, configSnapshot.getTuneFileDocumentDBSP()->_index, configSnapshot.getTuneFileDocumentDBSP()->_attr, _fileHeaderContext, indexManager); } void SearchableDocSubDB::setupIndexManager(searchcorespi::IIndexManager::SP indexManager) { _indexMgr = indexManager; _indexWriter.reset(new IndexWriter(_indexMgr)); } DocumentSubDbInitializer::UP SearchableDocSubDB:: createInitializer(const DocumentDBConfig &configSnapshot, SerialNum configSerialNum, const Schema::SP &unionSchema, const ProtonConfig::Summary &protonSummaryCfg, const ProtonConfig::Index &indexCfg) const { auto result = Parent::createInitializer(configSnapshot, configSerialNum, unionSchema, protonSummaryCfg, indexCfg); auto indexTask = createIndexManagerInitializer(configSnapshot, unionSchema, indexCfg, result->writableResult(). writableIndexManager()); result->addDependency(indexTask); return result; } void SearchableDocSubDB::setup(const DocumentSubDbInitializerResult &initResult) { Parent::setup(initResult); setupIndexManager(initResult.indexManager()); _docIdLimit.set(_dms->getCommittedDocIdLimit()); } void SearchableDocSubDB:: reconfigureMatchingMetrics(const RankProfilesConfig &cfg) { _metricsWireService.cleanRankProfiles(_metrics); for (const auto &profile : cfg.rankprofile) { search::fef::Properties properties; for (const auto &property : profile.fef.property) { properties.add(property.name, property.value); } size_t numDocIdPartitions = search::fef::indexproperties::matching::NumThreadsPerSearch::lookup(properties); _metricsWireService.addRankProfile(_metrics, profile.name, numDocIdPartitions); } } IReprocessingTask::List SearchableDocSubDB::applyConfig(const DocumentDBConfig &newConfigSnapshot, const DocumentDBConfig &oldConfigSnapshot, SerialNum serialNum, const ReconfigParams params) { IReprocessingTask::List tasks; updateLidReuseDelayer(&newConfigSnapshot); if (params.shouldMatchersChange() && _addMetrics) { reconfigureMatchingMetrics(newConfigSnapshot.getRankProfilesConfig()); } if (params.shouldAttributeManagerChange()) { proton::IAttributeManager::SP oldMgr = getAttributeManager(); AttributeCollectionSpec::UP attrSpec = createAttributeSpec(newConfigSnapshot.getAttributesConfig(), serialNum); IReprocessingInitializer::UP initializer = _configurer.reconfigure(newConfigSnapshot, oldConfigSnapshot, *attrSpec, params); if (initializer.get() != nullptr && initializer->hasReprocessors()) { tasks.push_back(IReprocessingTask::SP(createReprocessingTask(*initializer, newConfigSnapshot.getDocumentTypeRepoSP()).release())); } proton::IAttributeManager::SP newMgr = getAttributeManager(); if (_addMetrics) { reconfigureAttributeMetrics(*newMgr, *oldMgr); } } else { _configurer.reconfigure(newConfigSnapshot, oldConfigSnapshot, params); } syncViews(); return tasks; } void SearchableDocSubDB::initViews(const DocumentDBConfig &configSnapshot, const SessionManager::SP &sessionManager) { assert(_writeService.master().isCurrentThread()); AttributeManager::SP attrMgr = getAndResetInitAttributeManager(); const Schema::SP &schema = configSnapshot.getSchemaSP(); const IIndexManager::SP &indexMgr = getIndexManager(); Matchers::SP matchers(_configurer. createMatchers(schema, configSnapshot.getRankProfilesConfig()). release()); MatchView::SP matchView(new MatchView(matchers, indexMgr->getSearchable(), attrMgr, sessionManager, _metaStoreCtx, _docIdLimit)); _rSearchView.set(SearchView::SP( new SearchView( getSummaryManager()->createSummarySetup( configSnapshot.getSummaryConfig(), configSnapshot.getSummarymapConfig(), configSnapshot.getJuniperrcConfig(), configSnapshot.getDocumentTypeRepoSP(), matchView->getAttributeManager()), matchView))); IAttributeWriter::SP attrWriter(new AttributeWriter(attrMgr)); { vespalib::LockGuard guard(_configLock); initFeedView(attrWriter, configSnapshot); } if (_addMetrics) { reconfigureMatchingMetrics(configSnapshot.getRankProfilesConfig()); } } void SearchableDocSubDB::initFeedView(const IAttributeWriter::SP &attrWriter, const DocumentDBConfig &configSnapshot) { assert(_writeService.master().isCurrentThread()); SearchableFeedView::UP feedView(new SearchableFeedView(getStoreOnlyFeedViewContext(configSnapshot), getFeedViewPersistentParams(), FastAccessFeedView::Context(attrWriter, _docIdLimit), SearchableFeedView::Context(getIndexWriter()))); // XXX: Not exception safe. _rFeedView.set(SearchableFeedView::SP(feedView.release())); syncViews(); } /** * Handle reconfigure caused by index manager changing state. * * Flush engine is disabled (for all document dbs) during initial replay and * recovery feed modes, the flush engine has not started. For a resurrected * document type, flushing might occur during replay. */ bool SearchableDocSubDB:: reconfigure(vespalib::Closure0<bool>::UP closure) { assert(_writeService.master().isCurrentThread()); _writeService.sync(); // Everything should be quiet now. SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); bool ret = true; if (closure.get() != NULL) ret = closure->call(); // Perform index manager reconfiguration now reconfigureIndexSearchable(); return ret; } void SearchableDocSubDB::reconfigureIndexSearchable() { vespalib::LockGuard guard(_configLock); // Create new views as needed. _configurer.reconfigureIndexSearchable(); // Activate new feed view at once syncViews(); } IFlushTarget::List SearchableDocSubDB::getFlushTargetsInternal() { IFlushTarget::List ret(Parent::getFlushTargetsInternal()); IFlushTarget::List tmp = _indexMgr->getFlushTargets(); ret.insert(ret.end(), tmp.begin(), tmp.end()); return ret; } void SearchableDocSubDB::wipeHistory(SerialNum wipeSerial, const Schema &newHistorySchema, const Schema &wipeSchema) { assert(_writeService.master().isCurrentThread()); SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); _indexMgr->wipeHistory(wipeSerial, newHistorySchema); reconfigureIndexSearchable(); getAttributeManager()->wipeHistory(wipeSchema); } void SearchableDocSubDB::setIndexSchema(const Schema::SP &schema, const Schema::SP &fusionSchema) { assert(_writeService.master().isCurrentThread()); SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); _indexMgr->setSchema(*schema, *fusionSchema); reconfigureIndexSearchable(); } size_t SearchableDocSubDB::getNumActiveDocs() const { return _metaStoreCtx->getReadGuard()->get().getNumActiveLids(); } search::SearchableStats SearchableDocSubDB::getSearchableStats() const { return _indexMgr->getSearchableStats(); } IDocumentRetriever::UP SearchableDocSubDB::getDocumentRetriever() { return IDocumentRetriever::UP(new FastAccessDocumentRetriever(_rFeedView.get(), _rSearchView.get()->getAttributeManager())); } MatchingStats SearchableDocSubDB::getMatcherStats(const vespalib::string &rankProfile) const { return _rSearchView.get()->getMatcherStats(rankProfile); } void SearchableDocSubDB::updateLidReuseDelayer(const LidReuseDelayerConfig &config) { Parent::updateLidReuseDelayer(config); /* * The lid reuse delayer should not have any pending lids stored at this * time, since DocumentDB::applyConfig() calls forceCommit() on the * feed view before applying the new config to the sub dbs. */ _lidReuseDelayer->setHasIndexedFields(config.hasIndexedFields()); } } // namespace proton <commit_msg>Include fast_access_document_retriever.h<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/log/log.h> LOG_SETUP(".proton.server.searchabledocsubdb"); #include "searchabledocsubdb.h" #include "fast_access_document_retriever.h" #include <vespa/searchcore/proton/attribute/attribute_writer.h> #include <vespa/searchcore/proton/flushengine/threadedflushtarget.h> #include <vespa/searchcore/proton/index/index_manager_initializer.h> #include <vespa/searchcore/proton/index/index_writer.h> #include <vespa/searchcore/proton/metrics/legacy_documentdb_metrics.h> #include <vespa/searchcore/proton/metrics/metricswireservice.h> #include <vespa/searchcorespi/plugin/iindexmanagerfactory.h> #include <vespa/searchlib/common/indexmetainfo.h> #include <vespa/vespalib/io/fileutil.h> #include <vespa/vespalib/util/closuretask.h> using vespa::config::search::AttributesConfig; using vespa::config::search::RankProfilesConfig; using vespa::config::search::core::ProtonConfig; using proton::matching::MatchingStats; using proton::matching::SessionManager; using search::AttributeGuard; using search::AttributeVector; using search::GrowStrategy; using search::TuneFileDocumentDB; using search::index::Schema; using search::SerialNum; using searchcorespi::IndexManagerConfig; using searchcorespi::index::IndexMaintainerConfig; using searchcorespi::index::IndexMaintainerContext; using vespalib::IllegalStateException; using vespalib::ThreadStackExecutorBase; using namespace searchcorespi; namespace proton { SearchableDocSubDB::SearchableDocSubDB(const Config &cfg, const Context &ctx) : FastAccessDocSubDB(cfg._fastUpdCfg, ctx._fastUpdCtx), IIndexManager::Reconfigurer(), _indexMgr(), _indexWriter(), _rSearchView(), _rFeedView(), _configurer(_iSummaryMgr, _rSearchView, _rFeedView, ctx._queryLimiter, ctx._clock, getSubDbName(), ctx._fastUpdCtx._storeOnlyCtx._owner.getDistributionKey()), _numSearcherThreads(cfg._numSearcherThreads), _warmupExecutor(ctx._warmupExecutor) { } SearchableDocSubDB::~SearchableDocSubDB() { // XXX: Disk index wrappers should not live longer than index manager // which owns map of active disk indexes. clearViews(); } void SearchableDocSubDB::syncViews() { _iSearchView.set(_rSearchView.get()); _iFeedView.set(_rFeedView.get()); _owner.syncFeedView(); } SerialNum SearchableDocSubDB::getOldestFlushedSerial() { SerialNum lowest(Parent::getOldestFlushedSerial()); lowest = std::min(lowest, _indexMgr->getFlushedSerialNum()); return lowest; } SerialNum SearchableDocSubDB::getNewestFlushedSerial() { SerialNum highest(Parent::getNewestFlushedSerial()); highest = std::max(highest, _indexMgr->getFlushedSerialNum()); return highest; } initializer::InitializerTask::SP SearchableDocSubDB:: createIndexManagerInitializer(const DocumentDBConfig &configSnapshot, const Schema::SP &unionSchema, const ProtonConfig::Index &indexCfg, std::shared_ptr<searchcorespi::IIndexManager::SP> indexManager) const { Schema::SP schema(configSnapshot.getSchemaSP()); vespalib::string vespaIndexDir(_baseDir + "/index"); // Note: const_cast for reconfigurer role return std::make_shared<IndexManagerInitializer> (vespaIndexDir, indexCfg.warmup.time, indexCfg.maxflushed, indexCfg.cache.size, *schema, *unionSchema, const_cast<SearchableDocSubDB &>(*this), _writeService, _warmupExecutor, configSnapshot.getTuneFileDocumentDBSP()->_index, configSnapshot.getTuneFileDocumentDBSP()->_attr, _fileHeaderContext, indexManager); } void SearchableDocSubDB::setupIndexManager(searchcorespi::IIndexManager::SP indexManager) { _indexMgr = indexManager; _indexWriter.reset(new IndexWriter(_indexMgr)); } DocumentSubDbInitializer::UP SearchableDocSubDB:: createInitializer(const DocumentDBConfig &configSnapshot, SerialNum configSerialNum, const Schema::SP &unionSchema, const ProtonConfig::Summary &protonSummaryCfg, const ProtonConfig::Index &indexCfg) const { auto result = Parent::createInitializer(configSnapshot, configSerialNum, unionSchema, protonSummaryCfg, indexCfg); auto indexTask = createIndexManagerInitializer(configSnapshot, unionSchema, indexCfg, result->writableResult(). writableIndexManager()); result->addDependency(indexTask); return result; } void SearchableDocSubDB::setup(const DocumentSubDbInitializerResult &initResult) { Parent::setup(initResult); setupIndexManager(initResult.indexManager()); _docIdLimit.set(_dms->getCommittedDocIdLimit()); } void SearchableDocSubDB:: reconfigureMatchingMetrics(const RankProfilesConfig &cfg) { _metricsWireService.cleanRankProfiles(_metrics); for (const auto &profile : cfg.rankprofile) { search::fef::Properties properties; for (const auto &property : profile.fef.property) { properties.add(property.name, property.value); } size_t numDocIdPartitions = search::fef::indexproperties::matching::NumThreadsPerSearch::lookup(properties); _metricsWireService.addRankProfile(_metrics, profile.name, numDocIdPartitions); } } IReprocessingTask::List SearchableDocSubDB::applyConfig(const DocumentDBConfig &newConfigSnapshot, const DocumentDBConfig &oldConfigSnapshot, SerialNum serialNum, const ReconfigParams params) { IReprocessingTask::List tasks; updateLidReuseDelayer(&newConfigSnapshot); if (params.shouldMatchersChange() && _addMetrics) { reconfigureMatchingMetrics(newConfigSnapshot.getRankProfilesConfig()); } if (params.shouldAttributeManagerChange()) { proton::IAttributeManager::SP oldMgr = getAttributeManager(); AttributeCollectionSpec::UP attrSpec = createAttributeSpec(newConfigSnapshot.getAttributesConfig(), serialNum); IReprocessingInitializer::UP initializer = _configurer.reconfigure(newConfigSnapshot, oldConfigSnapshot, *attrSpec, params); if (initializer.get() != nullptr && initializer->hasReprocessors()) { tasks.push_back(IReprocessingTask::SP(createReprocessingTask(*initializer, newConfigSnapshot.getDocumentTypeRepoSP()).release())); } proton::IAttributeManager::SP newMgr = getAttributeManager(); if (_addMetrics) { reconfigureAttributeMetrics(*newMgr, *oldMgr); } } else { _configurer.reconfigure(newConfigSnapshot, oldConfigSnapshot, params); } syncViews(); return tasks; } void SearchableDocSubDB::initViews(const DocumentDBConfig &configSnapshot, const SessionManager::SP &sessionManager) { assert(_writeService.master().isCurrentThread()); AttributeManager::SP attrMgr = getAndResetInitAttributeManager(); const Schema::SP &schema = configSnapshot.getSchemaSP(); const IIndexManager::SP &indexMgr = getIndexManager(); Matchers::SP matchers(_configurer. createMatchers(schema, configSnapshot.getRankProfilesConfig()). release()); MatchView::SP matchView(new MatchView(matchers, indexMgr->getSearchable(), attrMgr, sessionManager, _metaStoreCtx, _docIdLimit)); _rSearchView.set(SearchView::SP( new SearchView( getSummaryManager()->createSummarySetup( configSnapshot.getSummaryConfig(), configSnapshot.getSummarymapConfig(), configSnapshot.getJuniperrcConfig(), configSnapshot.getDocumentTypeRepoSP(), matchView->getAttributeManager()), matchView))); IAttributeWriter::SP attrWriter(new AttributeWriter(attrMgr)); { vespalib::LockGuard guard(_configLock); initFeedView(attrWriter, configSnapshot); } if (_addMetrics) { reconfigureMatchingMetrics(configSnapshot.getRankProfilesConfig()); } } void SearchableDocSubDB::initFeedView(const IAttributeWriter::SP &attrWriter, const DocumentDBConfig &configSnapshot) { assert(_writeService.master().isCurrentThread()); SearchableFeedView::UP feedView(new SearchableFeedView(getStoreOnlyFeedViewContext(configSnapshot), getFeedViewPersistentParams(), FastAccessFeedView::Context(attrWriter, _docIdLimit), SearchableFeedView::Context(getIndexWriter()))); // XXX: Not exception safe. _rFeedView.set(SearchableFeedView::SP(feedView.release())); syncViews(); } /** * Handle reconfigure caused by index manager changing state. * * Flush engine is disabled (for all document dbs) during initial replay and * recovery feed modes, the flush engine has not started. For a resurrected * document type, flushing might occur during replay. */ bool SearchableDocSubDB:: reconfigure(vespalib::Closure0<bool>::UP closure) { assert(_writeService.master().isCurrentThread()); _writeService.sync(); // Everything should be quiet now. SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); bool ret = true; if (closure.get() != NULL) ret = closure->call(); // Perform index manager reconfiguration now reconfigureIndexSearchable(); return ret; } void SearchableDocSubDB::reconfigureIndexSearchable() { vespalib::LockGuard guard(_configLock); // Create new views as needed. _configurer.reconfigureIndexSearchable(); // Activate new feed view at once syncViews(); } IFlushTarget::List SearchableDocSubDB::getFlushTargetsInternal() { IFlushTarget::List ret(Parent::getFlushTargetsInternal()); IFlushTarget::List tmp = _indexMgr->getFlushTargets(); ret.insert(ret.end(), tmp.begin(), tmp.end()); return ret; } void SearchableDocSubDB::wipeHistory(SerialNum wipeSerial, const Schema &newHistorySchema, const Schema &wipeSchema) { assert(_writeService.master().isCurrentThread()); SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); _indexMgr->wipeHistory(wipeSerial, newHistorySchema); reconfigureIndexSearchable(); getAttributeManager()->wipeHistory(wipeSchema); } void SearchableDocSubDB::setIndexSchema(const Schema::SP &schema, const Schema::SP &fusionSchema) { assert(_writeService.master().isCurrentThread()); SearchView::SP oldSearchView = _rSearchView.get(); IFeedView::SP oldFeedView = _iFeedView.get(); _indexMgr->setSchema(*schema, *fusionSchema); reconfigureIndexSearchable(); } size_t SearchableDocSubDB::getNumActiveDocs() const { return _metaStoreCtx->getReadGuard()->get().getNumActiveLids(); } search::SearchableStats SearchableDocSubDB::getSearchableStats() const { return _indexMgr->getSearchableStats(); } IDocumentRetriever::UP SearchableDocSubDB::getDocumentRetriever() { return IDocumentRetriever::UP(new FastAccessDocumentRetriever(_rFeedView.get(), _rSearchView.get()->getAttributeManager())); } MatchingStats SearchableDocSubDB::getMatcherStats(const vespalib::string &rankProfile) const { return _rSearchView.get()->getMatcherStats(rankProfile); } void SearchableDocSubDB::updateLidReuseDelayer(const LidReuseDelayerConfig &config) { Parent::updateLidReuseDelayer(config); /* * The lid reuse delayer should not have any pending lids stored at this * time, since DocumentDB::applyConfig() calls forceCommit() on the * feed view before applying the new config to the sub dbs. */ _lidReuseDelayer->setHasIndexedFields(config.hasIndexedFields()); } } // namespace proton <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // 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 Google Inc. 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. #include "testing/gtest/include/gtest/gtest.h" #include "base/string_escape.h" TEST(StringEscapeTest, JavascriptDoubleQuote) { static const char* kToEscape = "\b\001aZ\"\\wee"; static const char* kEscaped = "\\b\\x01aZ\\\"\\\\wee"; static const wchar_t* kUToEscape = L"\b\x0001" L"a\x123fZ\"\\wee"; static const char* kUEscaped = "\\b\\x01a\\u123FZ\\\"\\\\wee"; static const char* kUEscapedQuoted = "\"\\b\\x01a\\u123FZ\\\"\\\\wee\""; std::string out; // Test wide unicode escaping out = "testy: "; string_escape::JavascriptDoubleQuote(std::wstring(kUToEscape), false, &out); ASSERT_EQ(std::string("testy: ") + kUEscaped, out); out = "testy: "; string_escape::JavascriptDoubleQuote(std::wstring(kUToEscape), true, &out); ASSERT_EQ(std::string("testy: ") + kUEscapedQuoted, out); // Test null and high bit / negative unicode values std::wstring wstr(L"TeSt"); wstr.push_back(0); wstr.push_back(0xffb1); wstr.push_back(0x00ff); out = "testy: "; string_escape::JavascriptDoubleQuote(wstr, false, &out); ASSERT_EQ("testy: TeSt\\x00\\uFFB1\\xFF", out); // Test escaping of 7bit ascii out = "testy: "; string_escape::JavascriptDoubleQuote(std::string(kToEscape), false, &out); ASSERT_EQ(std::string("testy: ") + kEscaped, out); // Test null, non-printable, and non-7bit std::string str("TeSt"); str.push_back(0); str.push_back(15); str.push_back(127); str.push_back(-16); str.push_back(-128); str.push_back('!'); out = "testy: "; string_escape::JavascriptDoubleQuote(str, false, &out); ASSERT_EQ("testy: TeSt\\x00\\x0F\\x7F\xf0\x80!", out); } <commit_msg>Add a few tests to string_escape improving code coverage.<commit_after>// Copyright 2008, Google Inc. // 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 Google Inc. 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. #include "testing/gtest/include/gtest/gtest.h" #include "base/string_escape.h" TEST(StringEscapeTest, JavascriptDoubleQuote) { static const char* kToEscape = "\b\001aZ\"\\wee"; static const char* kEscaped = "\\b\\x01aZ\\\"\\\\wee"; static const char* kEscapedQuoted = "\"\\b\\x01aZ\\\"\\\\wee\""; static const wchar_t* kUToEscape = L"\b\x0001" L"a\x123fZ\"\\wee"; static const char* kUEscaped = "\\b\\x01a\\u123FZ\\\"\\\\wee"; static const char* kUEscapedQuoted = "\"\\b\\x01a\\u123FZ\\\"\\\\wee\""; std::string out; // Test wide unicode escaping out = "testy: "; string_escape::JavascriptDoubleQuote(std::wstring(kUToEscape), false, &out); ASSERT_EQ(std::string("testy: ") + kUEscaped, out); out = "testy: "; string_escape::JavascriptDoubleQuote(std::wstring(kUToEscape), true, &out); ASSERT_EQ(std::string("testy: ") + kUEscapedQuoted, out); // Test null and high bit / negative unicode values std::wstring wstr(L"TeSt"); wstr.push_back(0); wstr.push_back(0xffb1); wstr.push_back(0x00ff); out = "testy: "; string_escape::JavascriptDoubleQuote(wstr, false, &out); ASSERT_EQ("testy: TeSt\\x00\\uFFB1\\xFF", out); // Test escaping of 7bit ascii out = "testy: "; string_escape::JavascriptDoubleQuote(std::string(kToEscape), false, &out); ASSERT_EQ(std::string("testy: ") + kEscaped, out); out = "testy: "; string_escape::JavascriptDoubleQuote(std::string(kToEscape), true, &out); ASSERT_EQ(std::string("testy: ") + kEscapedQuoted, out); // Test null, non-printable, and non-7bit std::string str("TeSt"); str.push_back(0); str.push_back(15); str.push_back(127); str.push_back(-16); str.push_back(-128); str.push_back('!'); out = "testy: "; string_escape::JavascriptDoubleQuote(str, false, &out); ASSERT_EQ("testy: TeSt\\x00\\x0F\\x7F\xf0\x80!", out); // Test escape sequences out = "testy: "; string_escape::JavascriptDoubleQuote("a\b\f\n\r\t\v\1\\.\"z", false, &out); ASSERT_EQ("testy: a\\b\\f\\n\\r\\t\\v\\x01\\\\.\\\"z", out); } <|endoftext|>
<commit_before>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/SimpleString.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestMemoryAllocator.h" TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; TestMemoryAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULL) return defaultNewArrayAllocator(); return stringAllocator_; } void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) { stringAllocator_ = allocator; } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ char* SimpleString::allocStringBuffer(size_t _size) { return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); } void SimpleString::deallocStringBuffer(char* str) { getStringAllocator()->free_memory(str, __FILE__, __LINE__); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1); empty[0] = '\0'; return empty; } SimpleString::SimpleString(const char *otherBuffer) { if (otherBuffer == 0) { buffer_ = getEmptyString(); } else { size_t len = PlatformSpecificStrLen(otherBuffer) + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, otherBuffer); } } SimpleString::SimpleString(const char *other, size_t repeatCount) { size_t len = PlatformSpecificStrLen(other) * repeatCount + 1; buffer_ = allocStringBuffer(len); char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { PlatformSpecificStrCpy(next, other); next += PlatformSpecificStrLen(other); } *next = 0; } SimpleString::SimpleString(const SimpleString& other) { size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) { deallocStringBuffer(buffer_); size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrCpy(buffer_, other.buffer_); } return *this; } bool SimpleString::contains(const SimpleString& other) const { //strstr on some machines does not handle "" //the right way. "" should be found in any string if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; } bool SimpleString::containsNoCase(const SimpleString& other) const { return toLower().contains(other.toLower()); } bool SimpleString::startsWith(const SimpleString& other) const { if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; } bool SimpleString::endsWith(const SimpleString& other) const { size_t buffer_length = PlatformSpecificStrLen(buffer_); size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); if (other_buffer_length == 0) return true; if (buffer_length == 0) return false; if (buffer_length < other_buffer_length) return false; return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; char* str = buffer_; while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { num++; str++; } return num; } void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const { size_t num = count(delimiter); size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; col.allocate(num + extraEndToken); char* str = buffer_; char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; size_t len = (size_t) (str - prev); char* sub = allocStringBuffer(len + 1); PlatformSpecificStrNCpy(sub, prev, len); sub[len] = '\0'; col[i] = sub; deallocStringBuffer(sub); } if (extraEndToken) { col[num] = str; } } void SimpleString::replace(char to, char with) { size_t s = size(); for (size_t i = 0; i < s; i++) { if (buffer_[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); size_t len = size(); size_t tolen = PlatformSpecificStrLen(to); size_t withlen = PlatformSpecificStrLen(with); size_t newsize = len + (withlen * c) - (tolen * c) + 1; if (newsize) { char* newbuf = allocStringBuffer(newsize); for (size_t i = 0, j = 0; i < len;) { if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { PlatformSpecificStrNCpy(&newbuf[j], with, withlen); j += withlen; i += tolen; } else { newbuf[j] = buffer_[i]; j++; i++; } } deallocStringBuffer(buffer_); buffer_ = newbuf; buffer_[newsize - 1] = '\0'; } else { buffer_ = getEmptyString(); buffer_[0] = '\0'; } } SimpleString SimpleString::toLower() const { SimpleString str(*this); size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); return str; } const char *SimpleString::asCharString() const { return buffer_; } size_t SimpleString::size() const { return PlatformSpecificStrLen(buffer_); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocStringBuffer(buffer_); } bool operator==(const SimpleString& left, const SimpleString& right) { return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); } bool SimpleString::equalsNoCase(const SimpleString& str) const { return toLower() == str.toLower(); } bool operator!=(const SimpleString& left, const SimpleString& right) { return !(left == right); } SimpleString SimpleString::operator+(const SimpleString& rhs) { SimpleString t(buffer_); t += rhs.buffer_; return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.buffer_); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t len = this->size() + PlatformSpecificStrLen(rhs) + 1; char* tbuffer = allocStringBuffer(len); PlatformSpecificStrCpy(tbuffer, this->buffer_); PlatformSpecificStrCat(tbuffer, rhs); deallocStringBuffer(buffer_); buffer_ = tbuffer; return *this; } void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) { if (str1.size() > str2.size()) { padStringsToSameLength(str2, str1, padCharacter); return; } char pad[2]; pad[0] = padCharacter; pad[1] = 0; str1 = SimpleString(pad, str2.size() - str1.size()) + str1; } SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; SimpleString newString = buffer_ + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } char SimpleString::at(int pos) const { return buffer_[pos]; } int SimpleString::find(char ch) const { return findFrom(0, ch); } int SimpleString::findFrom(size_t starting_position, char ch) const { size_t length = size(); for (size_t i = starting_position; i < length; i++) if (buffer_[i] == ch) return (int) i; return -1; } SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const { int beginPos = find(startChar); if (beginPos < 0) return ""; int endPos = findFrom((size_t)beginPos, lastExcludedChar); if (endPos == -1) return subString((size_t)beginPos, size()); return subString((size_t)beginPos, (size_t) (endPos - beginPos)); } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULL || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : "(null)"; } SimpleString StringFrom(int value) { return StringFromFormat("%d", value); } SimpleString StringFrom(long value) { return StringFromFormat("%ld", value); } SimpleString StringFrom(const void* value) { return SimpleString("0x") + HexStringFrom(value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", value); } static long convertPointerToLongValue(const void* value) { /* * This way of converting also can convert a 64bit pointer in a 32bit integer by truncating. * This isn't the right way to convert pointers values and need to change by implementing a * proper portable way to convert pointers to strings. */ long* long_value = (long*) &value; return *long_value; } SimpleString HexStringFrom(const void* value) { return StringFromFormat("%lx", convertPointerToLongValue(value)); } SimpleString StringFrom(double value, int precision) { return StringFromFormat("%.*g", precision, value); } SimpleString StringFrom(char value) { return StringFromFormat("%c", value); } SimpleString StringFrom(const SimpleString& value) { return SimpleString(value); } SimpleString StringFromFormat(const char* format, ...) { SimpleString resultString; va_list arguments; va_start(arguments, format); resultString = VStringFromFormat(format, arguments); va_end(arguments); return resultString; } SimpleString StringFrom(unsigned int i) { return StringFromFormat("%10u (0x%08x)", i, i); } #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } SimpleString StringFrom(unsigned long i) { return StringFromFormat("%lu (0x%lx)", i, i); } #endif //Kludge to get a va_copy in VC++ V6 #ifndef va_copy #define va_copy(copy, original) copy = original; #endif SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; va_copy(argsCopy, args); enum { sizeOfdefaultBuffer = 100 }; char defaultBuffer[sizeOfdefaultBuffer]; SimpleString resultString; size_t size = (size_t)PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); if (size < sizeOfdefaultBuffer) { resultString = SimpleString(defaultBuffer); } else { size_t newBufferSize = size + 1; char* newBuffer = SimpleString::allocStringBuffer(newBufferSize); PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); resultString = SimpleString(newBuffer); SimpleString::deallocStringBuffer(newBuffer); } va_end(argsCopy); return resultString; } SimpleStringCollection::SimpleStringCollection() { collection_ = 0; size_ = 0; } void SimpleStringCollection::allocate(size_t _size) { if (collection_) delete[] collection_; size_ = _size; collection_ = new SimpleString[size_]; } SimpleStringCollection::~SimpleStringCollection() { delete[] (collection_); } size_t SimpleStringCollection::size() const { return size_; } SimpleString& SimpleStringCollection::operator[](size_t index) { if (index >= size_) { empty_ = ""; return empty_; } return collection_[index]; } <commit_msg>Converted StrCpy into StrNCpy<commit_after>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/SimpleString.h" #include "CppUTest/PlatformSpecificFunctions.h" #include "CppUTest/TestMemoryAllocator.h" TestMemoryAllocator* SimpleString::stringAllocator_ = NULL; TestMemoryAllocator* SimpleString::getStringAllocator() { if (stringAllocator_ == NULL) return defaultNewArrayAllocator(); return stringAllocator_; } void SimpleString::setStringAllocator(TestMemoryAllocator* allocator) { stringAllocator_ = allocator; } /* Avoid using the memory leak detector INSIDE SimpleString as its used inside the detector */ char* SimpleString::allocStringBuffer(size_t _size) { return getStringAllocator()->alloc_memory(_size, __FILE__, __LINE__); } void SimpleString::deallocStringBuffer(char* str) { getStringAllocator()->free_memory(str, __FILE__, __LINE__); } char* SimpleString::getEmptyString() const { char* empty = allocStringBuffer(1); empty[0] = '\0'; return empty; } SimpleString::SimpleString(const char *otherBuffer) { if (otherBuffer == 0) { buffer_ = getEmptyString(); } else { size_t len = PlatformSpecificStrLen(otherBuffer) + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrNCpy(buffer_, otherBuffer, len); } } SimpleString::SimpleString(const char *other, size_t repeatCount) { size_t otherStringLength = PlatformSpecificStrLen(other); size_t len = otherStringLength * repeatCount + 1; buffer_ = allocStringBuffer(len); char* next = buffer_; for (size_t i = 0; i < repeatCount; i++) { PlatformSpecificStrNCpy(next, other, otherStringLength); next += otherStringLength; } *next = 0; } SimpleString::SimpleString(const SimpleString& other) { size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrNCpy(buffer_, other.buffer_, len); } SimpleString& SimpleString::operator=(const SimpleString& other) { if (this != &other) { deallocStringBuffer(buffer_); size_t len = other.size() + 1; buffer_ = allocStringBuffer(len); PlatformSpecificStrNCpy(buffer_, other.buffer_, len); } return *this; } bool SimpleString::contains(const SimpleString& other) const { //strstr on some machines does not handle "" //the right way. "" should be found in any string if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) != 0; } bool SimpleString::containsNoCase(const SimpleString& other) const { return toLower().contains(other.toLower()); } bool SimpleString::startsWith(const SimpleString& other) const { if (PlatformSpecificStrLen(other.buffer_) == 0) return true; else if (PlatformSpecificStrLen(buffer_) == 0) return false; else return PlatformSpecificStrStr(buffer_, other.buffer_) == buffer_; } bool SimpleString::endsWith(const SimpleString& other) const { size_t buffer_length = PlatformSpecificStrLen(buffer_); size_t other_buffer_length = PlatformSpecificStrLen(other.buffer_); if (other_buffer_length == 0) return true; if (buffer_length == 0) return false; if (buffer_length < other_buffer_length) return false; return PlatformSpecificStrCmp(buffer_ + buffer_length - other_buffer_length, other.buffer_) == 0; } size_t SimpleString::count(const SimpleString& substr) const { size_t num = 0; char* str = buffer_; while ((str = PlatformSpecificStrStr(str, substr.buffer_))) { num++; str++; } return num; } void SimpleString::split(const SimpleString& delimiter, SimpleStringCollection& col) const { size_t num = count(delimiter); size_t extraEndToken = (endsWith(delimiter)) ? 0 : 1U; col.allocate(num + extraEndToken); char* str = buffer_; char* prev; for (size_t i = 0; i < num; ++i) { prev = str; str = PlatformSpecificStrStr(str, delimiter.buffer_) + 1; size_t len = (size_t) (str - prev); char* sub = allocStringBuffer(len + 1); PlatformSpecificStrNCpy(sub, prev, len); sub[len] = '\0'; col[i] = sub; deallocStringBuffer(sub); } if (extraEndToken) { col[num] = str; } } void SimpleString::replace(char to, char with) { size_t s = size(); for (size_t i = 0; i < s; i++) { if (buffer_[i] == to) buffer_[i] = with; } } void SimpleString::replace(const char* to, const char* with) { size_t c = count(to); size_t len = size(); size_t tolen = PlatformSpecificStrLen(to); size_t withlen = PlatformSpecificStrLen(with); size_t newsize = len + (withlen * c) - (tolen * c) + 1; if (newsize) { char* newbuf = allocStringBuffer(newsize); for (size_t i = 0, j = 0; i < len;) { if (PlatformSpecificStrNCmp(&buffer_[i], to, tolen) == 0) { PlatformSpecificStrNCpy(&newbuf[j], with, withlen); j += withlen; i += tolen; } else { newbuf[j] = buffer_[i]; j++; i++; } } deallocStringBuffer(buffer_); buffer_ = newbuf; buffer_[newsize - 1] = '\0'; } else { buffer_ = getEmptyString(); buffer_[0] = '\0'; } } SimpleString SimpleString::toLower() const { SimpleString str(*this); size_t str_size = str.size(); for (size_t i = 0; i < str_size; i++) str.buffer_[i] = PlatformSpecificToLower(str.buffer_[i]); return str; } const char *SimpleString::asCharString() const { return buffer_; } size_t SimpleString::size() const { return PlatformSpecificStrLen(buffer_); } bool SimpleString::isEmpty() const { return size() == 0; } SimpleString::~SimpleString() { deallocStringBuffer(buffer_); } bool operator==(const SimpleString& left, const SimpleString& right) { return 0 == PlatformSpecificStrCmp(left.asCharString(), right.asCharString()); } bool SimpleString::equalsNoCase(const SimpleString& str) const { return toLower() == str.toLower(); } bool operator!=(const SimpleString& left, const SimpleString& right) { return !(left == right); } SimpleString SimpleString::operator+(const SimpleString& rhs) { SimpleString t(buffer_); t += rhs.buffer_; return t; } SimpleString& SimpleString::operator+=(const SimpleString& rhs) { return operator+=(rhs.buffer_); } SimpleString& SimpleString::operator+=(const char* rhs) { size_t originalSize = this->size(); size_t additionalStringSize = PlatformSpecificStrLen(rhs); size_t totalSizeOfNewBuffer = originalSize + additionalStringSize + 1; char* tbuffer = allocStringBuffer(totalSizeOfNewBuffer); PlatformSpecificStrNCpy(tbuffer, this->buffer_, originalSize); PlatformSpecificStrNCpy(tbuffer + originalSize, rhs, additionalStringSize + 1); deallocStringBuffer(buffer_); buffer_ = tbuffer; return *this; } void SimpleString::padStringsToSameLength(SimpleString& str1, SimpleString& str2, char padCharacter) { if (str1.size() > str2.size()) { padStringsToSameLength(str2, str1, padCharacter); return; } char pad[2]; pad[0] = padCharacter; pad[1] = 0; str1 = SimpleString(pad, str2.size() - str1.size()) + str1; } SimpleString SimpleString::subString(size_t beginPos, size_t amount) const { if (beginPos > size()-1) return ""; SimpleString newString = buffer_ + beginPos; if (newString.size() > amount) newString.buffer_[amount] = '\0'; return newString; } char SimpleString::at(int pos) const { return buffer_[pos]; } int SimpleString::find(char ch) const { return findFrom(0, ch); } int SimpleString::findFrom(size_t starting_position, char ch) const { size_t length = size(); for (size_t i = starting_position; i < length; i++) if (buffer_[i] == ch) return (int) i; return -1; } SimpleString SimpleString::subStringFromTill(char startChar, char lastExcludedChar) const { int beginPos = find(startChar); if (beginPos < 0) return ""; int endPos = findFrom((size_t)beginPos, lastExcludedChar); if (endPos == -1) return subString((size_t)beginPos, size()); return subString((size_t)beginPos, (size_t) (endPos - beginPos)); } void SimpleString::copyToBuffer(char* bufferToCopy, size_t bufferSize) const { if (bufferToCopy == NULL || bufferSize == 0) return; size_t sizeToCopy = (bufferSize-1 < size()) ? bufferSize-1 : size(); PlatformSpecificStrNCpy(bufferToCopy, buffer_, sizeToCopy); bufferToCopy[sizeToCopy] = '\0'; } SimpleString StringFrom(bool value) { return SimpleString(StringFromFormat("%s", value ? "true" : "false")); } SimpleString StringFrom(const char *value) { return SimpleString(value); } SimpleString StringFromOrNull(const char * expected) { return (expected) ? StringFrom(expected) : "(null)"; } SimpleString StringFrom(int value) { return StringFromFormat("%d", value); } SimpleString StringFrom(long value) { return StringFromFormat("%ld", value); } SimpleString StringFrom(const void* value) { return SimpleString("0x") + HexStringFrom(value); } SimpleString HexStringFrom(long value) { return StringFromFormat("%lx", value); } static long convertPointerToLongValue(const void* value) { /* * This way of converting also can convert a 64bit pointer in a 32bit integer by truncating. * This isn't the right way to convert pointers values and need to change by implementing a * proper portable way to convert pointers to strings. */ long* long_value = (long*) &value; return *long_value; } SimpleString HexStringFrom(const void* value) { return StringFromFormat("%lx", convertPointerToLongValue(value)); } SimpleString StringFrom(double value, int precision) { return StringFromFormat("%.*g", precision, value); } SimpleString StringFrom(char value) { return StringFromFormat("%c", value); } SimpleString StringFrom(const SimpleString& value) { return SimpleString(value); } SimpleString StringFromFormat(const char* format, ...) { SimpleString resultString; va_list arguments; va_start(arguments, format); resultString = VStringFromFormat(format, arguments); va_end(arguments); return resultString; } SimpleString StringFrom(unsigned int i) { return StringFromFormat("%10u (0x%08x)", i, i); } #if CPPUTEST_USE_STD_CPP_LIB #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } SimpleString StringFrom(unsigned long i) { return StringFromFormat("%lu (0x%lx)", i, i); } #endif //Kludge to get a va_copy in VC++ V6 #ifndef va_copy #define va_copy(copy, original) copy = original; #endif SimpleString VStringFromFormat(const char* format, va_list args) { va_list argsCopy; va_copy(argsCopy, args); enum { sizeOfdefaultBuffer = 100 }; char defaultBuffer[sizeOfdefaultBuffer]; SimpleString resultString; size_t size = (size_t)PlatformSpecificVSNprintf(defaultBuffer, sizeOfdefaultBuffer, format, args); if (size < sizeOfdefaultBuffer) { resultString = SimpleString(defaultBuffer); } else { size_t newBufferSize = size + 1; char* newBuffer = SimpleString::allocStringBuffer(newBufferSize); PlatformSpecificVSNprintf(newBuffer, newBufferSize, format, argsCopy); resultString = SimpleString(newBuffer); SimpleString::deallocStringBuffer(newBuffer); } va_end(argsCopy); return resultString; } SimpleStringCollection::SimpleStringCollection() { collection_ = 0; size_ = 0; } void SimpleStringCollection::allocate(size_t _size) { if (collection_) delete[] collection_; size_ = _size; collection_ = new SimpleString[size_]; } SimpleStringCollection::~SimpleStringCollection() { delete[] (collection_); } size_t SimpleStringCollection::size() const { return size_; } SimpleString& SimpleStringCollection::operator[](size_t index) { if (index >= size_) { empty_ = ""; return empty_; } return collection_[index]; } <|endoftext|>
<commit_before>#pragma once #include "SuperComponent.hpp" namespace Video { namespace Geometry { class Geometry3D; } } namespace Component { /// %Component providing geometry to an entity. class Mesh : public SuperComponent { public: /// Create new mesh. Mesh(); /// Destructor. ~Mesh() override; /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Geometry data. /** * Default: nullptr */ Video::Geometry::Geometry3D* geometry = nullptr; /// Highlight selection. /** * @return True if selected else false. */ bool GetSelected() const; /// Highlight selection. /** * @param Set true if mesh is selected, else false. */ void SetSelected(bool value); private: /// If mesh is selected in the editor. bool isSelected; }; } <commit_msg>Added proper comments.<commit_after>#pragma once #include "SuperComponent.hpp" namespace Video { namespace Geometry { class Geometry3D; } } namespace Component { /// %Component providing geometry to an entity. class Mesh : public SuperComponent { public: /// Create new mesh. Mesh(); /// Destructor. ~Mesh() override; /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Geometry data. /** * Default: nullptr */ Video::Geometry::Geometry3D* geometry = nullptr; /// Get mesh selection. /** * @return Bool Is this selected or not. */ bool GetSelected() const; /// Set mesh selection. /** * @param Value If selected or not. */ void SetSelected(bool value); private: bool isSelected; }; } <|endoftext|>
<commit_before>//============================================================================ // Name : Monte_carlo.cpp // Author : Rafael // Version : // Copyright : MIT // Description : Hello World in C++, Ansi-style // referencias: // 1 - http://ta.twi.tudelft.nl/mf/users/oosterle/oosterlee/lec8-hit-2009.pdf // 2 - Sadiku. M.N.O - Numeral Techniques in Electromagnetics with MATLAB // 3 - http://ww2.odu.edu/~agodunov/computing/programs/cpp/dmc_int1.cpp // 4 - https://github.com/s9w/articles/blob/master/perf%20cpp%20random.md - comparacao entre os metodos de gerar numeros aleatorios //http://www.cs.dartmouth.edu/~wjarosz/publications/dissertation/appendixA.pdf // AJUDOU SOBRE GERAR DOUBLE: //http://stackoverflow.com/questions/32071721/error-in-using-mt19937-with-random-device-as-static-class-members //http://physics.clarku.edu/courses/125/gtcdraft/chap11.pdf //http://stackoverflow.com/questions/24334012/best-way-to-seed-mt19937-64-for-monte-carlo-simulations // /* Artigos sobre geracao de aleatorios e monte carlo http://journals.aps.org/pre/abstract/10.1103/PhysRevE.75.066701 */ /* Metodos para gerar aleatorios: usado pelo chrome - xorshift128+ XX - Implementado GenerateNumbersXOR.h padrao do c++ 11 - mt19937 XX - Implementado GenerateNumbers.h descrito pelo numerical recipes pg 366- Ran XX - Implementado GenerateNumbersNR.h */ /* * Testar pelo método analitico as integrais * http://www.wolframalpha.com/examples/Integrals.html */ /** Alguns codigos fontes de MonteCarlo * http://ww2.odu.edu/~agodunov/computing/programs/cpp/dmc_int1.cpp * http://ww2.odu.edu/~agodunov/computing/programs/cpp/mc_int_nd.cpp */ /** tipos de metodos para integrar com o MonteCarlo * https://www.unige.ch/sciences/astro/files/2713/8971/4086/3_Paltani_MonteCarlo.pdf * -Strafiel sampling * -Importance sampling */ //============================================================================ /* * Adicionar novas formas de gerar numeros aleatorios * implementar novos metodos de monte carlo, importance * compilar * g++ -Wall -g -std=c++11 MonteCarloIntegration.cpp MonteCarloCrudeN.cpp GenerateNumbersNR.h -o MonteCarlo.o * */ #include <iostream> #include <random> #include <string> #include <math.h> //#include "MonteCarloCrude.h" #include "MonteCarloCrudeN.h" #include <time.h> #include <array> #include <fstream> #include <limits> #include <iomanip> #include <type_traits> #include <algorithm> using namespace std; // prototipo das funcoes /** * * @param x - uma funcao com apenas uma dimensao * @return retorna a funcao */ double funcao(double x); double funcaoN(double x[], int n, double limiteX, double limiteY, double limiteZ, double step); /** * Voce define a funcao que deve ser integrada * @param x Parametro de entrada da funcao * @return */ double funcao(double x) { double y; /** * I = x dx * resultado analitico: "http://www.wolframalpha.com/input/?i=int+x+dx+from+0+to+10" */ y = x; return y; } // classe para comprar numeros de ponto flutuante template<class T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp) { // the machine epsilon has to be scaled to the magnitude of the values used // and multiplied by the desired precision in ULPs (units in the last place) return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp // unless the result is subnormal || std::abs(x-y) < std::numeric_limits<T>::min(); } // estou usando a funcao do Alex Godunov // for (j = 0; j < n; j = j+1) // { // y = y + x[j]; // } // y = pow(y,2); /** resultado analitico * Wolfram: "http://www.wolframalpha.com/input/?i=int+x+%2B+y+%2B+z+dx+dy+dz%2C+x%3D0+to+1%2C+y%3D0+to+1%2C+z%3D0+to+1" */ double funcaoN(double x[], int n, double limiteX, double limiteY, double limiteZ, double step) { double y; /* Funcao antiga // int j; double gama_0 = 2.3562; int a_0 = 5; double c_a = 9.1439; y = 0.0; double raizG_0 = sqrt( pow(x[0],2) + pow(x[1],2) + pow(x[2],2) ); if( raizG_0 == 0 ){ y = a_0; }else if(raizG_0 < 1){ y = a_0 * (( sin(gama_0*raizG_0)) / (gama_0*raizG_0)) ; } else { y = c_a * (( exp( -gama_0*raizG_0)) / ( gama_0*raizG_0)) ; } y = pow(y,2); double raiz_R = sqrt( pow(limiteX - x[0],2) + pow(limiteY - x[1],2) + pow(limiteZ - x[2],2) ); if(raiz_R >= step ){ y/= raiz_R; } else { y/= 2 * step; } /* /* // return y = x[0] + x[1] + x[2]; //return y = pow(x[0],2) + sin(x[1]) * exp(x[2]); */ // y = 2*pow(x[0],2) + 3*pow(x[1],2) + 4*pow(x[2],2); //Valores Calculados para energia e constantes de normalização double e_l0, e_l1, e_l2; double gama1_l0, gama1_l1, gama1_l2, gama2_l0, gama2_l1, gama2_l2; int czao_l0, czao_l1, czao_l2; float azao_l0, azao_l1, azao_l2; e_l0 = 53.7; e_l1 = 198.5; e_l2 = 289.8; gama1_l0 = 2.1973; gama1_l1 = 4.2248; gama1_l2 = 5.1045; gama2_l0 = 5.5800; gama2_l1 = 4.2562; gama2_l2 = 3.1477; czao_l0 = 3; czao_l1 = 6; czao_l2 = 7; azao_l0 = 281779; azao_l1 = 5.9432; azao_l2 = 7.2102; return y; // cout << "x1: "<< x[0] <<endl; // cout << "y1: "<< x[1] <<endl; // cout << "z1: "<< x[2] <<endl; } int main() { clock_t tStart = clock(); // definindo a precisao de quando mostra os resultados cout.precision(5); cout.setf(ios::fixed | ios::showpoint); /** MonteCarlo 1 dimensao // double a, b, montecarlo, erro; // int n; // int ntimes; // a = 0.0; // b = 10.0; // n = 2; // ntimes = 16; // for (int var = 0; var <= ntimes; ++var) { // // montecarlo = MonteCarloCrude::CrudeMonteCarlo(funcao, a, b, n, erro); // // cout <<"N: " << n << " Monte: "<< montecarlo << " Erro:"<< erro << endl; // n = n * 2; // } /** MonteCarlo n dimensoes * Parametros: * numeroIntegrais - quantidade de integrais, ex: dx, dy, dz... * L - Limite superior e inferior do somatorio da integral e limite do x,y,z das variaveis internas * limiteInferior - valor para o limite inferior do somatorio da integral * limiteSuperior - valor para o limite supeior do somatorio da integral * numeroInteracoes - numero de chamadas para o montecarlo, quanto maior melhor, porem quanto maior maior tempo * step - o passo de cada interacao * resultado - valor retornado pelo metodo de montecarlo */ const int numeroIntegrais = 3; int L = 1; double limiteInferior[numeroIntegrais] = { -L, -L, -L}; double limiteSuperior[numeroIntegrais] = { L, L, L}; int numeroInteracoes = 100000; double step=0.5; double limiteX, limiteY, limiteZ; double matrizMonte[int((L/0.25)+1)][int((L/0.25)+1)][int((L/0.25)+1)]; double resultado; int aux_x, aux_y, aux_z; aux_x = 0; aux_y = 0; aux_z = 0; for (limiteX = -L, aux_x=0 ; limiteX <= L; limiteX+= step, ++aux_x) { for (limiteY = -L, aux_y=0 ; limiteY <= L; limiteY+= step, ++aux_y) { for (limiteZ = -L, aux_z=0 ; limiteZ <= L; limiteZ+= step, ++aux_z) { resultado = MonteCarloCrudeN::CrudeMonteCarloN(funcaoN, limiteInferior, limiteSuperior, numeroIntegrais, numeroInteracoes,limiteX, limiteY,limiteZ,step); // cout << "mN: " << mN << " Resul: "<< result << endl; cout << "x " << limiteX << " y "<< limiteY << " z " <<limiteZ << " Resul "<< resultado << endl; // cout << "a_x " << aux_x << " a_y "<< aux_y << " a_z " <<aux_z << endl; matrizMonte[aux_x][aux_y][aux_z] = resultado; } } } //Pegando a hora atual e definindo no nome do arquivo time_t now; struct tm *now_tm; now = time(NULL); now_tm = localtime(&now); int hour = now_tm->tm_hour; int min = now_tm->tm_min; int sec = now_tm->tm_sec; //Criando um arquivo para coloca os dados da matriz X Y Z Resultado ofstream myfile; string arquivoNome = "matriz " + to_string(hour)+ ":" + to_string(min) + ":" + to_string(sec) + ".txt"; myfile.open (arquivoNome); myfile << "X,\t" << "Y,\t" << "Z,\t"<< "Resultado\t" << endl; // escrevendo resultado no arquivo aux_x = 0; aux_y = 0; aux_z = 0; for (limiteX = -L, aux_x=0 ; limiteX <= L; limiteX+= step, ++aux_x) { for (limiteY = -L, aux_y=0 ; limiteY <= L; limiteY+= step, ++aux_y) { for (limiteZ = -L, aux_z=0 ; limiteZ <= L; limiteZ+= step, ++aux_z) { //escrevendo no arquivo myfile << limiteX <<",\t"<< limiteY << ",\t" << limiteZ << ",\t" << matrizMonte[aux_x][aux_y][aux_z] << "\t" << endl; } } } cout << "Time taken: " << (double)(clock() - tStart)/CLOCKS_PER_SEC << endl; return 0; } <commit_msg>tarefa2 - definindo funcao V11<commit_after>//============================================================================ // Name : Monte_carlo.cpp // Author : Rafael // Version : // Copyright : MIT // Description : Hello World in C++, Ansi-style // referencias: // 1 - http://ta.twi.tudelft.nl/mf/users/oosterle/oosterlee/lec8-hit-2009.pdf // 2 - Sadiku. M.N.O - Numeral Techniques in Electromagnetics with MATLAB // 3 - http://ww2.odu.edu/~agodunov/computing/programs/cpp/dmc_int1.cpp // 4 - https://github.com/s9w/articles/blob/master/perf%20cpp%20random.md - comparacao entre os metodos de gerar numeros aleatorios //http://www.cs.dartmouth.edu/~wjarosz/publications/dissertation/appendixA.pdf // AJUDOU SOBRE GERAR DOUBLE: //http://stackoverflow.com/questions/32071721/error-in-using-mt19937-with-random-device-as-static-class-members //http://physics.clarku.edu/courses/125/gtcdraft/chap11.pdf //http://stackoverflow.com/questions/24334012/best-way-to-seed-mt19937-64-for-monte-carlo-simulations // /* Artigos sobre geracao de aleatorios e monte carlo http://journals.aps.org/pre/abstract/10.1103/PhysRevE.75.066701 */ /* Metodos para gerar aleatorios: usado pelo chrome - xorshift128+ XX - Implementado GenerateNumbersXOR.h padrao do c++ 11 - mt19937 XX - Implementado GenerateNumbers.h descrito pelo numerical recipes pg 366- Ran XX - Implementado GenerateNumbersNR.h */ /* * Testar pelo método analitico as integrais * http://www.wolframalpha.com/examples/Integrals.html */ /** Alguns codigos fontes de MonteCarlo * http://ww2.odu.edu/~agodunov/computing/programs/cpp/dmc_int1.cpp * http://ww2.odu.edu/~agodunov/computing/programs/cpp/mc_int_nd.cpp */ /** tipos de metodos para integrar com o MonteCarlo * https://www.unige.ch/sciences/astro/files/2713/8971/4086/3_Paltani_MonteCarlo.pdf * -Strafiel sampling * -Importance sampling */ //============================================================================ /* * Adicionar novas formas de gerar numeros aleatorios * implementar novos metodos de monte carlo, importance * compilar * g++ -Wall -g -std=c++11 MonteCarloIntegration.cpp MonteCarloCrudeN.cpp GenerateNumbersNR.h -o MonteCarlo.o * */ #include <iostream> #include <random> #include <string> #include <math.h> //#include "MonteCarloCrude.h" #include "MonteCarloCrudeN.h" #include <time.h> #include <array> #include <fstream> #include <limits> #include <iomanip> #include <type_traits> #include <algorithm> using namespace std; // prototipo das funcoes /** * * @param x - uma funcao com apenas uma dimensao * @return retorna a funcao */ double funcao(double x); double funcaoN(double x[], int n, double limiteX, double limiteY, double limiteZ, double step); /** * Voce define a funcao que deve ser integrada * @param x Parametro de entrada da funcao * @return */ double funcao(double x) { double y; /** * I = x dx * resultado analitico: "http://www.wolframalpha.com/input/?i=int+x+dx+from+0+to+10" */ y = x; return y; } // classe para comprar numeros de ponto flutuante template<class T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, int ulp) { // the machine epsilon has to be scaled to the magnitude of the values used // and multiplied by the desired precision in ULPs (units in the last place) return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp // unless the result is subnormal || std::abs(x-y) < std::numeric_limits<T>::min(); } // estou usando a funcao do Alex Godunov // for (j = 0; j < n; j = j+1) // { // y = y + x[j]; // } // y = pow(y,2); /** resultado analitico * Wolfram: "http://www.wolframalpha.com/input/?i=int+x+%2B+y+%2B+z+dx+dy+dz%2C+x%3D0+to+1%2C+y%3D0+to+1%2C+z%3D0+to+1" */ double funcaoN(double x[], int n, double limiteX, double limiteY, double limiteZ, double step) { double y; /* Funcao antiga // int j; double gama_0 = 2.3562; int a_0 = 5; double c_a = 9.1439; y = 0.0; double raizG_0 = sqrt( pow(x[0],2) + pow(x[1],2) + pow(x[2],2) ); if( raizG_0 == 0 ){ y = a_0; }else if(raizG_0 < 1){ y = a_0 * (( sin(gama_0*raizG_0)) / (gama_0*raizG_0)) ; } else { y = c_a * (( exp( -gama_0*raizG_0)) / ( gama_0*raizG_0)) ; } y = pow(y,2); double raiz_R = sqrt( pow(limiteX - x[0],2) + pow(limiteY - x[1],2) + pow(limiteZ - x[2],2) ); if(raiz_R >= step ){ y/= raiz_R; } else { y/= 2 * step; } /* /* // return y = x[0] + x[1] + x[2]; //return y = pow(x[0],2) + sin(x[1]) * exp(x[2]); */ // y = 2*pow(x[0],2) + 3*pow(x[1],2) + 4*pow(x[2],2); //Valores Calculados para energia e constantes de normalização double e_l0, e_l1, e_l2; double gama1_l0, gama1_l1, gama1_l2, gama2_l0, gama2_l1, gama2_l2; int czao_l0, czao_l1, czao_l2; float azao_l0, azao_l1, azao_l2; float V0; double Y2; e_l0 = 53.7; e_l1 = 198.5; e_l2 = 289.8; gama1_l0 = 2.1973; gama1_l1 = 4.2248; gama1_l2 = 5.1045; gama2_l0 = 5.5800; gama2_l1 = 4.2562; gama2_l2 = 3.1477; czao_l0 = 3; czao_l1 = 6; czao_l2 = 7; azao_l0 = 281779; azao_l1 = 5.9432; azao_l2 = 7.2102; // valor calculado para o V0 V0 = -0.3697; //definicao do Y2 Y2 = (15 / (8 * M_PI) ) * ((pow(x[0],2) + pow(x[1],2)) * pow(x[2],2) ) / ( pow(pow(x[0],2) + pow(x[1],2) + pow(x[2],2), 2 ) ); double R_Rc = sqrt( (pow(limiteX - x[0], 2) + pow(limiteY - x[1],2) + pow(limiteZ - x[2],2) )); if( R_Rc < step){ R_Rc = 2 * step; } return y; // cout << "x1: "<< x[0] <<endl; // cout << "y1: "<< x[1] <<endl; // cout << "z1: "<< x[2] <<endl; } int main() { clock_t tStart = clock(); // definindo a precisao de quando mostra os resultados cout.precision(5); cout.setf(ios::fixed | ios::showpoint); /** MonteCarlo 1 dimensao // double a, b, montecarlo, erro; // int n; // int ntimes; // a = 0.0; // b = 10.0; // n = 2; // ntimes = 16; // for (int var = 0; var <= ntimes; ++var) { // // montecarlo = MonteCarloCrude::CrudeMonteCarlo(funcao, a, b, n, erro); // // cout <<"N: " << n << " Monte: "<< montecarlo << " Erro:"<< erro << endl; // n = n * 2; // } /** MonteCarlo n dimensoes * Parametros: * numeroIntegrais - quantidade de integrais, ex: dx, dy, dz... * L - Limite superior e inferior do somatorio da integral e limite do x,y,z das variaveis internas * limiteInferior - valor para o limite inferior do somatorio da integral * limiteSuperior - valor para o limite supeior do somatorio da integral * numeroInteracoes - numero de chamadas para o montecarlo, quanto maior melhor, porem quanto maior maior tempo * step - o passo de cada interacao * resultado - valor retornado pelo metodo de montecarlo */ const int numeroIntegrais = 3; int L = 1; double limiteInferior[numeroIntegrais] = { -L, -L, -L}; double limiteSuperior[numeroIntegrais] = { L, L, L}; int numeroInteracoes = 100000; double step=0.5; double limiteX, limiteY, limiteZ; double matrizMonte[int((L/0.25)+1)][int((L/0.25)+1)][int((L/0.25)+1)]; double resultado; int aux_x, aux_y, aux_z; aux_x = 0; aux_y = 0; aux_z = 0; for (limiteX = -L, aux_x=0 ; limiteX <= L; limiteX+= step, ++aux_x) { for (limiteY = -L, aux_y=0 ; limiteY <= L; limiteY+= step, ++aux_y) { for (limiteZ = -L, aux_z=0 ; limiteZ <= L; limiteZ+= step, ++aux_z) { resultado = MonteCarloCrudeN::CrudeMonteCarloN(funcaoN, limiteInferior, limiteSuperior, numeroIntegrais, numeroInteracoes,limiteX, limiteY,limiteZ,step); // cout << "mN: " << mN << " Resul: "<< result << endl; cout << "x " << limiteX << " y "<< limiteY << " z " <<limiteZ << " Resul "<< resultado << endl; // cout << "a_x " << aux_x << " a_y "<< aux_y << " a_z " <<aux_z << endl; matrizMonte[aux_x][aux_y][aux_z] = resultado; } } } //Pegando a hora atual e definindo no nome do arquivo time_t now; struct tm *now_tm; now = time(NULL); now_tm = localtime(&now); int hour = now_tm->tm_hour; int min = now_tm->tm_min; int sec = now_tm->tm_sec; //Criando um arquivo para coloca os dados da matriz X Y Z Resultado ofstream myfile; string arquivoNome = "matriz " + to_string(hour)+ ":" + to_string(min) + ":" + to_string(sec) + ".txt"; myfile.open (arquivoNome); myfile << "X,\t" << "Y,\t" << "Z,\t"<< "Resultado\t" << endl; // escrevendo resultado no arquivo aux_x = 0; aux_y = 0; aux_z = 0; for (limiteX = -L, aux_x=0 ; limiteX <= L; limiteX+= step, ++aux_x) { for (limiteY = -L, aux_y=0 ; limiteY <= L; limiteY+= step, ++aux_y) { for (limiteZ = -L, aux_z=0 ; limiteZ <= L; limiteZ+= step, ++aux_z) { //escrevendo no arquivo myfile << limiteX <<",\t"<< limiteY << ",\t" << limiteZ << ",\t" << matrizMonte[aux_x][aux_y][aux_z] << "\t" << endl; } } } cout << "Time taken: " << (double)(clock() - tStart)/CLOCKS_PER_SEC << endl; return 0; } <|endoftext|>
<commit_before>#include "cmm_socket_receiver.h" #include "cmm_socket_sender.h" #include <pthread.h> #include "debug.h" #include "timeops.h" #include <vector> using std::vector; class ReadyIROB { public: bool operator()(PendingIROB *pi) { assert(pi); PendingReceiverIROB *pirob = static_cast<PendingReceiverIROB*>(pi); assert(pirob); return (pirob->is_complete() && pirob->is_released()); } }; CMMSocketReceiver::CMMSocketReceiver(CMMSocketImpl *sk_) : sk(sk_) { handle(CMM_CONTROL_MSG_BEGIN_IROB, this, &CMMSocketReceiver::do_begin_irob); handle(CMM_CONTROL_MSG_END_IROB, this, &CMMSocketReceiver::do_end_irob); handle(CMM_CONTROL_MSG_IROB_CHUNK, this, &CMMSocketReceiver::do_irob_chunk); handle(CMM_CONTROL_MSG_DEFAULT_IROB, this, &CMMSocketReceiver::do_default_irob); handle(CMM_CONTROL_MSG_NEW_INTERFACE, this, &CMMSocketReceiver::do_new_interface); handle(CMM_CONTROL_MSG_DOWN_INTERFACE, this, &CMMSocketReceiver::do_down_interface); handle(CMM_CONTROL_MSG_ACK, this, &CMMSocketReceiver::do_ack); handle(CMM_CONTROL_MSG_GOODBYE, this, &CMMSocketReceiver::do_goodbye); } CMMSocketReceiver::~CMMSocketReceiver() { stop(); PendingIROBHash::accessor ac; while (pending_irobs.any(ac)) { PendingIROB *victim = ac->second; pending_irobs.erase(ac); delete victim; ac.release(); } } void CMMSocketReceiver::dispatch(struct CMMSocketControlHdr hdr) { struct timeval now; TIME(now); dbgprintf("Receiver-scheduler got request: %s\n", hdr.describe().c_str()); CMMSocketScheduler<struct CMMSocketControlHdr>::dispatch(hdr); } void CMMSocketReceiver::do_begin_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_BEGIN_IROB); if (hdr.op.begin_irob.numdeps > 0) { assert(hdr.op.begin_irob.deps); } PendingIROB *pirob = new PendingReceiverIROB(hdr.op.begin_irob); PendingIROBHash::accessor ac; if (!pending_irobs.insert(ac, pirob)) { delete pirob; throw Exception::make("Tried to begin IROB that already exists", hdr); } if (hdr.op.begin_irob.numdeps > 0) { delete [] hdr.op.begin_irob.deps; } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver began IROB %d, took %lu.%06lu seconds\n", ntohl(hdr.op.begin_irob.id), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_end_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_END_IROB); PendingIROBHash::accessor ac; irob_id_t id = ntohl(hdr.op.end_irob.id); if (!pending_irobs.find(ac, id)) { if (pending_irobs.past_irob_exists(id)) { throw Exception::make("Tried to end committed IROB", hdr); } else { throw Exception::make("Tried to end nonexistent IROB", hdr); } } PendingIROB *pirob = ac->second; assert(pirob); if (!pirob->finish()) { throw Exception::make("Tried to end already-done IROB", hdr); } PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob); pending_irobs.release_if_ready(prirob, ReadyIROB()); ac.release(); //sk->sendr->ack(id); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver ended IROB %d, took %lu.%06lu seconds\n", id, diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_irob_chunk(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK); irob_id_t id = ntohl(hdr.op.irob_chunk.id); PendingIROBHash::accessor ac; if (!pending_irobs.find(ac, id)) { if (pending_irobs.past_irob_exists(id)) { throw Exception::make("Tried to add to committed IROB", hdr); } else { throw Exception::make("Tried to add to nonexistent IROB", hdr); } } struct irob_chunk_data chunk; chunk.id = id; chunk.seqno = ntohl(hdr.op.irob_chunk.seqno); chunk.datalen = ntohl(hdr.op.irob_chunk.datalen); chunk.data = hdr.op.irob_chunk.data; PendingIROB *pirob = ac->second; assert(pirob); PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob); assert(prirob); if (!prirob->add_chunk(chunk)) { throw Exception::make("Tried to add to completed IROB", hdr); } else { dbgprintf("Successfully added chunk %d to IROB %d\n", chunk.seqno, id); } ac.release(); sk->sendr->ack(id, chunk.seqno); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Added and ACK'd chunk %d in IROB %d, took %lu.%06lu seconds\n", chunk.seqno, id, diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_default_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DEFAULT_IROB); PendingIROB *pirob = new PendingReceiverIROB(hdr.op.default_irob); PendingIROBHash::accessor ac; if (!pending_irobs.insert(ac, pirob)) { delete pirob; throw Exception::make("Tried to add default IROB that already exists", hdr); } /* missing ack */ TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Received default IROB %d, took %lu.%06lu seconds\n", ntohl(hdr.op.default_irob.id), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_new_interface(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE); struct net_interface iface = {hdr.op.new_interface.ip_addr, hdr.op.new_interface.labels}; sk->setup(iface, false); } void CMMSocketReceiver::do_down_interface(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DOWN_INTERFACE); struct net_interface iface = {hdr.op.down_interface.ip_addr}; sk->teardown(iface, false); } void CMMSocketReceiver::do_ack(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_ACK); sk->sendr->ack_received(ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno)); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver got ACK for IROB %d chunk %d, took %lu.%06lu seconds\n", ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_goodbye(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_GOODBYE); if (sk->sendr->is_shutting_down()) { /* I initiated the shutdown; this is the "FIN/ACK" */ /* at this point, both sides have stopped sending. */ sk->sendr->goodbye_acked(); } else { /* The other side initiated the shutdown; this is the "FIN" */ /* Send the "FIN/ACK" */ sk->sendr->goodbye(true); } /* Note: the senders will still wait for all IROB chunks * to be ACK'd before finalizing the shutdown. */ } void CMMSocketReceiver::shutdown() { pending_irobs.shutdown(); } /* This is where all the scheduling logic happens. * This function decides how to pass IROB data to the application. * * Additionally, this function is the only place we need * to worry about race conditions with the Receiver thread. * Thus, the locking discipline of that thread will be informed * by whatever reads and writes are necessary here. * * Initial stab at requirements: * This thread definitely needs to read from the pending_irobs * data structure, to figure out what data to pass to the * application. It also needs to update this data structure * and the past_irobs set as IROBs are committed. * Thought: we could make this function read-only by using the * msg_queue to cause the Receiver thread to do any needed updates. */ /* TODO: nonblocking mode */ ssize_t CMMSocketReceiver::recv(void *bufp, size_t len, int flags, u_long *recv_labels) { vector<PendingReceiverIROB *> pirobs; char *buf = (char*)bufp; struct timeval begin, end, diff; TIME(begin); ssize_t bytes_ready = 0; while ((size_t)bytes_ready < len) { struct timeval one_begin, one_end, one_diff; TIME(one_begin); PendingReceiverIROB *pirob = pending_irobs.get_ready_irob(); TIME(one_end); TIMEDIFF(one_begin, one_end, one_diff); dbgprintf("Getting one ready IROB took %lu.%06lu seconds\n", one_diff.tv_sec, one_diff.tv_usec); if (!pirob) { if (sk->sendr->is_shutting_down()) { return 0; } else { assert(0); /* XXX: nonblocking case may return NULL */ } } /* after the IROB is returned here, no other thread will * unsafely modify it. * XXX: this will not be true if we allow get_next_irob * to return released, incomplete IROBs. * We could fix that by simply having a sentinel chunk * on the concurrent_queue of chunks. */ assert(pirob->is_released()); assert(pirob->is_complete()); /* XXX: see get_next_irob */ ssize_t bytes = pirob->numbytes(); assert(bytes > 0); bytes_ready += bytes; pirobs.push_back(pirob); if (!pirob->is_complete()) { break; } } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("recv: gathering bytes took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); TIME(begin); ssize_t bytes_passed = 0; bool partial_irob = false; for (size_t i = 0; i < pirobs.size(); i++) { PendingIROBHash::accessor ac; PendingReceiverIROB *pirob = pirobs[i]; if (!pending_irobs.find(ac, pirob->id)) { assert(0); } assert(pirob == ac->second); if (i == 0) { if (recv_labels) { *recv_labels = pirob->send_labels; } } bytes_passed += pirob->read_data(buf + bytes_passed, len - bytes_passed); if (pirob->is_complete() && pirob->numbytes() == 0) { pending_irobs.erase(ac); pending_irobs.release_dependents(pirob, ReadyIROB()); delete pirob; } else { if (!pirob->is_complete()) { /* This should still be the last one in the list, * since it MUST finish before any IROB can be * passed to the application. */ } /* this should be true for at most the last IROB * in the vector */ assert(!partial_irob); partial_irob = true; pending_irobs.partially_read(pirob); } } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("recv: Copying bytes took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); dbgprintf("Passing bytes to application\n"); return bytes_passed; } bool CMMSocketReceiver::find_irob(PendingIROBHash::const_accessor& ac, irob_id_t id) { return pending_irobs.find(ac, id); } <commit_msg>Remember to release default IROBs as they arrive.<commit_after>#include "cmm_socket_receiver.h" #include "cmm_socket_sender.h" #include <pthread.h> #include "debug.h" #include "timeops.h" #include <vector> using std::vector; class ReadyIROB { public: bool operator()(PendingIROB *pi) { assert(pi); PendingReceiverIROB *pirob = static_cast<PendingReceiverIROB*>(pi); assert(pirob); return (pirob->is_complete() && pirob->is_released()); } }; CMMSocketReceiver::CMMSocketReceiver(CMMSocketImpl *sk_) : sk(sk_) { handle(CMM_CONTROL_MSG_BEGIN_IROB, this, &CMMSocketReceiver::do_begin_irob); handle(CMM_CONTROL_MSG_END_IROB, this, &CMMSocketReceiver::do_end_irob); handle(CMM_CONTROL_MSG_IROB_CHUNK, this, &CMMSocketReceiver::do_irob_chunk); handle(CMM_CONTROL_MSG_DEFAULT_IROB, this, &CMMSocketReceiver::do_default_irob); handle(CMM_CONTROL_MSG_NEW_INTERFACE, this, &CMMSocketReceiver::do_new_interface); handle(CMM_CONTROL_MSG_DOWN_INTERFACE, this, &CMMSocketReceiver::do_down_interface); handle(CMM_CONTROL_MSG_ACK, this, &CMMSocketReceiver::do_ack); handle(CMM_CONTROL_MSG_GOODBYE, this, &CMMSocketReceiver::do_goodbye); } CMMSocketReceiver::~CMMSocketReceiver() { stop(); PendingIROBHash::accessor ac; while (pending_irobs.any(ac)) { PendingIROB *victim = ac->second; pending_irobs.erase(ac); delete victim; ac.release(); } } void CMMSocketReceiver::dispatch(struct CMMSocketControlHdr hdr) { struct timeval now; TIME(now); dbgprintf("Receiver-scheduler got request: %s\n", hdr.describe().c_str()); CMMSocketScheduler<struct CMMSocketControlHdr>::dispatch(hdr); } void CMMSocketReceiver::do_begin_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_BEGIN_IROB); if (hdr.op.begin_irob.numdeps > 0) { assert(hdr.op.begin_irob.deps); } PendingIROB *pirob = new PendingReceiverIROB(hdr.op.begin_irob); PendingIROBHash::accessor ac; if (!pending_irobs.insert(ac, pirob)) { delete pirob; throw Exception::make("Tried to begin IROB that already exists", hdr); } if (hdr.op.begin_irob.numdeps > 0) { delete [] hdr.op.begin_irob.deps; } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver began IROB %d, took %lu.%06lu seconds\n", ntohl(hdr.op.begin_irob.id), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_end_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_END_IROB); PendingIROBHash::accessor ac; irob_id_t id = ntohl(hdr.op.end_irob.id); if (!pending_irobs.find(ac, id)) { if (pending_irobs.past_irob_exists(id)) { throw Exception::make("Tried to end committed IROB", hdr); } else { throw Exception::make("Tried to end nonexistent IROB", hdr); } } PendingIROB *pirob = ac->second; assert(pirob); if (!pirob->finish()) { throw Exception::make("Tried to end already-done IROB", hdr); } PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob); pending_irobs.release_if_ready(prirob, ReadyIROB()); ac.release(); //sk->sendr->ack(id); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver ended IROB %d, took %lu.%06lu seconds\n", id, diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_irob_chunk(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK); irob_id_t id = ntohl(hdr.op.irob_chunk.id); PendingIROBHash::accessor ac; if (!pending_irobs.find(ac, id)) { if (pending_irobs.past_irob_exists(id)) { throw Exception::make("Tried to add to committed IROB", hdr); } else { throw Exception::make("Tried to add to nonexistent IROB", hdr); } } struct irob_chunk_data chunk; chunk.id = id; chunk.seqno = ntohl(hdr.op.irob_chunk.seqno); chunk.datalen = ntohl(hdr.op.irob_chunk.datalen); chunk.data = hdr.op.irob_chunk.data; PendingIROB *pirob = ac->second; assert(pirob); PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob); assert(prirob); if (!prirob->add_chunk(chunk)) { throw Exception::make("Tried to add to completed IROB", hdr); } else { dbgprintf("Successfully added chunk %d to IROB %d\n", chunk.seqno, id); } ac.release(); sk->sendr->ack(id, chunk.seqno); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Added and ACK'd chunk %d in IROB %d, took %lu.%06lu seconds\n", chunk.seqno, id, diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_default_irob(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DEFAULT_IROB); PendingIROB *pirob = new PendingReceiverIROB(hdr.op.default_irob); PendingIROBHash::accessor ac; if (!pending_irobs.insert(ac, pirob)) { delete pirob; throw Exception::make("Tried to add default IROB that already exists", hdr); } PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob); pending_irobs.release_if_ready(prirob, ReadyIROB()); ac.release(); sk->sendr->ack(ntohl(hdr.op.default_irob.id)); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Received default IROB %d, took %lu.%06lu seconds\n", ntohl(hdr.op.default_irob.id), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_new_interface(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE); struct net_interface iface = {hdr.op.new_interface.ip_addr, hdr.op.new_interface.labels}; sk->setup(iface, false); } void CMMSocketReceiver::do_down_interface(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DOWN_INTERFACE); struct net_interface iface = {hdr.op.down_interface.ip_addr}; sk->teardown(iface, false); } void CMMSocketReceiver::do_ack(struct CMMSocketControlHdr hdr) { struct timeval begin, end, diff; TIME(begin); assert(ntohs(hdr.type) == CMM_CONTROL_MSG_ACK); sk->sendr->ack_received(ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno)); TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("Receiver got ACK for IROB %d chunk %d, took %lu.%06lu seconds\n", ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno), diff.tv_sec, diff.tv_usec); } void CMMSocketReceiver::do_goodbye(struct CMMSocketControlHdr hdr) { assert(ntohs(hdr.type) == CMM_CONTROL_MSG_GOODBYE); if (sk->sendr->is_shutting_down()) { /* I initiated the shutdown; this is the "FIN/ACK" */ /* at this point, both sides have stopped sending. */ sk->sendr->goodbye_acked(); } else { /* The other side initiated the shutdown; this is the "FIN" */ /* Send the "FIN/ACK" */ sk->sendr->goodbye(true); } /* Note: the senders will still wait for all IROB chunks * to be ACK'd before finalizing the shutdown. */ } void CMMSocketReceiver::shutdown() { pending_irobs.shutdown(); } /* This is where all the scheduling logic happens. * This function decides how to pass IROB data to the application. * * Additionally, this function is the only place we need * to worry about race conditions with the Receiver thread. * Thus, the locking discipline of that thread will be informed * by whatever reads and writes are necessary here. * * Initial stab at requirements: * This thread definitely needs to read from the pending_irobs * data structure, to figure out what data to pass to the * application. It also needs to update this data structure * and the past_irobs set as IROBs are committed. * Thought: we could make this function read-only by using the * msg_queue to cause the Receiver thread to do any needed updates. */ /* TODO: nonblocking mode */ ssize_t CMMSocketReceiver::recv(void *bufp, size_t len, int flags, u_long *recv_labels) { vector<PendingReceiverIROB *> pirobs; char *buf = (char*)bufp; struct timeval begin, end, diff; TIME(begin); ssize_t bytes_ready = 0; while ((size_t)bytes_ready < len) { struct timeval one_begin, one_end, one_diff; TIME(one_begin); PendingReceiverIROB *pirob = pending_irobs.get_ready_irob(); TIME(one_end); TIMEDIFF(one_begin, one_end, one_diff); dbgprintf("Getting one ready IROB took %lu.%06lu seconds\n", one_diff.tv_sec, one_diff.tv_usec); if (!pirob) { if (sk->sendr->is_shutting_down()) { return 0; } else { assert(0); /* XXX: nonblocking case may return NULL */ } } /* after the IROB is returned here, no other thread will * unsafely modify it. * XXX: this will not be true if we allow get_next_irob * to return released, incomplete IROBs. * We could fix that by simply having a sentinel chunk * on the concurrent_queue of chunks. */ assert(pirob->is_released()); assert(pirob->is_complete()); /* XXX: see get_next_irob */ ssize_t bytes = pirob->numbytes(); assert(bytes > 0); bytes_ready += bytes; pirobs.push_back(pirob); if (!pirob->is_complete()) { break; } } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("recv: gathering bytes took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); TIME(begin); ssize_t bytes_passed = 0; bool partial_irob = false; for (size_t i = 0; i < pirobs.size(); i++) { PendingIROBHash::accessor ac; PendingReceiverIROB *pirob = pirobs[i]; if (!pending_irobs.find(ac, pirob->id)) { assert(0); } assert(pirob == ac->second); if (i == 0) { if (recv_labels) { *recv_labels = pirob->send_labels; } } bytes_passed += pirob->read_data(buf + bytes_passed, len - bytes_passed); if (pirob->is_complete() && pirob->numbytes() == 0) { pending_irobs.erase(ac); pending_irobs.release_dependents(pirob, ReadyIROB()); delete pirob; } else { if (!pirob->is_complete()) { /* This should still be the last one in the list, * since it MUST finish before any IROB can be * passed to the application. */ } /* this should be true for at most the last IROB * in the vector */ assert(!partial_irob); partial_irob = true; pending_irobs.partially_read(pirob); } } TIME(end); TIMEDIFF(begin, end, diff); dbgprintf("recv: Copying bytes took %lu.%06lu seconds\n", diff.tv_sec, diff.tv_usec); dbgprintf("Passing bytes to application\n"); return bytes_passed; } bool CMMSocketReceiver::find_irob(PendingIROBHash::const_accessor& ac, irob_id_t id) { return pending_irobs.find(ac, id); } <|endoftext|>
<commit_before>#pragma once #include <eosio/chain/wasm_interface.hpp> #include <eosio/chain/webassembly/wavm.hpp> #include <eosio/chain/webassembly/binaryen.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/wasm_eosio_injection.hpp> #include "IR/Module.h" #include "Runtime/Intrinsics.h" #include "Platform/Platform.h" #include "WAST/WAST.h" #include "IR/Validate.h" using namespace fc; using namespace eosio::chain::webassembly; using namespace IR; using namespace Runtime; namespace eosio { namespace chain { struct wasm_interface_impl { wasm_interface_impl(wasm_interface::vm_type vm) { if(vm == wasm_interface::vm_type::wavm) runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>(); else if(vm == wasm_interface::vm_type::binaryen) runtime_interface = std::make_unique<webassembly::binaryen::binaryen_runtime>(); else FC_THROW("wasm_interface_impl fall through"); } std::vector<uint8_t> parse_initial_memory(const Module& module) { std::vector<uint8_t> mem_image; for(const DataSegment& data_segment : module.dataSegments) { FC_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const); FC_ASSERT(module.memories.defs.size()); const U32 base_offset = data_segment.baseOffset.i32; const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2); if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size) FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range"); if(base_offset + data_segment.data.size() > mem_image.size()) mem_image.resize(base_offset + data_segment.data.size(), 0x00); memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size()); } return mem_image; } std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module(const digest_type& code_id, const shared_vector<char>& code) { auto it = instantiation_cache.find(code_id); if(it == instantiation_cache.end()) { ilog("START0 ${now}", ("now",fc::time_point::now())); IR::Module module; try { Serialization::MemoryInputStream stream((const U8*)code.data(), code.size()); WASM::serialize(stream, module); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } wasm_injections::wasm_binary_injection injector(module); injector.inject(); std::vector<U8> bytes; try { Serialization::ArrayOutputStream outstream; WASM::serialize(outstream, module); bytes = outstream.getBytes(); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } it = instantiation_cache.emplace(code_id, runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module))).first; ilog("END0 ${now}", ("now",fc::time_point::now())); } return it->second; } std::unique_ptr<wasm_runtime_interface> runtime_interface; map<digest_type, std::unique_ptr<wasm_instantiated_module_interface>> instantiation_cache; }; #define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_BINARYEN_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) #define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG ) #define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) ) #define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) ) #define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\ static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature"); #define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\ static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature"); #define _UNWRAP_SEQ(...) __VA_ARGS__ #define _EXPAND_ARGS(CLS, MOD, INFO)\ ( CLS, MOD, _UNWRAP_SEQ INFO ) #define _REGISTER_INTRINSIC(R, CLS, INFO)\ BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY()) #define REGISTER_INTRINSICS(CLS, MEMBERS)\ BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS)) #define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\ BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY()) #define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\ BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS)) } } // eosio::chain <commit_msg>Forgot debug output<commit_after>#pragma once #include <eosio/chain/wasm_interface.hpp> #include <eosio/chain/webassembly/wavm.hpp> #include <eosio/chain/webassembly/binaryen.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/wasm_eosio_injection.hpp> #include "IR/Module.h" #include "Runtime/Intrinsics.h" #include "Platform/Platform.h" #include "WAST/WAST.h" #include "IR/Validate.h" using namespace fc; using namespace eosio::chain::webassembly; using namespace IR; using namespace Runtime; namespace eosio { namespace chain { struct wasm_interface_impl { wasm_interface_impl(wasm_interface::vm_type vm) { if(vm == wasm_interface::vm_type::wavm) runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>(); else if(vm == wasm_interface::vm_type::binaryen) runtime_interface = std::make_unique<webassembly::binaryen::binaryen_runtime>(); else FC_THROW("wasm_interface_impl fall through"); } std::vector<uint8_t> parse_initial_memory(const Module& module) { std::vector<uint8_t> mem_image; for(const DataSegment& data_segment : module.dataSegments) { FC_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const); FC_ASSERT(module.memories.defs.size()); const U32 base_offset = data_segment.baseOffset.i32; const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2); if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size) FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range"); if(base_offset + data_segment.data.size() > mem_image.size()) mem_image.resize(base_offset + data_segment.data.size(), 0x00); memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size()); } return mem_image; } std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module(const digest_type& code_id, const shared_vector<char>& code) { auto it = instantiation_cache.find(code_id); if(it == instantiation_cache.end()) { IR::Module module; try { Serialization::MemoryInputStream stream((const U8*)code.data(), code.size()); WASM::serialize(stream, module); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } wasm_injections::wasm_binary_injection injector(module); injector.inject(); std::vector<U8> bytes; try { Serialization::ArrayOutputStream outstream; WASM::serialize(outstream, module); bytes = outstream.getBytes(); } catch(Serialization::FatalSerializationException& e) { EOS_ASSERT(false, wasm_serialization_error, e.message.c_str()); } it = instantiation_cache.emplace(code_id, runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module))).first; } return it->second; } std::unique_ptr<wasm_runtime_interface> runtime_interface; map<digest_type, std::unique_ptr<wasm_instantiated_module_interface>> instantiation_cache; }; #define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_BINARYEN_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) #define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG ) #define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) ) #define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\ _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) ) #define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\ static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature"); #define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\ static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature"); #define _UNWRAP_SEQ(...) __VA_ARGS__ #define _EXPAND_ARGS(CLS, MOD, INFO)\ ( CLS, MOD, _UNWRAP_SEQ INFO ) #define _REGISTER_INTRINSIC(R, CLS, INFO)\ BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY()) #define REGISTER_INTRINSICS(CLS, MEMBERS)\ BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS)) #define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\ BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY()) #define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\ BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS)) } } // eosio::chain <|endoftext|>
<commit_before>#include <iostream> #include "occa.hpp" int main(int argc, char **argv){ int entries = 5; //---[ Init CUDA ]------------------ int cuDeviceID; void *cu_a, *cu_b, *cu_ab; cudaMalloc(&cu_a , entries*sizeof(float)); cudaMalloc(&cu_b , entries*sizeof(float)); cudaMalloc(&cu_ab, entries*sizeof(float)); // ---[ Get CUDA Info ]---- CUdevice cuDevice; CUcontext cuContext; cuDeviceGet(&cuDevice, cuDeviceID); cuCtxGetCurrent(&cuContext); // ======================== //==================================== float *a = new float[entries]; float *b = new float[entries]; float *ab = new float[entries]; occa::device device = occa::cuda::wrapDevice(cuDevice, cuContext); occa::kernel addVectors; occa::memory o_a, o_b, o_ab; for(int i = 0; i < entries; ++i){ a[i] = i; b[i] = 1 - i; ab[i] = 0; } o_a = device.wrapMemory(&cu_a , entries*sizeof(float)); o_b = device.wrapMemory(&cu_b , entries*sizeof(float)); o_ab = device.wrapMemory(&cu_ab, entries*sizeof(float)); addVectors = device.buildKernelFromSource("addVectors.occa", "addVectors"); int dims = 1; int itemsPerGroup(2); int groups((entries + itemsPerGroup - 1)/itemsPerGroup); addVectors.setWorkingDims(dims, itemsPerGroup, groups); o_a.copyFrom(a); o_b.copyFrom(b); occa::initTimer(device); occa::tic("addVectors"); addVectors(entries, o_a, o_b, o_ab); double elapsedTime = occa::toc("addVectors", addVectors); o_ab.copyTo(ab); std::cout << "Elapsed time = " << elapsedTime << " s" << std::endl; occa::printTimer(); for(int i = 0; i < 5; ++i) std::cout << i << ": " << ab[i] << '\n'; addVectors.free(); o_a.free(); o_b.free(); o_ab.free(); delete [] a; delete [] b; delete [] ab; return 0; } <commit_msg>[Example] Updated CUDA wrapping example (still need to test)<commit_after>#include <iostream> #include "occa.hpp" int main(int argc, char **argv){ int entries = 5; //---[ Init CUDA ]------------------ int cuDeviceID; cudaStream_t cuStream; void *cu_a, *cu_b, *cu_ab; // Default: cuStream = 0 cudaStreamCreate(&customStream); cudaMalloc(&cu_a , entries*sizeof(float)); cudaMalloc(&cu_b , entries*sizeof(float)); cudaMalloc(&cu_ab, entries*sizeof(float)); // ---[ Get CUDA Info ]---- CUdevice cuDevice; CUcontext cuContext; cuDeviceGet(&cuDevice, cuDeviceID); cuCtxGetCurrent(&cuContext); // ======================== //==================================== float *a = new float[entries]; float *b = new float[entries]; float *ab = new float[entries]; occa::device device = occa::cuda::wrapDevice(cuDevice, cuContext); occa::stream stream = device.wrapStream(&cuStream); device.setStream(stream); occa::kernel addVectors; occa::memory o_a, o_b, o_ab; for(int i = 0; i < entries; ++i){ a[i] = i; b[i] = 1 - i; ab[i] = 0; } o_a = device.wrapMemory(&cu_a , entries*sizeof(float)); o_b = device.wrapMemory(&cu_b , entries*sizeof(float)); o_ab = device.wrapMemory(&cu_ab, entries*sizeof(float)); addVectors = device.buildKernelFromSource("addVectors.occa", "addVectors"); int dims = 1; int itemsPerGroup(2); int groups((entries + itemsPerGroup - 1)/itemsPerGroup); addVectors.setWorkingDims(dims, itemsPerGroup, groups); o_a.copyFrom(a); o_b.copyFrom(b); occa::initTimer(device); occa::tic("addVectors"); addVectors(entries, o_a, o_b, o_ab); double elapsedTime = occa::toc("addVectors", addVectors); o_ab.copyTo(ab); std::cout << "Elapsed time = " << elapsedTime << " s" << std::endl; occa::printTimer(); for(int i = 0; i < 5; ++i) std::cout << i << ": " << ab[i] << '\n'; addVectors.free(); o_a.free(); o_b.free(); o_ab.free(); delete [] a; delete [] b; delete [] ab; return 0; } <|endoftext|>
<commit_before>// Copyright 2015 Patrick Putnam // // 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. #ifndef FITNESS_GENERATOR_HPP_ #define FITNESS_GENERATOR_HPP_ #include <boost/property_tree/ptree.hpp> #include <iterator> #include "clotho/genetics/normal_fitness_metric.hpp" class normal_fitness_generator { public: typedef normal_fitness_metric result_type; normal_fitness_generator( boost::property_tree::ptree & config ) : m_mu(1.) { parseConfig( config ); } template < class Iter > result_type operator()( Iter first, Iter last ) { // theoretical standard deviation: // sqrt( 2 * N * mu), where // N - is the haploid sequence count // mu - mutation rate per sequence // distance(,) - number of individuals in population (N_p) => N = 2 * (N_p); hence: 4.0 * N_p double n = 4.0 * (double)std::distance(first, last); n *= m_mu; n = sqrt(n); // theoretical standard deviation return result_type( 0., n ); } protected: void parseConfig( boost::property_tree::ptree & config ) { std::ostringstream oss; oss << CONFIG_BLOCK_K << "." << MUT_BLOCK_K << "." << RATE_PER_REGION_K; if( config.get_child_optional( oss.str() ) != boost::none ) { m_mu = config.get< double >( oss.str(), 1. ); } } double m_mu; }; #include "clotho/genetics/quadratic_fitness_metric.hpp" extern const string FITNESS_BLOCK_K; extern const string QUADRATIC_SCALE_K; class quadratic_fitness_generator { public: typedef quadratic_fitness_metric result_type; quadratic_fitness_generator( boost::property_tree::ptree & config ) : m_scale(1.) , m_mu( 1. ) { parseConfig( config ); } template < class Iter > result_type operator()( Iter first, Iter last ) { // theoretical standard deviation: // sqrt( 2 * N * mu), where // N - is the haploid sequence count // mu - mutation rate per sequence // distance(,) - number of individuals in population (N_p) => N = 2 * (N_p); hence: 4.0 * N_p double res = 4.0 * (double)std::distance( first, last ); res *= m_mu; res = sqrt( res ); // theoretical standard deviation return result_type( m_scale * res ); } protected: void parseConfig( boost::property_tree::ptree & config ) { std::ostringstream oss; oss << CONFIG_BLOCK_K << "." << FITNESS_BLOCK_K << "." << QUADRATIC_SCALE_K; if( config.get_child_optional( oss.str() ) == boost::none ) { config.put( oss.str(), m_scale ); } else { m_scale = config.get< double >( oss.str(), 1. ); assert( m_scale > 0.0 ); } oss.str(""); oss.clear(); oss << CONFIG_BLOCK_K << "." << MUT_BLOCK_K << "." << RATE_PER_REGION_K; if( config.get_child_optional( oss.str() ) != boost::none ) { m_mu = config.get< double >( oss.str(), 1. ); } } double m_scale, m_mu; }; #include "clotho/genetics/constant_fitness_metric.hpp" extern const string CONSTANT_K; class constant_fitness_generator { public: typedef constant_fitness_metric result_type; constant_fitness_generator( boost::property_tree::ptree & config ) : m_val( 1. ) { parseConfig( config ); } template < class Iter > result_type operator()( Iter first, Iter last ) { return result_type( m_val ); } protected: void parseConfig( boost::property_tree::ptree & config ) { std::ostringstream oss; oss << CONFIG_BLOCK_K << "." << FITNESS_BLOCK_K << "." << CONSTANT_K; if( config.get_child_optional( oss.str() ) == boost::none ) { config.put( oss.str(), m_val ); } else { m_val = config.get< double >( oss.str(), 1. ); } } double m_val; }; #endif // FITNESS_GENERATOR_HPP_ <commit_msg>Deprecated<commit_after><|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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. * *=========================================================================*/ #ifndef __itkColorTable_hxx #define __itkColorTable_hxx #include "itkColorTable.h" #include "itkNumericTraits.h" #include "vnl/vnl_sample.h" #include <sstream> #include <iomanip> namespace itk { template< typename TPixel > ColorTable< TPixel > ::ColorTable() { m_NumberOfColors = 0; } template< typename TPixel > void ColorTable< TPixel > ::DeleteColors() { m_Color.resize(0); m_ColorName.resize(0); } template< typename TPixel > void ColorTable< TPixel > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfColors = " << m_NumberOfColors << std::endl; for ( unsigned int i = 0; i < m_NumberOfColors; i++ ) { os << indent << "ColorName[" << i << "] = " << m_ColorName[i] << ", " << "Color[" << i << "] = " << m_Color[i] << std::endl; } } template< typename TPixel > void ColorTable< TPixel > ::UseDiscreteColors(void) { this->DeleteColors(); m_NumberOfColors = 8; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType scale; typename NumericTraits< TPixel >::RealType shift; if (NumericTraits<TPixel>::is_integer) { scale = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); shift = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); } else { scale = NumericTraits< TPixel >::One; shift = NumericTraits< TPixel >::Zero; } m_Color[0].Set((TPixel)(0.9 * scale + shift), (TPixel)( shift), (TPixel)( shift) ); m_ColorName[0] = "Red"; m_Color[1].Set((TPixel)(0.8 * scale + shift), (TPixel)( shift), (TPixel)(0.8 * scale + shift)); m_ColorName[1] = "Purple"; m_Color[2].Set((TPixel)( shift), (TPixel)(0.8 * scale + shift), (TPixel)(0.8 * scale + shift)); m_ColorName[2] = "Aqua"; m_Color[3].Set((TPixel)(0.8 * scale + shift), (TPixel)(0.8 * scale + shift), (TPixel)( shift)); m_ColorName[3] = "Yellow"; m_Color[4].Set((TPixel)( shift), (TPixel)(0.9 * scale + shift), (TPixel)( shift)); m_ColorName[4] = "Green"; m_Color[5].Set((TPixel)( shift), (TPixel)( shift), (TPixel)(0.9 * scale + shift)); m_ColorName[5] = "Blue"; m_Color[6].Set((TPixel)(0.7 * scale + shift), (TPixel)(0.7 * scale + shift), (TPixel)(0.7 * scale + shift)); m_ColorName[6] = "Grey0.70"; // // to avoid numeric exception, need to make // sure that the value assigned is clamped at // max for TPixel. Exceptions were happening // on this assignment, even if realMax was // set to NumericTraits<TPixel>::max(). typename NumericTraits< TPixel >::RealType realMax(1.0 * scale + shift); TPixel pixelMax(NumericTraits< TPixel >::max()); if(realMax < NumericTraits< TPixel >::max()) { pixelMax = static_cast< TPixel >(realMax); } m_Color[7].Set(pixelMax,pixelMax,pixelMax); m_ColorName[7] = "White"; } template< typename TPixel > void ColorTable< TPixel > ::UseGrayColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType range; typename NumericTraits< TPixel >::RealType minimum; if (NumericTraits<TPixel>::is_integer) { range = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); minimum = NumericTraits< TPixel >::NonpositiveMin(); } else { range = NumericTraits< TPixel >::One; minimum = NumericTraits< TPixel >::Zero; } typename NumericTraits< TPixel >::RealType delta; if (m_NumberOfColors > 1) { delta = range / ( m_NumberOfColors - 1 ); } else { delta = 0.0; } for ( i = 0; i < m_NumberOfColors; i++ ) { typename NumericTraits< TPixel >::RealType realGray( minimum + i * delta ); TPixel gray = NumericTraits< TPixel >::max(); if( realGray < NumericTraits< TPixel >::max() ) { gray = static_cast< TPixel >(realGray); } m_Color[i].Set(gray, gray, gray); std::ostringstream name; name << "Gray" << std::fixed << std::setprecision(2) << static_cast<float>(gray); m_ColorName[i] = name.str(); } } template< typename TPixel > void ColorTable< TPixel > ::UseHeatColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType scale; typename NumericTraits< TPixel >::RealType shift; if (NumericTraits<TPixel>::is_integer) { scale = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); shift = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); } else { scale = NumericTraits< TPixel >::One; shift = NumericTraits< TPixel >::Zero; } for ( i = 0; i < n / 2.0; i++ ) { // // avoid overflow typename NumericTraits < TPixel >::RealType realR((( i + 1 ) / ( n / 2.0 + 1 ) ) * scale + shift); TPixel r(NumericTraits< TPixel >::max()); if(realR < NumericTraits< TPixel >::max()) { r = static_cast< TPixel >(realR); } TPixel g(static_cast<TPixel>( shift)); TPixel b(static_cast<TPixel>( shift)); m_Color[i].Set(r,g,b); std::ostringstream name; name << "Heat" << std::fixed << std::setprecision(2) << i / static_cast<float>(n); m_ColorName[i] = name.str(); } for ( i = 0; i < n / 2; i++ ) { typename NumericTraits< TPixel >::RealType rdouble(1.0 * scale + shift); TPixel r(NumericTraits<TPixel>::max()); if( rdouble < NumericTraits<TPixel>::max() ) { r = static_cast<TPixel>(rdouble); } TPixel g = static_cast<TPixel>((( i + 1 ) / ( n / 2.0 + 1 )) * scale + shift); TPixel b = static_cast<TPixel>((( i + 1 ) / ( n / 2.0 + 1 )) * scale + shift); m_Color[(size_t)(i + n / 2.0 )].Set(r,g,b); std::ostringstream name; name << "Heat" << std::fixed << std::setprecision(2) << ( i + n / 2.0 ) / (float)n; m_ColorName[static_cast<size_t>(( i + n / 2.0 ))] = name.str(); } } template< typename TPixel > void ColorTable< TPixel > ::UseRandomColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); TPixel r, g, b; TPixel minimum, maximum; if (NumericTraits<TPixel>::is_integer) { minimum = NumericTraits< TPixel >::NonpositiveMin(); maximum = NumericTraits< TPixel >::max(); } else { minimum = NumericTraits< TPixel >::Zero; maximum = NumericTraits< TPixel >::One; } for ( i = 0; i < n; i++ ) { r = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][0] = r; g = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][1] = g; b = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][2] = b; std::ostringstream name; name << "Random(" << std::fixed << std::setprecision(2) << static_cast< float >( r ) << "," << static_cast< float >( g ) << "," << static_cast< float >( b ) << ")"; m_ColorName[i] = name.str(); } } template< typename TPixel > bool ColorTable< TPixel > ::SetColor(unsigned int c, RGBPixel<TPixel> pixel, const char *name) { return this->SetColor(c, pixel[0], pixel[1], pixel[2], name); } template< typename TPixel > bool ColorTable< TPixel > ::SetColor(unsigned int c, TPixel r, TPixel g, TPixel b, const char *name) { if ( c < m_NumberOfColors ) { m_Color[c][0] = r; m_Color[c][1] = g; m_Color[c][2] = b; m_ColorName[c] = name; return true; } return false; } template< typename TPixel > RGBPixel< TPixel > ColorTable< TPixel > ::GetColor(unsigned int c) { if ( c < m_NumberOfColors ) { return m_Color[c]; } else { RGBPixel<TPixel> pixel; pixel.Set(0, 0, 0); return pixel; } } template< typename TPixel > TPixel ColorTable< TPixel > ::GetColorComponent(unsigned int c, char rgb) { if ( c < m_NumberOfColors ) { switch ( rgb ) { case 'r': { return m_Color[c][0]; } case 'g': { return m_Color[c][1]; } case 'b': { return m_Color[c][2]; } default: { return 0; } } } else { return 0; } } template< typename TPixel > std::string ColorTable< TPixel > ::GetColorName(unsigned int c) { if ( c < m_NumberOfColors ) { return m_ColorName[c]; } else { return NULL; } } template< typename TPixel > unsigned int ColorTable< TPixel > ::GetClosestColorTableId(TPixel r, TPixel g, TPixel b) { double match; double bestMatch = 0; unsigned int bestMatchColor = 0; for ( unsigned int i = 0; i < m_NumberOfColors; i++ ) { match = ( r - (double)m_Color[i].GetRed() ) * ( r - (double)m_Color[i].GetRed() ); match += ( g - (double)m_Color[i].GetGreen() ) * ( g - (double)m_Color[i].GetGreen() ); match += ( b - (double)m_Color[i].GetGreen() ) * ( b - (double)m_Color[i].GetBlue() ); if ( i == 0 || match < bestMatch ) { bestMatch = match; bestMatchColor = i; } } return bestMatchColor; } } // namespace itk #endif <commit_msg>STYLE: 14th Ann Reduce variable scope.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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. * *=========================================================================*/ #ifndef __itkColorTable_hxx #define __itkColorTable_hxx #include "itkColorTable.h" #include "itkNumericTraits.h" #include "vnl/vnl_sample.h" #include <sstream> #include <iomanip> namespace itk { template< typename TPixel > ColorTable< TPixel > ::ColorTable() { m_NumberOfColors = 0; } template< typename TPixel > void ColorTable< TPixel > ::DeleteColors() { m_Color.resize(0); m_ColorName.resize(0); } template< typename TPixel > void ColorTable< TPixel > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfColors = " << m_NumberOfColors << std::endl; for ( unsigned int i = 0; i < m_NumberOfColors; i++ ) { os << indent << "ColorName[" << i << "] = " << m_ColorName[i] << ", " << "Color[" << i << "] = " << m_Color[i] << std::endl; } } template< typename TPixel > void ColorTable< TPixel > ::UseDiscreteColors(void) { this->DeleteColors(); m_NumberOfColors = 8; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType scale; typename NumericTraits< TPixel >::RealType shift; if (NumericTraits<TPixel>::is_integer) { scale = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); shift = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); } else { scale = NumericTraits< TPixel >::One; shift = NumericTraits< TPixel >::Zero; } m_Color[0].Set((TPixel)(0.9 * scale + shift), (TPixel)( shift), (TPixel)( shift) ); m_ColorName[0] = "Red"; m_Color[1].Set((TPixel)(0.8 * scale + shift), (TPixel)( shift), (TPixel)(0.8 * scale + shift)); m_ColorName[1] = "Purple"; m_Color[2].Set((TPixel)( shift), (TPixel)(0.8 * scale + shift), (TPixel)(0.8 * scale + shift)); m_ColorName[2] = "Aqua"; m_Color[3].Set((TPixel)(0.8 * scale + shift), (TPixel)(0.8 * scale + shift), (TPixel)( shift)); m_ColorName[3] = "Yellow"; m_Color[4].Set((TPixel)( shift), (TPixel)(0.9 * scale + shift), (TPixel)( shift)); m_ColorName[4] = "Green"; m_Color[5].Set((TPixel)( shift), (TPixel)( shift), (TPixel)(0.9 * scale + shift)); m_ColorName[5] = "Blue"; m_Color[6].Set((TPixel)(0.7 * scale + shift), (TPixel)(0.7 * scale + shift), (TPixel)(0.7 * scale + shift)); m_ColorName[6] = "Grey0.70"; // // to avoid numeric exception, need to make // sure that the value assigned is clamped at // max for TPixel. Exceptions were happening // on this assignment, even if realMax was // set to NumericTraits<TPixel>::max(). typename NumericTraits< TPixel >::RealType realMax(1.0 * scale + shift); TPixel pixelMax(NumericTraits< TPixel >::max()); if(realMax < NumericTraits< TPixel >::max()) { pixelMax = static_cast< TPixel >(realMax); } m_Color[7].Set(pixelMax,pixelMax,pixelMax); m_ColorName[7] = "White"; } template< typename TPixel > void ColorTable< TPixel > ::UseGrayColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType range; typename NumericTraits< TPixel >::RealType minimum; if (NumericTraits<TPixel>::is_integer) { range = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); minimum = NumericTraits< TPixel >::NonpositiveMin(); } else { range = NumericTraits< TPixel >::One; minimum = NumericTraits< TPixel >::Zero; } typename NumericTraits< TPixel >::RealType delta; if (m_NumberOfColors > 1) { delta = range / ( m_NumberOfColors - 1 ); } else { delta = 0.0; } for ( i = 0; i < m_NumberOfColors; i++ ) { typename NumericTraits< TPixel >::RealType realGray( minimum + i * delta ); TPixel gray = NumericTraits< TPixel >::max(); if( realGray < NumericTraits< TPixel >::max() ) { gray = static_cast< TPixel >(realGray); } m_Color[i].Set(gray, gray, gray); std::ostringstream name; name << "Gray" << std::fixed << std::setprecision(2) << static_cast<float>(gray); m_ColorName[i] = name.str(); } } template< typename TPixel > void ColorTable< TPixel > ::UseHeatColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); typename NumericTraits< TPixel >::RealType scale; typename NumericTraits< TPixel >::RealType shift; if (NumericTraits<TPixel>::is_integer) { scale = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::max()) - static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); shift = static_cast< typename NumericTraits< TPixel >::RealType>(NumericTraits< TPixel >::NonpositiveMin()); } else { scale = NumericTraits< TPixel >::One; shift = NumericTraits< TPixel >::Zero; } for ( i = 0; i < n / 2.0; i++ ) { // // avoid overflow typename NumericTraits < TPixel >::RealType realR((( i + 1 ) / ( n / 2.0 + 1 ) ) * scale + shift); TPixel r(NumericTraits< TPixel >::max()); if(realR < NumericTraits< TPixel >::max()) { r = static_cast< TPixel >(realR); } TPixel g(static_cast<TPixel>( shift)); TPixel b(static_cast<TPixel>( shift)); m_Color[i].Set(r,g,b); std::ostringstream name; name << "Heat" << std::fixed << std::setprecision(2) << i / static_cast<float>(n); m_ColorName[i] = name.str(); } for ( i = 0; i < n / 2; i++ ) { typename NumericTraits< TPixel >::RealType rdouble(1.0 * scale + shift); TPixel r(NumericTraits<TPixel>::max()); if( rdouble < NumericTraits<TPixel>::max() ) { r = static_cast<TPixel>(rdouble); } TPixel g = static_cast<TPixel>((( i + 1 ) / ( n / 2.0 + 1 )) * scale + shift); TPixel b = static_cast<TPixel>((( i + 1 ) / ( n / 2.0 + 1 )) * scale + shift); m_Color[(size_t)(i + n / 2.0 )].Set(r,g,b); std::ostringstream name; name << "Heat" << std::fixed << std::setprecision(2) << ( i + n / 2.0 ) / (float)n; m_ColorName[static_cast<size_t>(( i + n / 2.0 ))] = name.str(); } } template< typename TPixel > void ColorTable< TPixel > ::UseRandomColors(unsigned int n) { unsigned int i; this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); TPixel r, g, b; TPixel minimum, maximum; if (NumericTraits<TPixel>::is_integer) { minimum = NumericTraits< TPixel >::NonpositiveMin(); maximum = NumericTraits< TPixel >::max(); } else { minimum = NumericTraits< TPixel >::Zero; maximum = NumericTraits< TPixel >::One; } for ( i = 0; i < n; i++ ) { r = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][0] = r; g = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][1] = g; b = static_cast< TPixel >( vnl_sample_uniform( minimum, maximum)); m_Color[i][2] = b; std::ostringstream name; name << "Random(" << std::fixed << std::setprecision(2) << static_cast< float >( r ) << "," << static_cast< float >( g ) << "," << static_cast< float >( b ) << ")"; m_ColorName[i] = name.str(); } } template< typename TPixel > bool ColorTable< TPixel > ::SetColor(unsigned int c, RGBPixel<TPixel> pixel, const char *name) { return this->SetColor(c, pixel[0], pixel[1], pixel[2], name); } template< typename TPixel > bool ColorTable< TPixel > ::SetColor(unsigned int c, TPixel r, TPixel g, TPixel b, const char *name) { if ( c < m_NumberOfColors ) { m_Color[c][0] = r; m_Color[c][1] = g; m_Color[c][2] = b; m_ColorName[c] = name; return true; } return false; } template< typename TPixel > RGBPixel< TPixel > ColorTable< TPixel > ::GetColor(unsigned int c) { if ( c < m_NumberOfColors ) { return m_Color[c]; } else { RGBPixel<TPixel> pixel; pixel.Set(0, 0, 0); return pixel; } } template< typename TPixel > TPixel ColorTable< TPixel > ::GetColorComponent(unsigned int c, char rgb) { if ( c < m_NumberOfColors ) { switch ( rgb ) { case 'r': { return m_Color[c][0]; } case 'g': { return m_Color[c][1]; } case 'b': { return m_Color[c][2]; } default: { return 0; } } } else { return 0; } } template< typename TPixel > std::string ColorTable< TPixel > ::GetColorName(unsigned int c) { if ( c < m_NumberOfColors ) { return m_ColorName[c]; } else { return NULL; } } template< typename TPixel > unsigned int ColorTable< TPixel > ::GetClosestColorTableId(TPixel r, TPixel g, TPixel b) { double bestMatch = 0.0; unsigned int bestMatchColor = 0; for ( unsigned int i = 0; i < m_NumberOfColors; i++ ) { double match; match = ( r - (double)m_Color[i].GetRed() ) * ( r - (double)m_Color[i].GetRed() ); match += ( g - (double)m_Color[i].GetGreen() ) * ( g - (double)m_Color[i].GetGreen() ); match += ( b - (double)m_Color[i].GetGreen() ) * ( b - (double)m_Color[i].GetBlue() ); if ( i == 0 || match < bestMatch ) { bestMatch = match; bestMatchColor = i; } } return bestMatchColor; } } // namespace itk #endif <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include <Ogre.h> #include <OgreTextAreaOverlayElement.h> #include "EC_OgreConsoleOverlay.h" #include "OgreRenderingModule.h" #include "Renderer.h" namespace OgreRenderer { EC_OgreConsoleOverlay::EC_OgreConsoleOverlay(Foundation::ModuleInterface* module) : EC_OgreConsoleOverlayInterface(module->GetFramework()) , overlay_element_(NULL) , container_(NULL) , overlay_(NULL) , renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()) , height_(module->GetFramework()->GetDefaultConfig().DeclareSetting("DebugConsole", "height", 0.4f)) // , char_height_(0.0175f) , char_height_(module->GetFramework()->GetDefaultConfig().DeclareSetting("DebugConsole", "font_height", 0.0175f)) , visible_(false) , max_visible_lines_( height_ / char_height_ * 0.91876f ) , position_(0) , speed_(3.0f) , active_(visible_) { CreateOverlay(); } EC_OgreConsoleOverlay::EC_OgreConsoleOverlay(const EC_OgreConsoleOverlay &other) : EC_OgreConsoleOverlayInterface(other) , height_(other.height_) , char_height_(other.char_height_) , max_visible_lines_(other.max_visible_lines_) , speed_(3.0f) { // not meant to be used but still needed, since components are generally meant to be copyable assert (false); } EC_OgreConsoleOverlay::~EC_OgreConsoleOverlay() { // Funny thing, Ogre manual says not to destroy overlay elements while // they are still contained in some Overlay but doing this in any other // way seems to cause crashes. if (renderer_.expired() == false) { Ogre::OverlayManager::getSingleton().destroyOverlayElement("ConsoleText"); Ogre::OverlayManager::getSingleton().destroyOverlayElement("ConsoleContainer"); Ogre::OverlayManager::getSingleton().destroy("Console"); } } void EC_OgreConsoleOverlay::CreateOverlay() { // Creating second console overlay component is a programming error in any case, // so we let Ogre throw exception if that happens. if (renderer_.expired()) return; overlay_element_ = checked_static_cast<Ogre::TextAreaOverlayElement*>(Ogre::OverlayManager::getSingleton().createOverlayElement("TextArea", "ConsoleText")); overlay_element_->setCaption("Console"); overlay_element_->setColour(Ogre::ColourValue::Black); overlay_element_->setDimensions(0.98f, height_); overlay_element_->setPosition(0.01f, 0.01f); overlay_element_->setFontName("Console"); overlay_element_->setCharHeight(char_height_); overlay_element_->show(); overlay_ = Ogre::OverlayManager::getSingleton().create("Console"); container_ = checked_static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "ConsoleContainer")); container_->setPosition(0.f, -height_); container_->setDimensions(1.f, height_); container_->setMaterialName("Console"); container_->addChild(overlay_element_); container_->show(); overlay_->add2D(container_); if (visible_) overlay_->show(); else overlay_->hide(); overlay_->setZOrder(500); } void EC_OgreConsoleOverlay::Display(const std::string &text) { //! \todo render mutex here -cm if (renderer_.expired()) return; overlay_element_->setCaption(text); } void EC_OgreConsoleOverlay::SetVisible(bool visible) { visible_ = visible; if (visible && !renderer_.expired()) overlay_->show(); active_ = visible; } bool EC_OgreConsoleOverlay::IsVisible() const { if (renderer_.expired()) return false; return overlay_->isVisible(); } void EC_OgreConsoleOverlay::Update(Core::f64 frametime) { if (renderer_.expired()) return; if (visible_ && position_ < Ogre::Math::HALF_PI) { position_ += frametime * speed_; if (position_ > Ogre::Math::HALF_PI) position_ = Ogre::Math::HALF_PI; container_->setTop( -height_ + Ogre::Math::Sin(position_) * height_); } else if (visible_ == false && abs(position_) > 0.001f) { position_ -= frametime * speed_; if (position_ <= 0.f) { position_ = 0.f; overlay_->hide(); } container_->setTop( -height_ + Ogre::Math::Sin(position_) * height_); } } } <commit_msg>Ogre console overlay speed is now defined in configuration file rather than being hardcoded.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include <Ogre.h> #include <OgreTextAreaOverlayElement.h> #include "EC_OgreConsoleOverlay.h" #include "OgreRenderingModule.h" #include "Renderer.h" namespace OgreRenderer { EC_OgreConsoleOverlay::EC_OgreConsoleOverlay(Foundation::ModuleInterface* module) : EC_OgreConsoleOverlayInterface(module->GetFramework()) , overlay_element_(NULL) , container_(NULL) , overlay_(NULL) , renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()) , height_(module->GetFramework()->GetDefaultConfig().DeclareSetting("DebugConsole", "height", 0.4f)) // , char_height_(0.0175f) , char_height_(module->GetFramework()->GetDefaultConfig().DeclareSetting("DebugConsole", "font_height", 0.0175f)) , visible_(false) , max_visible_lines_( height_ / char_height_ * 0.91876f ) , position_(0) , speed_(module->GetFramework()->GetDefaultConfig().DeclareSetting("DebugConsole", "appear_speed", 3.0f)) , active_(visible_) { CreateOverlay(); } EC_OgreConsoleOverlay::EC_OgreConsoleOverlay(const EC_OgreConsoleOverlay &other) : EC_OgreConsoleOverlayInterface(other) , height_(other.height_) , char_height_(other.char_height_) , max_visible_lines_(other.max_visible_lines_) , speed_(3.0f) { // not meant to be used but still needed, since components are generally meant to be copyable assert (false); } EC_OgreConsoleOverlay::~EC_OgreConsoleOverlay() { // Funny thing, Ogre manual says not to destroy overlay elements while // they are still contained in some Overlay but doing this in any other // way seems to cause crashes. if (renderer_.expired() == false) { Ogre::OverlayManager::getSingleton().destroyOverlayElement("ConsoleText"); Ogre::OverlayManager::getSingleton().destroyOverlayElement("ConsoleContainer"); Ogre::OverlayManager::getSingleton().destroy("Console"); } } void EC_OgreConsoleOverlay::CreateOverlay() { // Creating second console overlay component is a programming error in any case, // so we let Ogre throw exception if that happens. if (renderer_.expired()) return; overlay_element_ = checked_static_cast<Ogre::TextAreaOverlayElement*>(Ogre::OverlayManager::getSingleton().createOverlayElement("TextArea", "ConsoleText")); overlay_element_->setCaption("Console"); overlay_element_->setColour(Ogre::ColourValue::Black); overlay_element_->setDimensions(0.98f, height_); overlay_element_->setPosition(0.01f, 0.01f); overlay_element_->setFontName("Console"); overlay_element_->setCharHeight(char_height_); overlay_element_->show(); overlay_ = Ogre::OverlayManager::getSingleton().create("Console"); container_ = checked_static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "ConsoleContainer")); container_->setPosition(0.f, -height_); container_->setDimensions(1.f, height_); container_->setMaterialName("Console"); container_->addChild(overlay_element_); container_->show(); overlay_->add2D(container_); if (visible_) overlay_->show(); else overlay_->hide(); overlay_->setZOrder(500); } void EC_OgreConsoleOverlay::Display(const std::string &text) { //! \todo render mutex here -cm if (renderer_.expired()) return; overlay_element_->setCaption(text); } void EC_OgreConsoleOverlay::SetVisible(bool visible) { visible_ = visible; if (visible && !renderer_.expired()) overlay_->show(); active_ = visible; } bool EC_OgreConsoleOverlay::IsVisible() const { if (renderer_.expired()) return false; return overlay_->isVisible(); } void EC_OgreConsoleOverlay::Update(Core::f64 frametime) { if (renderer_.expired()) return; if (visible_ && position_ < Ogre::Math::HALF_PI) { position_ += frametime * speed_; if (position_ > Ogre::Math::HALF_PI) position_ = Ogre::Math::HALF_PI; container_->setTop( -height_ + Ogre::Math::Sin(position_) * height_); } else if (visible_ == false && abs(position_) > 0.001f) { position_ -= frametime * speed_; if (position_ <= 0.f) { position_ = 0.f; overlay_->hide(); } container_->setTop( -height_ + Ogre::Math::Sin(position_) * height_); } } } <|endoftext|>
<commit_before>#include <OpenSim/OpenSim.h> namespace OpenSim { class ComponentContainer : public ModelComponent { OpenSim_DECLARE_CONCRETE_OBJECT(ComponentContainer, Component); public: OpenSim_DECLARE_LIST_PROPERTY(components, Component, "List of serialized internal components"); ComponentContainer() { constructInfrastructure(); } void adopt(Component* comp) { // add it the property list of components that owns and serializes them updProperty_components().adoptAndAppendValue(comp); finalizeFromProperties(); } private: void constructProperties() override { constructProperty_components(); } }; /** * This produces a control signal k * a, where `k` is the gain property, and * `a` is the activation input. This is intended to model proportional * myoelectric device controllers. This Controller can control any * ScalarActuator. The ScalarActuator that this control controls is set using * the `device` connector. * * http://en.wikipedia.org/wiki/Proportional_Myoelectric_Control */ class PropMyoController : public OpenSim::Controller { OpenSim_DECLARE_CONCRETE_OBJECT(PropMyoController, OpenSim::Controller); public: OpenSim_DECLARE_PROPERTY(gain, double, "Gain used in converting muscle activation into a" " control signal (units depend on the device)"); PropMyoController() { constructInfrastructure(); } void computeControls(const SimTK::State& s, SimTK::Vector& controls) const override { double activation = getInputValue<double>(s, "activation"); // Compute the control signal. double signal = get_gain() * activation; // Add in this control signal to controls. const auto& device = getConnectee<Actuator>("device"); SimTK::Vector thisActuatorsControls(1, signal); device.addInControls(thisActuatorsControls, controls); } private: void constructProperties() override { constructProperty_gain(1.0); } void constructConnectors() override { // The ScalarActuator for which we're computing a control signal. constructConnector<Actuator>("device"); } void constructInputs() override { // The control signal is proportional to this input. constructInput<double>("activation", SimTK::Stage::Model); } void constructOutputs() override { constructOutput<double>("constant", [] (const SimTK::State&) { return 2;}, SimTK::Stage::Model); } }; } // namespace OpenSim int main() { using SimTK::Vec3; using SimTK::Inertia; using SimTK::Pi; // Create a sphere geometry to reuse later. OpenSim::Sphere sphere{0.1}; sphere.setName("sphere"); // Create the device to hold the components. //------------------------------------------------------------------------- auto device = new OpenSim::ComponentContainer{}; device->setName("device"); // Two body(s), with mass of 1 kg, center of mass at the // origin of their respective frames, and moments/products of inertia of // zero. auto massA = new OpenSim::Body("massA", 1, Vec3(0), Inertia(1)); auto massB = new OpenSim::Body("massB", 1, Vec3(0), Inertia(1)); // Add the masses to the device. device->adopt(massA); device->adopt(massB); // Sphere geometry for the masses. sphere.setFrameName("massA"); massA->append_geometry(sphere); sphere.setFrameName("massB"); massB->append_geometry(sphere); // Joint from something in the environment to massA. auto anchorA = new OpenSim::WeldJoint(); anchorA->setName("anchorA"); // Set only the child now. Parent will be in the environment. anchorA->setChildFrameName("massA"); device->adopt(anchorA); // Joint from something in the environment to massB. auto anchorB = new OpenSim::WeldJoint(); anchorB->setName("anchorB"); // Set only the child now. Parent will be in the environment. anchorB->setChildFrameName("massB"); device->adopt(anchorB); // Actuator connecting the two masses. auto pathActuator = new OpenSim::PathActuator(); pathActuator->setName("cableAtoB"); pathActuator->addNewPathPoint("point1", *massA, Vec3(0)); pathActuator->addNewPathPoint("point2", *massB, Vec3(0)); device->adopt(pathActuator); // A controller that specifies the excitation of the biceps muscle. auto controller = new OpenSim::PropMyoController(); controller->setName("controller"); controller->getInput("activation"). connect(controller->getOutput("constant")); controller->updConnector<OpenSim::Actuator>("device"). connect(*pathActuator); device->adopt(controller); // Build a test environment for the device. //------------------------------------------------------------------------- OpenSim::Model model; model.setUseVisualizer(true); model.setGravity(Vec3(0)); // Create a load of mass 10kg. auto load = new OpenSim::Body("load", 10, Vec3(0), Inertia(1)); // Set properties of the sphere geometry to be used for the load. sphere.setFrameName("load"); sphere.set_radius(0.2); sphere.setOpacity(0.5); sphere.setColor(Vec3{0, 0, 1}); load->append_geometry(sphere); model.addBody(load); auto grndToLoad = new OpenSim::FreeJoint("grndToLoad", "ground", "load"); // Set the location of the load to (1, 0, 0). grndToLoad->getCoordinateSet()[3].setDefaultValue(1); model.addJoint(grndToLoad); // Connect device to/from the environment. //------------------------------------------------------------------------- // Set parent of anchorA as ground. anchorA->setParentFrameName("ground"); // Set parent of anchorB as load. anchorB->setParentFrameName("load"); // Add bodies and joints to the model. model.addModelComponent(device); // Print the model. model.print("exampleHopperDevice.xml"); // Configure the model. auto& state = model.initSystem(); // Add display geometry. model.updMatterSubsystem().setShowDefaultGeometry(true); auto& viz = model.updVisualizer().updSimbodyVisualizer(); // Simulate. SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem()); OpenSim::Manager manager(model, integrator); manager.setInitialTime(0); manager.setFinalTime(10.0); manager.integrate(state); }; <commit_msg>Segrate calls into simulate method.<commit_after>#include <OpenSim/OpenSim.h> namespace OpenSim { class ComponentContainer : public ModelComponent { OpenSim_DECLARE_CONCRETE_OBJECT(ComponentContainer, Component); public: OpenSim_DECLARE_LIST_PROPERTY(components, Component, "List of serialized internal components"); ComponentContainer() { constructInfrastructure(); } void adopt(Component* comp) { // add it the property list of components that owns and serializes them updProperty_components().adoptAndAppendValue(comp); finalizeFromProperties(); } private: void constructProperties() override { constructProperty_components(); } }; /** * This produces a control signal k * a, where `k` is the gain property, and * `a` is the activation input. This is intended to model proportional * myoelectric device controllers. This Controller can control any * ScalarActuator. The ScalarActuator that this control controls is set using * the `device` connector. * * http://en.wikipedia.org/wiki/Proportional_Myoelectric_Control */ class PropMyoController : public OpenSim::Controller { OpenSim_DECLARE_CONCRETE_OBJECT(PropMyoController, OpenSim::Controller); public: OpenSim_DECLARE_PROPERTY(gain, double, "Gain used in converting muscle activation into a" " control signal (units depend on the device)"); PropMyoController() { constructInfrastructure(); } void computeControls(const SimTK::State& s, SimTK::Vector& controls) const override { double activation = getInputValue<double>(s, "activation"); // Compute the control signal. double signal = get_gain() * activation; // Add in this control signal to controls. const auto& device = getConnectee<Actuator>("device"); SimTK::Vector thisActuatorsControls(1, signal); device.addInControls(thisActuatorsControls, controls); } private: void constructProperties() override { constructProperty_gain(1.0); } void constructConnectors() override { // The ScalarActuator for which we're computing a control signal. constructConnector<Actuator>("device"); } void constructInputs() override { // The control signal is proportional to this input. constructInput<double>("activation", SimTK::Stage::Model); } void constructOutputs() override { constructOutput<double>("constant", [] (const SimTK::State&) { return 2;}, SimTK::Stage::Model); } }; } // namespace OpenSim void simulate(OpenSim::Model& model) { // Configure the model. auto& state = model.initSystem(); model.updMatterSubsystem().setShowDefaultGeometry(true); // Simulate. SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem()); OpenSim::Manager manager(model, integrator); manager.setInitialTime(0); manager.setFinalTime(10.0); manager.integrate(state); } int main() { using SimTK::Vec3; using SimTK::Inertia; using SimTK::Pi; // Create a sphere geometry to reuse later. OpenSim::Sphere sphere{0.1}; sphere.setName("sphere"); // Create the device to hold the components. //------------------------------------------------------------------------- auto device = new OpenSim::ComponentContainer{}; device->setName("device"); // Two body(s), with mass of 1 kg, center of mass at the // origin of their respective frames, and moments/products of inertia of // zero. auto massA = new OpenSim::Body("massA", 1, Vec3(0), Inertia(1)); auto massB = new OpenSim::Body("massB", 1, Vec3(0), Inertia(1)); // Add the masses to the device. device->adopt(massA); device->adopt(massB); // Sphere geometry for the masses. sphere.setFrameName("massA"); massA->append_geometry(sphere); sphere.setFrameName("massB"); massB->append_geometry(sphere); // Joint from something in the environment to massA. auto anchorA = new OpenSim::WeldJoint(); anchorA->setName("anchorA"); // Set only the child now. Parent will be in the environment. anchorA->setChildFrameName("massA"); device->adopt(anchorA); // Joint from something in the environment to massB. auto anchorB = new OpenSim::WeldJoint(); anchorB->setName("anchorB"); // Set only the child now. Parent will be in the environment. anchorB->setChildFrameName("massB"); device->adopt(anchorB); // Actuator connecting the two masses. auto pathActuator = new OpenSim::PathActuator(); pathActuator->setName("cableAtoB"); pathActuator->addNewPathPoint("point1", *massA, Vec3(0)); pathActuator->addNewPathPoint("point2", *massB, Vec3(0)); device->adopt(pathActuator); // A controller that specifies the excitation of the biceps muscle. auto controller = new OpenSim::PropMyoController(); controller->setName("controller"); controller->getInput("activation"). connect(controller->getOutput("constant")); controller->updConnector<OpenSim::Actuator>("device"). connect(*pathActuator); device->adopt(controller); // Build a test environment for the device. //------------------------------------------------------------------------- OpenSim::Model testBed; testBed.setUseVisualizer(true); testBed.setGravity(Vec3(0)); // Create a load of mass 10kg. auto load = new OpenSim::Body("load", 10, Vec3(0), Inertia(1)); // Set properties of the sphere geometry to be used for the load. sphere.setFrameName("load"); sphere.set_radius(0.2); sphere.setOpacity(0.5); sphere.setColor(Vec3{0, 0, 1}); load->append_geometry(sphere); testBed.addBody(load); auto grndToLoad = new OpenSim::FreeJoint("grndToLoad", "ground", "load"); // Set the location of the load to (1, 0, 0). grndToLoad->getCoordinateSet()[3].setDefaultValue(1); testBed.addJoint(grndToLoad); // Connect device to/from the environment. //------------------------------------------------------------------------- // Set parent of anchorA as ground. anchorA->setParentFrameName("ground"); // Set parent of anchorB as load. anchorB->setParentFrameName("load"); // Add bodies and joints to the testBed. testBed.addModelComponent(device); // Print the testBed. testBed.print("exampleHopperDevice.xml"); simulate(testBed); }; <|endoftext|>
<commit_before><commit_msg>Storytelling: Retire notification as we have customized UI now.<commit_after><|endoftext|>
<commit_before> #include "pch.h" #include "slackapp.h" #include "utils.h" using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams //web::http::client::http_client::~http_client() noexcept {} pplx::task<bool> slack_app::test_access_token(const string_t &access_token) { printf("authing\n"); auto path = U("auth.test?token=") + access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { return json.as_object() .at(U("ok")) .as_bool(); }); } pplx::task<utility::string_t> slack_app::get_userid(const string_t &access_token) { auto path = U("auth.test?token=") + access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { return json.as_object() .at(U("user_id")) .as_string(); }); } pplx::task<web::uri> slack_app::get_ws_url() { auto path = U("rtm.connect?token=") + _bot_access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { auto obj = json.as_object(); auto isok = obj.at(U("ok")).as_bool(); if (isok) { auto url = obj.at(U("url")).as_string(); return web::uri{ url }; } else { throw std::runtime_error(N(obj.at(U("error")).as_string())); } }); } pplx::task<void> slack_app::verify_access_tokens() { printf("verifying\n"); std::array<pplx::task<bool>, 2> tasks { test_access_token(_access_token), test_access_token(_bot_access_token) }; pplx::task<void> combined = pplx::when_all(std::begin(tasks), std::end(tasks)) .then([](std::vector<bool> results) { printf("checking\n"); auto at_ok = results[0]; auto bat_ok = results[1]; if (!at_ok || !bat_ok) { std::string messages("Could not authenticate"); if (!at_ok) { messages += "\n Problem with access token"; } if (!bat_ok) { messages += "\n Problem with bot access token"; } throw std::runtime_error(messages); } }); return combined; } pplx::task<void> slack_app::listen() { pplx::task_completion_event<void> tce; pplx::task<void> completed(tce); return async_do_while([=]() { return _rtm_client.receive().then([=](web::websockets::client::websocket_incoming_message in_msg) { return in_msg.extract_string().then([=](std::string msg_str) { string_t msg_str_t = W(msg_str); json::value json_val = json::value::parse(msg_str_t); handle_message(json_val); }); }).then([=](pplx::task<void> end_task) { try { end_task.get(); return true; } catch (std::exception &e) { printf("ws error: %s\n", e.what()); } catch (...) { printf("unkown error\n"); } // We are here means we encountered some exception. // Return false to break the asynchronous loop. return false; }); }); } pplx::task<void> slack_app::handle_message(web::json::value message) { printf("message:\n%s\n", N(message.serialize()).c_str()); auto vtype = message[U("type")]; auto vreply = message[U("reply_to")]; if(vtype.is_string()) { auto type = message[U("type")].as_string(); if (type == U("hello")) { printf("received hello message\n"); } else if (type == U("reconnect_url")) { auto new_url = message[U("url")].as_string(); _rtm_url = new_url; printf("received new connect URL\n"); } else if (type == U("message")) { auto text = message[U("text")].as_string(); auto channel = message[U("channel")].as_string(); auto from = message[U("user")].as_string(); printf("got message: %s from %s\n", N(text).c_str(), N(from).c_str()); if(from != _bot_userid) { auto emojis = get_emojis_in_message(N(text)); sequential_transform(emojis.begin(), emojis.end(), [=] (std::string p) -> pplx::task<std::pair<std::string, std::string>> { return get_emoji_url(p).then([=](std::string url) { return std::make_pair(p, url); }); }) .then([=] (std::vector<std::pair<std::string, std::string>> urls) { std::string replymsg; if (urls.size()) { replymsg = "you specified these emojis: \n"; for (auto&pair : urls) { std::string url; if(pair.second.empty()) { url = ":question:"; } else { url = pair.second; } replymsg += " " + pair.first + " -> " + url + "\n"; } } else { replymsg = "you did not specify any emojis"; } return send_message(W(replymsg), channel); }); } } else if (type == U("presence_change") || type == U("desktop_notification")) { } else { } } else if(vreply.is_number()) { } return pplx::task_from_result(); } pplx::task<void> slack_app::send_message(const utility::string_t &text, const utility::string_t &channel) { auto obj = json::value::object(); obj[U("id")] = json::value::number(++_messageid); obj[U("type")] = json::value::string(U("message")); obj[U("channel")] = json::value::string(channel); obj[U("text")] = json::value::string(text); websockets::client::websocket_outgoing_message message; message.set_utf8_message(N(obj.serialize())); return _rtm_client.send(message); } static std::regex rx_emoji(":([-a-zA-Z0-9_+]+):"); std::vector<std::string> slack_app::get_emojis_in_message(const std::string &s) const { std::vector<std::string> result; auto emojis_begin = std::sregex_iterator(s.begin(), s.end(), rx_emoji); auto emojis_end = std::sregex_iterator(); for (std::sregex_iterator i = emojis_begin; i != emojis_end; ++i) { std::smatch match = *i; std::string match_str = match.str(1); result.push_back(match_str); } std::sort(result.begin(), result.end()); auto last = std::unique(result.begin(), result.end()); result.erase(last, result.end()); return result; } pplx::task<std::map<std::string, std::string>> slack_app::get_custom_emojis() { auto path = U("emoji.list?token=") + _access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }).then([=](json::value json) { std::map<std::string, std::string> obj_emoji; auto emojis = json[U("emoji")].as_object(); for(auto i = emojis.begin(); i != emojis.end(); ++i) { auto kvp = *i; auto key = N(kvp.first); auto val = N(kvp.second.as_string()); obj_emoji[key] = val; } return obj_emoji; }); } pplx::task<void> slack_app::process_loop() { pplx::task<void> at_verified { _access_ok ? pplx::task_from_result() : verify_access_tokens() }; // the task will resolve on disconnect return at_verified.then([=] { if(_bot_userid.empty()) { return get_userid(_bot_access_token).then([=](string_t userid) { printf("my user id: %s\n", N(userid).c_str()); _bot_userid = userid; }); } else { return pplx::task_from_result(); } }).then([=] { _access_ok = true; printf("verified\n"); //get url if(_rtm_url.is_empty()) { return get_ws_url().then([=](web::uri wsurl) { printf("got ws url\n"); _rtm_url = wsurl; }); } else { return pplx::task_from_result(); } }).then([=] { //get emojis return get_custom_emojis().then([=](std::map<std::string, std::string> emojis) { for(auto &i : emojis) { _emojis.insert_or_assign(i.first, i.second); } }); }).then([=] { //connect return _rtm_client.connect(_rtm_url); }).then([this](pplx::task<void> task) { try { task.get(); printf("connected.\n"); } catch (...) { printf("connection error.\n"); // force re-getting url _rtm_url = U(""); _access_ok = false; return pplx::task_from_result(); } return listen(); }).then([] { printf("listen over\n"); }); } pplx::task<const void*> slack_app::get_emoji_data(const std::string &emoji) { return pplx::task_from_result<const void*>(nullptr); } pplx::task<std::string> slack_app::get_emoji_url(const std::string &emoji) { //try cached emoji auto found = _emojis.find(emoji); if(found != _emojis.end()) { return pplx::task_from_result(found->second); } else { //get emojis again return get_custom_emojis().then([this,emoji](std::map<std::string, std::string> emojis) { // cache new custom emojis for (auto &i : emojis) { _emojis.insert_or_assign(i.first, i.second); } // find from custom emojis auto found2 = _emojis.find(emoji); if (found2 != _emojis.end()) { return found2->second; } else { return std::string(); } }); } } void slack_app::run() { printf("enteing\n"); auto task = async_do_while([=] { return process_loop().then([=] { return true; }); }); task.wait(); }<commit_msg>Fixed a problem where modifying past messages cause a crash<commit_after> #include "pch.h" #include "slackapp.h" #include "utils.h" using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams //web::http::client::http_client::~http_client() noexcept {} pplx::task<bool> slack_app::test_access_token(const string_t &access_token) { printf("authing\n"); auto path = U("auth.test?token=") + access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { return json.as_object() .at(U("ok")) .as_bool(); }); } pplx::task<utility::string_t> slack_app::get_userid(const string_t &access_token) { auto path = U("auth.test?token=") + access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { return json.as_object() .at(U("user_id")) .as_string(); }); } pplx::task<web::uri> slack_app::get_ws_url() { auto path = U("rtm.connect?token=") + _bot_access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }) .then([=](json::value json) { auto obj = json.as_object(); auto isok = obj.at(U("ok")).as_bool(); if (isok) { auto url = obj.at(U("url")).as_string(); return web::uri{ url }; } else { throw std::runtime_error(N(obj.at(U("error")).as_string())); } }); } pplx::task<void> slack_app::verify_access_tokens() { printf("verifying\n"); std::array<pplx::task<bool>, 2> tasks { test_access_token(_access_token), test_access_token(_bot_access_token) }; pplx::task<void> combined = pplx::when_all(std::begin(tasks), std::end(tasks)) .then([](std::vector<bool> results) { printf("checking\n"); auto at_ok = results[0]; auto bat_ok = results[1]; if (!at_ok || !bat_ok) { std::string messages("Could not authenticate"); if (!at_ok) { messages += "\n Problem with access token"; } if (!bat_ok) { messages += "\n Problem with bot access token"; } throw std::runtime_error(messages); } }); return combined; } pplx::task<void> slack_app::listen() { pplx::task_completion_event<void> tce; pplx::task<void> completed(tce); return async_do_while([=]() { return _rtm_client.receive().then([=](web::websockets::client::websocket_incoming_message in_msg) { return in_msg.extract_string().then([=](std::string msg_str) { string_t msg_str_t = W(msg_str); json::value json_val = json::value::parse(msg_str_t); handle_message(json_val); }); }).then([=](pplx::task<void> end_task) { try { end_task.get(); return true; } catch (std::exception &e) { printf("ws error: %s\n", e.what()); } catch (...) { printf("unkown error\n"); } // We are here means we encountered some exception. // Return false to break the asynchronous loop. return false; }); }); } pplx::task<void> slack_app::handle_message(web::json::value message) { printf("message:\n%s\n", N(message.serialize()).c_str()); auto vtype = message[U("type")]; auto vreply = message[U("reply_to")]; if(vtype.is_string()) { auto type = message[U("type")].as_string(); if (type == U("hello")) { printf("received hello message\n"); } else if (type == U("reconnect_url")) { auto new_url = message[U("url")].as_string(); _rtm_url = new_url; printf("received new connect URL\n"); } else if (type == U("message")) { auto text = message[U("text")]; std::string stext; if(text.is_string() && !(stext = N(text.as_string())).empty()) { auto channel = message[U("channel")].as_string(); auto from = message[U("user")].as_string(); printf("got message: %s from %s\n", stext.c_str(), N(from).c_str()); if(from != _bot_userid) { auto emojis = get_emojis_in_message(stext); sequential_transform(emojis.begin(), emojis.end(), [=] (std::string p) -> pplx::task<std::pair<std::string, std::string>> { return get_emoji_url(p).then([=](std::string url) { return std::make_pair(p, url); }); }) .then([=] (std::vector<std::pair<std::string, std::string>> urls) { std::string replymsg; if (urls.size()) { replymsg = "you specified these emojis: \n"; for (auto&pair : urls) { std::string url; if(pair.second.empty()) { url = ":question:"; } else { url = pair.second; } replymsg += " " + pair.first + " -> " + url + "\n"; } } else { replymsg = "you did not specify any emojis"; } return send_message(W(replymsg), channel); }); } } } else if (type == U("presence_change") || type == U("desktop_notification")) { } else { } } else if(vreply.is_number()) { } return pplx::task_from_result(); } pplx::task<void> slack_app::send_message(const utility::string_t &text, const utility::string_t &channel) { auto obj = json::value::object(); obj[U("id")] = json::value::number(++_messageid); obj[U("type")] = json::value::string(U("message")); obj[U("channel")] = json::value::string(channel); obj[U("text")] = json::value::string(text); websockets::client::websocket_outgoing_message message; message.set_utf8_message(N(obj.serialize())); return _rtm_client.send(message); } static std::regex rx_emoji(":([-a-zA-Z0-9_+]+):"); std::vector<std::string> slack_app::get_emojis_in_message(const std::string &s) const { std::vector<std::string> result; auto emojis_begin = std::sregex_iterator(s.begin(), s.end(), rx_emoji); auto emojis_end = std::sregex_iterator(); for (std::sregex_iterator i = emojis_begin; i != emojis_end; ++i) { std::smatch match = *i; std::string match_str = match.str(1); result.push_back(match_str); } std::sort(result.begin(), result.end()); auto last = std::unique(result.begin(), result.end()); result.erase(last, result.end()); return result; } pplx::task<std::map<std::string, std::string>> slack_app::get_custom_emojis() { auto path = U("emoji.list?token=") + _access_token; return _client.request(methods::POST, path) .then([=](http_response response) { return response.extract_json(); }).then([=](json::value json) { std::map<std::string, std::string> obj_emoji; auto emojis = json[U("emoji")].as_object(); for(auto i = emojis.begin(); i != emojis.end(); ++i) { auto kvp = *i; auto key = N(kvp.first); auto val = N(kvp.second.as_string()); obj_emoji[key] = val; } return obj_emoji; }); } pplx::task<void> slack_app::process_loop() { pplx::task<void> at_verified { _access_ok ? pplx::task_from_result() : verify_access_tokens() }; // the task will resolve on disconnect return at_verified.then([=] { if(_bot_userid.empty()) { return get_userid(_bot_access_token).then([=](string_t userid) { printf("my user id: %s\n", N(userid).c_str()); _bot_userid = userid; }); } else { return pplx::task_from_result(); } }).then([=] { _access_ok = true; printf("verified\n"); //get url if(_rtm_url.is_empty()) { return get_ws_url().then([=](web::uri wsurl) { printf("got ws url\n"); _rtm_url = wsurl; }); } else { return pplx::task_from_result(); } }).then([=] { //get emojis return get_custom_emojis().then([=](std::map<std::string, std::string> emojis) { for(auto &i : emojis) { _emojis.insert_or_assign(i.first, i.second); } }); }).then([=] { //connect return _rtm_client.connect(_rtm_url); }).then([this](pplx::task<void> task) { try { task.get(); printf("connected.\n"); } catch (...) { printf("connection error.\n"); // force re-getting url _rtm_url = U(""); _access_ok = false; return pplx::task_from_result(); } return listen(); }).then([] { printf("listen over\n"); }); } pplx::task<const void*> slack_app::get_emoji_data(const std::string &emoji) { return pplx::task_from_result<const void*>(nullptr); } pplx::task<std::string> slack_app::get_emoji_url(const std::string &emoji) { //try cached emoji auto found = _emojis.find(emoji); if(found != _emojis.end()) { return pplx::task_from_result(found->second); } else { //get emojis again return get_custom_emojis().then([this,emoji](std::map<std::string, std::string> emojis) { // cache new custom emojis for (auto &i : emojis) { _emojis.insert_or_assign(i.first, i.second); } // find from custom emojis auto found2 = _emojis.find(emoji); if (found2 != _emojis.end()) { return found2->second; } else { return std::string(); } }); } } void slack_app::run() { printf("enteing\n"); auto task = async_do_while([=] { return process_loop().then([=] { return true; }); }); task.wait(); }<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Coindex[1]right (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "itkTractDensityImageFilter.h" // VTK #include <vtkPolyLine.h> #include <vtkCellArray.h> #include <vtkCellData.h> // misc #include <math.h> #include <boost/progress.hpp> namespace itk{ template< class OutputImageType > TractDensityImageFilter< OutputImageType >::TractDensityImageFilter() : m_InvertImage(false) , m_FiberBundle(NULL) , m_UpsamplingFactor(1) , m_InputImage(NULL) , m_BinaryOutput(false) , m_UseImageGeometry(false) , m_OutputAbsoluteValues(false) , m_UseTrilinearInterpolation(false) { } template< class OutputImageType > TractDensityImageFilter< OutputImageType >::~TractDensityImageFilter() { } template< class OutputImageType > itk::Point<float, 3> TractDensityImageFilter< OutputImageType >::GetItkPoint(double point[3]) { itk::Point<float, 3> itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; return itkPoint; } template< class OutputImageType > void TractDensityImageFilter< OutputImageType >::GenerateData() { // generate upsampled image mitk::BaseGeometry::Pointer geometry = m_FiberBundle->GetGeometry(); typename OutputImageType::Pointer outImage = this->GetOutput(); // calculate new image parameters itk::Vector<double,3> newSpacing; mitk::Point3D newOrigin; itk::Matrix<double, 3, 3> newDirection; ImageRegion<3> upsampledRegion; if (m_UseImageGeometry && !m_InputImage.IsNull()) { MITK_INFO << "TractDensityImageFilter: using image geometry"; newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor; upsampledRegion = m_InputImage->GetLargestPossibleRegion(); newOrigin = m_InputImage->GetOrigin(); typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize(); size[0] *= m_UpsamplingFactor; size[1] *= m_UpsamplingFactor; size[2] *= m_UpsamplingFactor; upsampledRegion.SetSize(size); newDirection = m_InputImage->GetDirection(); } else { MITK_INFO << "TractDensityImageFilter: using fiber bundle geometry"; newSpacing = geometry->GetSpacing()/m_UpsamplingFactor; newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); for (int i=0; i<3; i++) for (int j=0; j<3; j++) newDirection[j][i] = geometry->GetMatrixColumn(i)[j]; upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); } typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); // apply new image parameters outImage->SetSpacing( newSpacing ); outImage->SetOrigin( newOrigin ); outImage->SetDirection( newDirection ); outImage->SetRegions( upsampledRegion ); outImage->Allocate(); outImage->FillBuffer(0.0); int w = upsampledSize[0]; int h = upsampledSize[1]; int d = upsampledSize[2]; // set/initialize output OutPixelType* outImageBufferPointer = (OutPixelType*)outImage->GetBufferPointer(); // resample fiber bundle float minSpacing = 1; if(newSpacing[0]<newSpacing[1] && newSpacing[0]<newSpacing[2]) minSpacing = newSpacing[0]; else if (newSpacing[1] < newSpacing[2]) minSpacing = newSpacing[1]; else minSpacing = newSpacing[2]; MITK_INFO << "TractDensityImageFilter: resampling fibers to ensure sufficient voxel coverage"; m_FiberBundle = m_FiberBundle->GetDeepCopy(); m_FiberBundle->ResampleSpline(minSpacing/10); MITK_INFO << "TractDensityImageFilter: starting image generation"; vtkSmartPointer<vtkPolyData> fiberPolyData = m_FiberBundle->GetFiberPolyData(); vtkSmartPointer<vtkCellArray> vLines = fiberPolyData->GetLines(); vLines->InitTraversal(); int numFibers = m_FiberBundle->GetNumFibers(); boost::progress_display disp(numFibers); for( int i=0; i<numFibers; i++ ) { ++disp; vtkIdType numPoints(0); vtkIdType* points(NULL); vLines->GetNextCell ( numPoints, points ); // fill output image for( int j=0; j<numPoints; j++) { itk::Point<float, 3> vertex = GetItkPoint(fiberPolyData->GetPoint(points[j])); itk::Index<3> index; itk::ContinuousIndex<float, 3> contIndex; outImage->TransformPhysicalPointToIndex(vertex, index); outImage->TransformPhysicalPointToContinuousIndex(vertex, contIndex); if (!m_UseTrilinearInterpolation) { if (m_BinaryOutput) outImage->SetPixel(index, 1); else outImage->SetPixel(index, outImage->GetPixel(index)+0.01); continue; } float frac_x = contIndex[0] - index[0]; float frac_y = contIndex[1] - index[1]; float frac_z = contIndex[2] - index[2]; if (frac_x<0) { index[0] -= 1; frac_x += 1; } if (frac_y<0) { index[1] -= 1; frac_y += 1; } if (frac_z<0) { index[2] -= 1; frac_z += 1; } frac_x = 1-frac_x; frac_y = 1-frac_y; frac_z = 1-frac_z; // int coordinates inside image? if (index[0] < 0 || index[0] >= w-1) continue; if (index[1] < 0 || index[1] >= h-1) continue; if (index[2] < 0 || index[2] >= d-1) continue; if (m_BinaryOutput) { outImageBufferPointer[( index[0] + w*(index[1] + h*index[2] ))] = 1; outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2] ))] = 1; outImageBufferPointer[( index[0] + w*(index[1] + h*index[2]+h))] = 1; outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2]+h))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2] ))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2]+h))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2] ))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2]+h))] = 1; } else { outImageBufferPointer[( index[0] + w*(index[1] + h*index[2] ))] += ( frac_x)*( frac_y)*( frac_z); outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2] ))] += ( frac_x)*(1-frac_y)*( frac_z); outImageBufferPointer[( index[0] + w*(index[1] + h*index[2]+h))] += ( frac_x)*( frac_y)*(1-frac_z); outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2]+h))] += ( frac_x)*(1-frac_y)*(1-frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2] ))] += (1-frac_x)*( frac_y)*( frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2]+h))] += (1-frac_x)*( frac_y)*(1-frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2] ))] += (1-frac_x)*(1-frac_y)*( frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2]+h))] += (1-frac_x)*(1-frac_y)*(1-frac_z); } } } if (!m_OutputAbsoluteValues && !m_BinaryOutput) { MITK_INFO << "TractDensityImageFilter: max-normalizing output image"; OutPixelType max = 0; for (int i=0; i<w*h*d; i++) if (max < outImageBufferPointer[i]) max = outImageBufferPointer[i]; if (max>0) for (int i=0; i<w*h*d; i++) outImageBufferPointer[i] /= max; } if (m_InvertImage) { MITK_INFO << "TractDensityImageFilter: inverting image"; for (int i=0; i<w*h*d; i++) outImageBufferPointer[i] = 1-outImageBufferPointer[i]; } MITK_INFO << "TractDensityImageFilter: finished processing"; } } <commit_msg>checking if index is inside image<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Coindex[1]right (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "itkTractDensityImageFilter.h" // VTK #include <vtkPolyLine.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkCell.h> // misc #include <math.h> #include <boost/progress.hpp> namespace itk{ template< class OutputImageType > TractDensityImageFilter< OutputImageType >::TractDensityImageFilter() : m_InvertImage(false) , m_FiberBundle(NULL) , m_UpsamplingFactor(1) , m_InputImage(NULL) , m_BinaryOutput(false) , m_UseImageGeometry(false) , m_OutputAbsoluteValues(false) , m_UseTrilinearInterpolation(false) { } template< class OutputImageType > TractDensityImageFilter< OutputImageType >::~TractDensityImageFilter() { } template< class OutputImageType > itk::Point<float, 3> TractDensityImageFilter< OutputImageType >::GetItkPoint(double point[3]) { itk::Point<float, 3> itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; return itkPoint; } template< class OutputImageType > void TractDensityImageFilter< OutputImageType >::GenerateData() { // generate upsampled image mitk::BaseGeometry::Pointer geometry = m_FiberBundle->GetGeometry(); typename OutputImageType::Pointer outImage = this->GetOutput(); // calculate new image parameters itk::Vector<double,3> newSpacing; mitk::Point3D newOrigin; itk::Matrix<double, 3, 3> newDirection; ImageRegion<3> upsampledRegion; if (m_UseImageGeometry && !m_InputImage.IsNull()) { MITK_INFO << "TractDensityImageFilter: using image geometry"; newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor; upsampledRegion = m_InputImage->GetLargestPossibleRegion(); newOrigin = m_InputImage->GetOrigin(); typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize(); size[0] *= m_UpsamplingFactor; size[1] *= m_UpsamplingFactor; size[2] *= m_UpsamplingFactor; upsampledRegion.SetSize(size); newDirection = m_InputImage->GetDirection(); } else { MITK_INFO << "TractDensityImageFilter: using fiber bundle geometry"; newSpacing = geometry->GetSpacing()/m_UpsamplingFactor; newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); for (int i=0; i<3; i++) for (int j=0; j<3; j++) newDirection[j][i] = geometry->GetMatrixColumn(i)[j]; upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); } typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); // apply new image parameters outImage->SetSpacing( newSpacing ); outImage->SetOrigin( newOrigin ); outImage->SetDirection( newDirection ); outImage->SetLargestPossibleRegion( upsampledRegion ); outImage->SetBufferedRegion( upsampledRegion ); outImage->SetRequestedRegion( upsampledRegion ); outImage->Allocate(); outImage->FillBuffer(0.0); int w = upsampledSize[0]; int h = upsampledSize[1]; int d = upsampledSize[2]; // set/initialize output OutPixelType* outImageBufferPointer = (OutPixelType*)outImage->GetBufferPointer(); // resample fiber bundle float minSpacing = 1; if(newSpacing[0]<newSpacing[1] && newSpacing[0]<newSpacing[2]) minSpacing = newSpacing[0]; else if (newSpacing[1] < newSpacing[2]) minSpacing = newSpacing[1]; else minSpacing = newSpacing[2]; MITK_INFO << "TractDensityImageFilter: resampling fibers to ensure sufficient voxel coverage"; m_FiberBundle = m_FiberBundle->GetDeepCopy(); m_FiberBundle->ResampleSpline(minSpacing/10); MITK_INFO << "TractDensityImageFilter: starting image generation"; vtkSmartPointer<vtkPolyData> fiberPolyData = m_FiberBundle->GetFiberPolyData(); vtkSmartPointer<vtkCellArray> vLines = fiberPolyData->GetLines(); vLines->InitTraversal(); int numFibers = m_FiberBundle->GetNumFibers(); boost::progress_display disp(numFibers); for( int i=0; i<numFibers; i++ ) { ++disp; vtkIdType numPoints(0); vtkIdType* points(NULL); vLines->GetNextCell ( numPoints, points ); // fill output image for( int j=0; j<numPoints; j++) { itk::Point<float, 3> vertex = GetItkPoint(fiberPolyData->GetPoint(points[j])); itk::Index<3> index; itk::ContinuousIndex<float, 3> contIndex; outImage->TransformPhysicalPointToIndex(vertex, index); outImage->TransformPhysicalPointToContinuousIndex(vertex, contIndex); if (!m_UseTrilinearInterpolation && outImage->GetLargestPossibleRegion().IsInside(index)) { if (m_BinaryOutput) outImage->SetPixel(index, 1); else outImage->SetPixel(index, outImage->GetPixel(index)+0.01); continue; } float frac_x = contIndex[0] - index[0]; float frac_y = contIndex[1] - index[1]; float frac_z = contIndex[2] - index[2]; if (frac_x<0) { index[0] -= 1; frac_x += 1; } if (frac_y<0) { index[1] -= 1; frac_y += 1; } if (frac_z<0) { index[2] -= 1; frac_z += 1; } frac_x = 1-frac_x; frac_y = 1-frac_y; frac_z = 1-frac_z; // int coordinates inside image? if (index[0] < 0 || index[0] >= w-1) continue; if (index[1] < 0 || index[1] >= h-1) continue; if (index[2] < 0 || index[2] >= d-1) continue; if (m_BinaryOutput) { outImageBufferPointer[( index[0] + w*(index[1] + h*index[2] ))] = 1; outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2] ))] = 1; outImageBufferPointer[( index[0] + w*(index[1] + h*index[2]+h))] = 1; outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2]+h))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2] ))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2]+h))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2] ))] = 1; outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2]+h))] = 1; } else { outImageBufferPointer[( index[0] + w*(index[1] + h*index[2] ))] += ( frac_x)*( frac_y)*( frac_z); outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2] ))] += ( frac_x)*(1-frac_y)*( frac_z); outImageBufferPointer[( index[0] + w*(index[1] + h*index[2]+h))] += ( frac_x)*( frac_y)*(1-frac_z); outImageBufferPointer[( index[0] + w*(index[1]+1+ h*index[2]+h))] += ( frac_x)*(1-frac_y)*(1-frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2] ))] += (1-frac_x)*( frac_y)*( frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1] + h*index[2]+h))] += (1-frac_x)*( frac_y)*(1-frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2] ))] += (1-frac_x)*(1-frac_y)*( frac_z); outImageBufferPointer[( index[0]+1 + w*(index[1]+1+ h*index[2]+h))] += (1-frac_x)*(1-frac_y)*(1-frac_z); } } } if (!m_OutputAbsoluteValues && !m_BinaryOutput) { MITK_INFO << "TractDensityImageFilter: max-normalizing output image"; OutPixelType max = 0; for (int i=0; i<w*h*d; i++) if (max < outImageBufferPointer[i]) max = outImageBufferPointer[i]; if (max>0) for (int i=0; i<w*h*d; i++) outImageBufferPointer[i] /= max; } if (m_InvertImage) { MITK_INFO << "TractDensityImageFilter: inverting image"; for (int i=0; i<w*h*d; i++) outImageBufferPointer[i] = 1-outImageBufferPointer[i]; } MITK_INFO << "TractDensityImageFilter: finished processing"; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Cerebra Module: cbMRIRegistration.cxx Copyright (c) 2011-2013 Qian Lu, David Adair 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 Calgary Image Processing and Analysis Centre (CIPAC), the University of Calgary, nor the names of any authors nor 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. =========================================================================*/ /*========================================================================= Copyright (c) 2005 Atamai, Inc. All rights reserved. Use, modification and redistribution of the software, in source or binary forms, are permitted provided that the following terms and conditions are met: 1) Redistribution of the source code, in verbatim or modified form, must retain the above copyright notice, this license, the following disclaimer, and any notices that refer to this license and/or the following disclaimer. 2) Redistribution in binary form must include the above copyright notice, a copy of this license and the following disclaimer in the documentation or with other materials provided with the distribution. 3) Modified copies of the source code must be clearly marked as such, and must not be misrepresented as verbatim copies of the source code. THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =========================================================================*/ #include "cbMRIRegistration.h" #include <vtkSmartPointer.h> #include <vtkMath.h> #include <vtkImageResize.h> #include <vtkImageReslice.h> #include <vtkImageSincInterpolator.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <vtkMatrix4x4.h> #include <vtkTransform.h> #include <vtkRenderer.h> #include <vtkCamera.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleImage.h> #include <vtkImageSlice.h> #include <vtkImageStack.h> #include <vtkImageResliceMapper.h> #include <vtkImageProperty.h> #include <vtkTimerLog.h> #include <vtkErrorCode.h> #include <vtkImageRegistration.h> #include <vtkProgressAccumulator.h> //---------------------------------------------------------------------------- cbMRIRegistration::cbMRIRegistration() { this->m_sourceImage = NULL; this->m_targetImage = NULL; this->m_sourceMatrix = NULL; this->m_targetMatrix = NULL; this->m_renderWindow = NULL; this->m_progressAccumulate = NULL; this->m_modifySourceMatrix = true; this->m_registrationMethod = MUTUAL_INFORMATION; } //---------------------------------------------------------------------------- cbMRIRegistration::~cbMRIRegistration() { if (m_sourceImage) { this->m_sourceImage->Delete(); } if (m_targetImage) { this->m_targetImage->Delete(); } if (m_sourceMatrix) { this->m_sourceMatrix->Delete(); } if (m_targetMatrix) { this->m_targetMatrix->Delete(); } if (m_renderWindow) { this->m_renderWindow->Delete(); } if (m_progressAccumulate) { this->m_progressAccumulate->Delete(); } } //---------------------------------------------------------------------------- void cbMRIRegistration::SetRenderWindow(vtkRenderWindow *renderwindow) { m_renderWindow = renderwindow; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputSource(vtkImageData *inputSource) { this->m_sourceImage = inputSource; } //---------------------------------------------------------------------------- vtkImageData *cbMRIRegistration::GetInputSource() { return this->m_sourceImage; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputTarget(vtkImageData *inputTarget) { this->m_targetImage = inputTarget; } //---------------------------------------------------------------------------- vtkImageData *cbMRIRegistration::GetInputTarget() { return this->m_targetImage; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputSourceMatrix(vtkMatrix4x4 *inputSourceMatrix) { this->m_sourceMatrix = inputSourceMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetInputSourceMatrix() { return this->m_sourceMatrix; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputTargetMatrix(vtkMatrix4x4 *inputTargetMatrix) { this->m_targetMatrix = inputTargetMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetInputTargetMatrix() { return this->m_targetMatrix; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetRegistrationMethod(int method) { if (method == 0) { this->m_registrationMethod = MUTUAL_INFORMATION; } else if (method == 1) { this->m_registrationMethod = CROSS_CORRELATION; } } //---------------------------------------------------------------------------- void cbMRIRegistration::SetModifyMatrixToSource() { this->m_modifySourceMatrix = true; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetModifyMatrixToTarget() { this->m_modifySourceMatrix = false; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetProgressAccumulator( vtkProgressAccumulator *progressAccumulate) { this->m_progressAccumulate = progressAccumulate; } //---------------------------------------------------------------------------- vtkProgressAccumulator *cbMRIRegistration::GetProgressAccumulator() { return this->m_progressAccumulate; } //---------------------------------------------------------------------------- int cbMRIRegistration::Execute() { if (this->m_sourceImage == NULL || this->m_targetImage == NULL || this->m_sourceMatrix == NULL || this->m_targetMatrix == NULL) { cout << "Execute: Input source image & matrix and" "target image & matrix are not set " << endl; return 0; } // parameters for registration int interpolatorType = vtkImageRegistration::Linear; double transformTolerance = 0.1; // tolerance on transformation result int numberOfBins = 64; // for Mattes' mutual information double initialBlurFactor = 4.0; // get information about the images double targetSpacing[3], sourceSpacing[3]; this->m_targetImage->GetSpacing(targetSpacing); this->m_sourceImage->GetSpacing(sourceSpacing); for (int jj = 0; jj < 3; jj++) { targetSpacing[jj] = fabs(targetSpacing[jj]); sourceSpacing[jj] = fabs(sourceSpacing[jj]); } double minSpacing = sourceSpacing[0]; if (minSpacing > sourceSpacing[1]) { minSpacing = sourceSpacing[1]; } if (minSpacing > sourceSpacing[2]) { minSpacing = sourceSpacing[2]; } // blur source image with Hamming-windowed sinc vtkSmartPointer<vtkImageSincInterpolator> sourceBlurKernel = vtkSmartPointer<vtkImageSincInterpolator>::New(); sourceBlurKernel->SetWindowFunctionToHamming(); // reduce the source resolution vtkSmartPointer<vtkImageResize> sourceBlur = vtkSmartPointer<vtkImageResize>::New(); sourceBlur->SetInput(this->m_sourceImage); sourceBlur->SetResizeMethodToOutputSpacing(); sourceBlur->SetInterpolator(sourceBlurKernel); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(sourceBlur,0.07f); } // blur target with Hamming-windowed sinc vtkSmartPointer<vtkImageSincInterpolator> targetBlurKernel = vtkSmartPointer<vtkImageSincInterpolator>::New(); targetBlurKernel->SetWindowFunctionToHamming(); // keep target at full resolution vtkSmartPointer<vtkImageResize> targetBlur = vtkSmartPointer<vtkImageResize>::New(); targetBlur->SetInput(this->m_targetImage); targetBlur->SetResizeMethodToOutputSpacing(); targetBlur->SetInterpolator(targetBlurKernel); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(targetBlur,0.07f); } // get the initial transformation vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New(); matrix->DeepCopy(this->m_targetMatrix); matrix->Invert(); vtkMatrix4x4::Multiply4x4(matrix, this->m_sourceMatrix, matrix); // set up the registration vtkSmartPointer<vtkImageRegistration> registration = vtkSmartPointer<vtkImageRegistration>::New(); registration->SetTargetImageInputConnection(targetBlur->GetOutputPort()); registration->SetSourceImageInputConnection(sourceBlur->GetOutputPort()); registration->SetInitializerTypeToCentered(); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(registration,0.05f); } if (!m_modifySourceMatrix) { registration->SetTransformTypeToScaleTargetAxes(); } else { registration->SetTransformTypeToRigid(); } if (this->m_registrationMethod == MUTUAL_INFORMATION) { registration->SetMetricTypeToNormalizedMutualInformation(); } else if (this->m_registrationMethod == CROSS_CORRELATION) { registration->SetMetricTypeToNormalizedCrossCorrelation(); } registration->SetInterpolatorType(interpolatorType); registration->SetJointHistogramSize(numberOfBins,numberOfBins); registration->SetMetricTolerance(1e-4); registration->SetTransformTolerance(transformTolerance); registration->SetMaximumNumberOfIterations(500); // make a timer vtkSmartPointer<vtkTimerLog> timer = vtkSmartPointer<vtkTimerLog>::New(); double startTime = timer->GetUniversalTime(); double lastTime = startTime; // do the registration // the registration starts at low-resolution double blurFactor = initialBlurFactor; // two stages for each resolution: // first without interpolation, and then with interpolation int stage = 0; // will be set to "true" when registration is initialized bool initialized = false; for (;;) { if (stage == 0) { registration->SetInterpolatorTypeToNearest(); registration->SetTransformTolerance(minSpacing); } else { registration->SetInterpolatorType(interpolatorType); registration->SetTransformTolerance(transformTolerance); } if (blurFactor < 1.1) { // full resolution: no blurring or resampling sourceBlur->InterpolateOff(); sourceBlur->SetOutputSpacing(sourceSpacing); sourceBlur->Update(); targetBlur->InterpolateOff(); targetBlur->SetOutputSpacing(targetSpacing); targetBlur->Update(); } else { // reduced resolution: set the blurring double spacing[3]; for (int j = 0; j < 3; j++) { spacing[j] = blurFactor*minSpacing; if (spacing[j] < sourceSpacing[j]) { spacing[j] = sourceSpacing[j]; } } sourceBlurKernel->SetBlurFactors( spacing[0]/sourceSpacing[0], spacing[1]/sourceSpacing[1], spacing[2]/sourceSpacing[2]); sourceBlur->SetOutputSpacing(spacing); sourceBlur->Update(); targetBlurKernel->SetBlurFactors( blurFactor*minSpacing/targetSpacing[0], blurFactor*minSpacing/targetSpacing[1], blurFactor*minSpacing/targetSpacing[2]); targetBlur->Update(); } if (initialized) { // re-initialize with the matrix from the previous step registration->SetInitializerTypeToNone(); matrix->DeepCopy(registration->GetTransform()->GetMatrix()); } registration->Initialize(matrix); initialized = true; while (registration->Iterate()) { //registration->UpdateRegistration(); // will iterate until convergence or failure if (m_modifySourceMatrix) { vtkMatrix4x4::Multiply4x4(this->m_targetMatrix, registration->GetTransform()->GetMatrix(), this->m_sourceMatrix); this->m_sourceMatrix->Modified(); } else { vtkMatrix4x4::Multiply4x4( this->m_sourceMatrix, registration->GetTransform()->GetLinearInverse()->GetMatrix(), this->m_targetMatrix); this->m_targetMatrix->Modified(); } if (m_renderWindow) { m_renderWindow->Render(); } } double newTime = timer->GetUniversalTime(); cout << "blur " << blurFactor << " stage " << stage << " took " << (newTime - lastTime) << "s and " << registration->GetNumberOfEvaluations() << " evaluations" << endl; lastTime = newTime; // prepare for next iteration if (stage == 1) { blurFactor /= 2.0; if (blurFactor < 0.9) { break; } } stage = (stage + 1) % 2; } if (m_progressAccumulate) { m_progressAccumulate->RegisterEndEvent(); } cout << "registration took " << (lastTime - startTime) << "s" << endl; return 1; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetModifiedSourceMatrix() { return this->m_sourceMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetModifiedTargetMatrix() { return this->m_targetMatrix; } <commit_msg>Use Affine registration for secondary.<commit_after>/*========================================================================= Program: Cerebra Module: cbMRIRegistration.cxx Copyright (c) 2011-2013 Qian Lu, David Adair 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 Calgary Image Processing and Analysis Centre (CIPAC), the University of Calgary, nor the names of any authors nor 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. =========================================================================*/ /*========================================================================= Copyright (c) 2005 Atamai, Inc. All rights reserved. Use, modification and redistribution of the software, in source or binary forms, are permitted provided that the following terms and conditions are met: 1) Redistribution of the source code, in verbatim or modified form, must retain the above copyright notice, this license, the following disclaimer, and any notices that refer to this license and/or the following disclaimer. 2) Redistribution in binary form must include the above copyright notice, a copy of this license and the following disclaimer in the documentation or with other materials provided with the distribution. 3) Modified copies of the source code must be clearly marked as such, and must not be misrepresented as verbatim copies of the source code. THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =========================================================================*/ #include "cbMRIRegistration.h" #include <vtkSmartPointer.h> #include <vtkMath.h> #include <vtkImageResize.h> #include <vtkImageReslice.h> #include <vtkImageSincInterpolator.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <vtkMatrix4x4.h> #include <vtkTransform.h> #include <vtkRenderer.h> #include <vtkCamera.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleImage.h> #include <vtkImageSlice.h> #include <vtkImageStack.h> #include <vtkImageResliceMapper.h> #include <vtkImageProperty.h> #include <vtkTimerLog.h> #include <vtkErrorCode.h> #include <vtkImageRegistration.h> #include <vtkProgressAccumulator.h> //---------------------------------------------------------------------------- cbMRIRegistration::cbMRIRegistration() { this->m_sourceImage = NULL; this->m_targetImage = NULL; this->m_sourceMatrix = NULL; this->m_targetMatrix = NULL; this->m_renderWindow = NULL; this->m_progressAccumulate = NULL; this->m_modifySourceMatrix = true; this->m_registrationMethod = MUTUAL_INFORMATION; } //---------------------------------------------------------------------------- cbMRIRegistration::~cbMRIRegistration() { if (m_sourceImage) { this->m_sourceImage->Delete(); } if (m_targetImage) { this->m_targetImage->Delete(); } if (m_sourceMatrix) { this->m_sourceMatrix->Delete(); } if (m_targetMatrix) { this->m_targetMatrix->Delete(); } if (m_renderWindow) { this->m_renderWindow->Delete(); } if (m_progressAccumulate) { this->m_progressAccumulate->Delete(); } } //---------------------------------------------------------------------------- void cbMRIRegistration::SetRenderWindow(vtkRenderWindow *renderwindow) { m_renderWindow = renderwindow; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputSource(vtkImageData *inputSource) { this->m_sourceImage = inputSource; } //---------------------------------------------------------------------------- vtkImageData *cbMRIRegistration::GetInputSource() { return this->m_sourceImage; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputTarget(vtkImageData *inputTarget) { this->m_targetImage = inputTarget; } //---------------------------------------------------------------------------- vtkImageData *cbMRIRegistration::GetInputTarget() { return this->m_targetImage; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputSourceMatrix(vtkMatrix4x4 *inputSourceMatrix) { this->m_sourceMatrix = inputSourceMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetInputSourceMatrix() { return this->m_sourceMatrix; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetInputTargetMatrix(vtkMatrix4x4 *inputTargetMatrix) { this->m_targetMatrix = inputTargetMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetInputTargetMatrix() { return this->m_targetMatrix; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetRegistrationMethod(int method) { if (method == 0) { this->m_registrationMethod = MUTUAL_INFORMATION; } else if (method == 1) { this->m_registrationMethod = CROSS_CORRELATION; } } //---------------------------------------------------------------------------- void cbMRIRegistration::SetModifyMatrixToSource() { this->m_modifySourceMatrix = true; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetModifyMatrixToTarget() { this->m_modifySourceMatrix = false; } //---------------------------------------------------------------------------- void cbMRIRegistration::SetProgressAccumulator( vtkProgressAccumulator *progressAccumulate) { this->m_progressAccumulate = progressAccumulate; } //---------------------------------------------------------------------------- vtkProgressAccumulator *cbMRIRegistration::GetProgressAccumulator() { return this->m_progressAccumulate; } //---------------------------------------------------------------------------- int cbMRIRegistration::Execute() { if (this->m_sourceImage == NULL || this->m_targetImage == NULL || this->m_sourceMatrix == NULL || this->m_targetMatrix == NULL) { cout << "Execute: Input source image & matrix and" "target image & matrix are not set " << endl; return 0; } // parameters for registration int interpolatorType = vtkImageRegistration::Linear; double transformTolerance = 0.1; // tolerance on transformation result int numberOfBins = 64; // for Mattes' mutual information double initialBlurFactor = 4.0; // get information about the images double targetSpacing[3], sourceSpacing[3]; this->m_targetImage->GetSpacing(targetSpacing); this->m_sourceImage->GetSpacing(sourceSpacing); for (int jj = 0; jj < 3; jj++) { targetSpacing[jj] = fabs(targetSpacing[jj]); sourceSpacing[jj] = fabs(sourceSpacing[jj]); } double minSpacing = sourceSpacing[0]; if (minSpacing > sourceSpacing[1]) { minSpacing = sourceSpacing[1]; } if (minSpacing > sourceSpacing[2]) { minSpacing = sourceSpacing[2]; } // blur source image with Hamming-windowed sinc vtkSmartPointer<vtkImageSincInterpolator> sourceBlurKernel = vtkSmartPointer<vtkImageSincInterpolator>::New(); sourceBlurKernel->SetWindowFunctionToHamming(); // reduce the source resolution vtkSmartPointer<vtkImageResize> sourceBlur = vtkSmartPointer<vtkImageResize>::New(); sourceBlur->SetInput(this->m_sourceImage); sourceBlur->SetResizeMethodToOutputSpacing(); sourceBlur->SetInterpolator(sourceBlurKernel); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(sourceBlur,0.07f); } // blur target with Hamming-windowed sinc vtkSmartPointer<vtkImageSincInterpolator> targetBlurKernel = vtkSmartPointer<vtkImageSincInterpolator>::New(); targetBlurKernel->SetWindowFunctionToHamming(); // keep target at full resolution vtkSmartPointer<vtkImageResize> targetBlur = vtkSmartPointer<vtkImageResize>::New(); targetBlur->SetInput(this->m_targetImage); targetBlur->SetResizeMethodToOutputSpacing(); targetBlur->SetInterpolator(targetBlurKernel); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(targetBlur,0.07f); } // get the initial transformation vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New(); matrix->DeepCopy(this->m_targetMatrix); matrix->Invert(); vtkMatrix4x4::Multiply4x4(matrix, this->m_sourceMatrix, matrix); // set up the registration vtkSmartPointer<vtkImageRegistration> registration = vtkSmartPointer<vtkImageRegistration>::New(); registration->SetTargetImageInputConnection(targetBlur->GetOutputPort()); registration->SetSourceImageInputConnection(sourceBlur->GetOutputPort()); registration->SetInitializerTypeToCentered(); if (m_progressAccumulate) { m_progressAccumulate->RegisterFilter(registration,0.05f); } registration->SetTransformTypeToAffine(); if (this->m_registrationMethod == MUTUAL_INFORMATION) { registration->SetMetricTypeToNormalizedMutualInformation(); } else if (this->m_registrationMethod == CROSS_CORRELATION) { registration->SetMetricTypeToNormalizedCrossCorrelation(); } registration->SetInterpolatorType(interpolatorType); registration->SetJointHistogramSize(numberOfBins,numberOfBins); registration->SetMetricTolerance(1e-4); registration->SetTransformTolerance(transformTolerance); registration->SetMaximumNumberOfIterations(500); // make a timer vtkSmartPointer<vtkTimerLog> timer = vtkSmartPointer<vtkTimerLog>::New(); double startTime = timer->GetUniversalTime(); double lastTime = startTime; // do the registration // the registration starts at low-resolution double blurFactor = initialBlurFactor; // two stages for each resolution: // first without interpolation, and then with interpolation int stage = 0; // will be set to "true" when registration is initialized bool initialized = false; for (;;) { if (stage == 0) { registration->SetInterpolatorTypeToNearest(); registration->SetTransformTolerance(minSpacing); } else { registration->SetInterpolatorType(interpolatorType); registration->SetTransformTolerance(transformTolerance); } if (blurFactor < 1.1) { // full resolution: no blurring or resampling sourceBlur->InterpolateOff(); sourceBlur->SetOutputSpacing(sourceSpacing); sourceBlur->Update(); targetBlur->InterpolateOff(); targetBlur->SetOutputSpacing(targetSpacing); targetBlur->Update(); } else { // reduced resolution: set the blurring double spacing[3]; for (int j = 0; j < 3; j++) { spacing[j] = blurFactor*minSpacing; if (spacing[j] < sourceSpacing[j]) { spacing[j] = sourceSpacing[j]; } } sourceBlurKernel->SetBlurFactors( spacing[0]/sourceSpacing[0], spacing[1]/sourceSpacing[1], spacing[2]/sourceSpacing[2]); sourceBlur->SetOutputSpacing(spacing); sourceBlur->Update(); targetBlurKernel->SetBlurFactors( blurFactor*minSpacing/targetSpacing[0], blurFactor*minSpacing/targetSpacing[1], blurFactor*minSpacing/targetSpacing[2]); targetBlur->Update(); } if (initialized) { // re-initialize with the matrix from the previous step registration->SetInitializerTypeToNone(); matrix->DeepCopy(registration->GetTransform()->GetMatrix()); } registration->Initialize(matrix); initialized = true; while (registration->Iterate()) { //registration->UpdateRegistration(); // will iterate until convergence or failure if (m_modifySourceMatrix) { vtkMatrix4x4::Multiply4x4(this->m_targetMatrix, registration->GetTransform()->GetMatrix(), this->m_sourceMatrix); this->m_sourceMatrix->Modified(); } else { vtkMatrix4x4::Multiply4x4( this->m_sourceMatrix, registration->GetTransform()->GetLinearInverse()->GetMatrix(), this->m_targetMatrix); this->m_targetMatrix->Modified(); } if (m_renderWindow) { m_renderWindow->Render(); } } double newTime = timer->GetUniversalTime(); cout << "blur " << blurFactor << " stage " << stage << " took " << (newTime - lastTime) << "s and " << registration->GetNumberOfEvaluations() << " evaluations" << endl; lastTime = newTime; // prepare for next iteration if (stage == 1) { blurFactor /= 2.0; if (blurFactor < 0.9) { break; } } stage = (stage + 1) % 2; } if (m_progressAccumulate) { m_progressAccumulate->RegisterEndEvent(); } cout << "registration took " << (lastTime - startTime) << "s" << endl; return 1; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetModifiedSourceMatrix() { return this->m_sourceMatrix; } //---------------------------------------------------------------------------- vtkMatrix4x4 *cbMRIRegistration::GetModifiedTargetMatrix() { return this->m_targetMatrix; } <|endoftext|>
<commit_before>/* Copyright (c) 2013, Tolga HOŞGÖR 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 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. 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 the FreeBSD Project. */ #include <cstdio> #include <algorithm> #include <array> #include <iostream> #include <mutex> #include <thread> #include "threadpool11/threadpool11.h" std::mutex coutMutex; void test1Func() { coutMutex.lock(); //heavy job that takes 1 second std::cout << "Waiting thread id: " << std::this_thread::get_id() << std::endl; coutMutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } void test2Func() { volatile int i = std::min(5, rand()); } std::atomic<uint64_t> test3Var(0); void test3Func() { volatile uint16_t var = 0; while(++var < (std::numeric_limits<uint16_t>::max())); ++test3Var; } int main() { threadpool11::Pool pool; std::cout << "Your machine's hardware concurrency is " << std::thread::hardware_concurrency() << std::endl << std::endl; /** * Demo #1. */ { std::cout << "This demo is about showing how parallelization increases the performance. " << "In this test case, work is simulated by making the threads inactive by sleeping for 1 second. " << "It will seem like all jobs complete in ~1 second even in a single core machine. " << "However, in real life cases, work would keep CPU busy so you would not get any real benefit using " << "thread numbers that are higher than your machine's hardware concurrency (threads that are executed " << "concurrently) except in some cases like doing file IO." << std::endl << std::endl; { std::cout << "Demo 1\n"; std::cout << "Executing 5 test1Func() WITHOUT posting to thread pool:\n"; auto begin = std::chrono::high_resolution_clock::now(); test1Func(); test1Func(); test1Func(); test1Func(); test1Func(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "\texecution took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds.\n\n"; } { std::cout << "Executing 5 test1Func() WITH posting to thread pool:" << std::endl; std::vector<std::future<void>> futures; auto begin = std::chrono::high_resolution_clock::now(); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); for(auto& it : futures) it.get(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "\tDemo 1 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } } /*! Helper function tests */ { std::cout << "Increasing worker count by 5." << std::endl; pool.increaseWorkerCountBy(5); std::cout << "Current worker count is " << pool.getWorkerCount() << ". Setting worker count to " << std::thread::hardware_concurrency() << "... " << std::flush; pool.setWorkerCount(std::thread::hardware_concurrency()); std::cout << "The new worker count is (may be still) " << pool.getWorkerCount() << "." << std::endl; std::cout << "Waiting 1 second..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "The new worker count is " << pool.getWorkerCount() << "." << std::endl << std::endl; } /** * Demo #2 */ { std::cout << "Demo 2" << std::endl; std::cout << "Posting 1.000.000 jobs." << std::endl; std::vector<std::future<void>> futures; auto begin = std::chrono::high_resolution_clock::now(); for(int i = 0; i < 1000000; ++i) { futures.emplace_back(pool.postWork<void>(test2Func)); } auto end = std::chrono::high_resolution_clock::now(); for(auto& it : futures) it.get(); auto end2 = std::chrono::high_resolution_clock::now(); std::cout << "Demo 2 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - begin).count() << " milliseconds. (Posting: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " ms, getting: " << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - end).count() << " ms)" << std::endl << std::endl; } /** * Demo #3 * You should always capture by value or use appropriate mutexes for reference access. */ { std::cout << "Demo 3" << std::endl; std::cout << "Testing work queue flow." << std::endl; #define th11_demo_iterations 30000 pool.increaseWorkerCountBy(th11_demo_iterations - 2); std::array<std::future<void>, th11_demo_iterations> futures; auto begin = std::chrono::high_resolution_clock::now(); for (int i = 0; i < th11_demo_iterations; ++i) futures[i] = pool.postWork<void>([=]() { test3Func(); }); for (int i = 0; i < th11_demo_iterations; ++i) futures[i].get(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "Variable is: " << test3Var << ", expected: " << th11_demo_iterations << std::endl; std::cout << "Demo 3 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } /** * Demo #4 * Using futures. */ { std::cout << "Demo 4\n"; std::cout << "WARNING: This test's output may be distorted because no synchronization on std::cout is done.\n"; std::array<std::future<float>, 20> futures; auto begin = std::chrono::high_resolution_clock::now(); for (int i=0; i<20; i++) { futures[i] = pool.postWork<float>([=]() { std::cout << "\tExecuted pow(" << i << ", 2) by thread id " << std::this_thread::get_id() << std::endl; return pow(i, 2); }); } for (int i=0; i < 20; i++) { std::cout << "\tfuture[" << i << "] value: " << futures[i].get() << std::endl; } auto end = std::chrono::high_resolution_clock::now(); std::cout << "Demo 4 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } /** * Test case for Issue #1 (fixed): Pool::postWork waiting forever, due to posting work before all threads in pool * are properly initialized and waiting. */ /*{ while(true) { std::cout << "Loop begin" << std::endl; std::vector<std::future<void>> futures; futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo1" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo2" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo3" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo4" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo5" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo6" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo7" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo8" << std::endl;})); //pool[0].setWork([]{}); std::cout << "waiting 1" << std::endl; for(auto& it : futures) it.get(); std::cout << "wait 1 end" << std::endl; futures.clear(); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo1" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo2" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo3" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo4" << std::endl;})); std::cout << "waiting 2" << std::endl; for(auto& it : futures) it.get(); std::cout << "wait 2 end" << std::endl; futures.clear(); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << "Increasing thread count by 4." << std::endl; pool.increaseWorkerCountBy(4); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << "Decreasing thread count by 4." << std::endl; pool.decreaseWorkerCountBy(4); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(5)); } }*/ std::cout << std::endl << std::endl; std::cout << "Demos completed." << std::endl; pool.joinAll(); //std::cin.get(); return 0; } <commit_msg>some fixes for msvc 12<commit_after>/* Copyright (c) 2013, Tolga HOŞGÖR 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 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. 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 the FreeBSD Project. */ #include <cstdio> #include <algorithm> #include <array> #include <iostream> #include <mutex> #include <thread> #include "threadpool11/threadpool11.h" std::mutex coutMutex; void test1Func() { coutMutex.lock(); //heavy job that takes 1 second std::cout << "Waiting thread id: " << std::this_thread::get_id() << std::endl; coutMutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } void test2Func() { volatile int i = std::min(5, rand()); } std::atomic<uint64_t> test3Var(0); void test3Func() { volatile uint16_t var = 0; while(++var < (std::numeric_limits<uint16_t>::max())); ++test3Var; } int main() { threadpool11::Pool pool; std::cout << "Your machine's hardware concurrency is " << std::thread::hardware_concurrency() << std::endl << std::endl; /** * Demo #1. */ { std::cout << "This demo is about showing how parallelization increases the performance. " << "In this test case, work is simulated by making the threads inactive by sleeping for 1 second. " << "It will seem like all jobs complete in ~1 second even in a single core machine. " << "However, in real life cases, work would keep CPU busy so you would not get any real benefit using " << "thread numbers that are higher than your machine's hardware concurrency (threads that are executed " << "concurrently) except in some cases like doing file IO." << std::endl << std::endl; { std::cout << "Demo 1\n"; std::cout << "Executing 5 test1Func() WITHOUT posting to thread pool:\n"; auto begin = std::chrono::high_resolution_clock::now(); test1Func(); test1Func(); test1Func(); test1Func(); test1Func(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "\texecution took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds.\n\n"; } { std::cout << "Executing 5 test1Func() WITH posting to thread pool:" << std::endl; std::vector<std::future<void>> futures; auto begin = std::chrono::high_resolution_clock::now(); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); futures.emplace_back(pool.postWork<void>(test1Func)); for(auto& it : futures) it.get(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "\tDemo 1 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } } /*! Helper function tests */ { std::cout << "Increasing worker count by 5." << std::endl; pool.increaseWorkerCountBy(5); std::cout << "Current worker count is " << pool.getWorkerCount() << ". Setting worker count to " << std::thread::hardware_concurrency() << "... " << std::flush; pool.setWorkerCount(std::thread::hardware_concurrency()); std::cout << "The new worker count is (may be still) " << pool.getWorkerCount() << "." << std::endl; std::cout << "Waiting 1 second..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "The new worker count is " << pool.getWorkerCount() << "." << std::endl << std::endl; } /** * Demo #2 */ { std::cout << "Demo 2" << std::endl; std::cout << "Posting 1.000.000 jobs." << std::endl; std::vector<std::future<void>> futures; auto begin = std::chrono::high_resolution_clock::now(); for(int i = 0; i < 1000000; ++i) { futures.emplace_back(pool.postWork<void>(test2Func)); } auto end = std::chrono::high_resolution_clock::now(); for(auto& it : futures) it.get(); auto end2 = std::chrono::high_resolution_clock::now(); std::cout << "Demo 2 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - begin).count() << " milliseconds. (Posting: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " ms, getting: " << std::chrono::duration_cast<std::chrono::milliseconds>(end2 - end).count() << " ms)" << std::endl << std::endl; } /** * Demo #3 * You should always capture by value or use appropriate mutexes for reference access. */ { std::cout << "Demo 3" << std::endl; std::cout << "Testing work queue flow." << std::endl; #define th11_demo_iterations 30000 //pool.increaseWorkerCountBy(th11_demo_iterations - 2); std::array<std::future<void>, th11_demo_iterations> futures; auto begin = std::chrono::high_resolution_clock::now(); for (int i = 0; i < th11_demo_iterations; ++i) futures[i] = pool.postWork<void>([=]() { test3Func(); }); for (int i = 0; i < th11_demo_iterations; ++i) futures[i].get(); auto end = std::chrono::high_resolution_clock::now(); std::cout << "Variable is: " << test3Var << ", expected: " << th11_demo_iterations << std::endl; std::cout << "Demo 3 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } /** * Demo #4 * Using futures. */ { std::cout << "Demo 4\n"; std::cout << "WARNING: This test's output may be distorted because no synchronization on std::cout is done.\n"; std::array<std::future<float>, 20> futures; auto begin = std::chrono::high_resolution_clock::now(); for (int i=0; i<20; i++) { futures[i] = pool.postWork<float>([=]() { std::cout << "\tExecuted pow(" << i << ", 2) by thread id " << std::this_thread::get_id() << std::endl; return pow(i, 2); }); } for (int i=0; i < 20; i++) { std::cout << "\tfuture[" << i << "] value: " << futures[i].get() << std::endl; } auto end = std::chrono::high_resolution_clock::now(); std::cout << "Demo 4 took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " milliseconds." << std::endl << std::endl; } /** * Test case for Issue #1 (fixed): Pool::postWork waiting forever, due to posting work before all threads in pool * are properly initialized and waiting. */ /*{ while(true) { std::cout << "Loop begin" << std::endl; std::vector<std::future<void>> futures; futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo1" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo2" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo3" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo4" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo5" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo6" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo7" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " heyyo8" << std::endl;})); //pool[0].setWork([]{}); std::cout << "waiting 1" << std::endl; for(auto& it : futures) it.get(); std::cout << "wait 1 end" << std::endl; futures.clear(); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo1" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo2" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo3" << std::endl;})); futures.emplace_back(pool.postWork<void>([]{std::cout << std::this_thread::get_id() << " 2heyyo4" << std::endl;})); std::cout << "waiting 2" << std::endl; for(auto& it : futures) it.get(); std::cout << "wait 2 end" << std::endl; futures.clear(); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << "Increasing thread count by 4." << std::endl; pool.increaseWorkerCountBy(4); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << "Decreasing thread count by 4." << std::endl; pool.decreaseWorkerCountBy(4); std::cout << "Active thread count: " << pool.getActiveWorkerCount() << std::endl; std::cout << "Inactive thread count: " << pool.getInactiveWorkerCount() << std::endl; std::cout << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(5)); } }*/ std::cout << std::endl << std::endl; std::cout << "Demos completed." << std::endl; pool.joinAll(); //std::cin.get(); return 0; } <|endoftext|>
<commit_before>// // C++ Implementation: PresetLoader // // Description: // // // Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007 // // Copyright: See COPYING file that comes with this distribution // // #include "PresetLoader.hpp" #include "Preset.hpp" #include <iostream> #include <sstream> extern "C" { #include <errno.h> #include <dirent.h> } #include <cassert> #include "projectM.hpp" const std::string PresetLoader::PROJECTM_FILE_EXTENSION(".prjm"); const std::string PresetLoader::MILKDROP_FILE_EXTENSION(".milk"); PresetLoader::PresetLoader(std::string dirname) :m_dirname(dirname), m_dir(0) { // Do one scan rescan(); } PresetLoader::~PresetLoader() { if (m_dir) closedir(m_dir); } void PresetLoader::setScanDirectory(std::string dirname) { m_dirname = dirname; } void PresetLoader::rescan() { std::cerr << "Rescanning..." << std::endl; // Clear the directory entry collection m_entries.clear(); std::cerr << "cleared!" << std::endl; // If directory already opened, close it first if (m_dir) { std::cerr << "m_dir" << std::endl; closedir(m_dir); m_dir = 0; } std::cerr << "opening " << m_dirname << std::endl; // Allocate a new a stream given the current directory name if ((m_dir = opendir(m_dirname.c_str())) == NULL) { handleDirectoryError(); abort(); } struct dirent * dir_entry; while ((dir_entry = readdir(m_dir)) != NULL) { std::ostringstream out; // Convert char * to friendly string std::string filename(dir_entry->d_name); // Verify extension is projectm or milkdrop if ((filename.rfind(PROJECTM_FILE_EXTENSION) != (filename.length() - PROJECTM_FILE_EXTENSION.length())) && (filename.rfind(MILKDROP_FILE_EXTENSION) != (filename.length() - MILKDROP_FILE_EXTENSION.length()))) continue; // Create full path name out << m_dirname << PATH_SEPARATOR << filename; // std::cerr << "[PresetLoader]" << filename << std::endl; // Add to our directory entry collection m_entries.push_back(out.str()); // the directory entry struct is freed elsewhere } } std::auto_ptr<Preset> PresetLoader::loadPreset(unsigned int index, const PresetInputs & presetInputs, PresetOutputs & presetOutputs) const { // Check that index isn't insane assert(index >= 0); assert(index < m_entries.size()); // Return a new pointer to a present return std::auto_ptr<Preset>(new Preset(m_entries[index], presetInputs, presetOutputs)); } void PresetLoader::handleDirectoryError() { switch (errno) { case ENOENT: std::cerr << "[PresetLoader] ENOENT error. \"man fopen\" for more info." << std::endl; break; case ENOMEM: std::cerr << "[PresetLoader] out of memory! Are you running Windows?" << std::endl; abort(); case ENOTDIR: std::cerr << "[PresetLoader] directory specified is not a preset directory! Cannot continue." << std::endl; break; case ENFILE: std::cerr << "[PresetLoader] Your system has reached its open file limit. Giving up..." << std::endl; abort(); case EMFILE: std::cerr << "[PresetLoader] too many files in use by projectM! Bailing!" << std::endl; abort(); case EACCES: std::cerr << "[PresetLoader] permissions issue reading the specified preset directory." << std::endl; break; default: break; } } <commit_msg>more useful error message added when preset dir is invalid<commit_after>// // C++ Implementation: PresetLoader // // Description: // // // Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007 // // Copyright: See COPYING file that comes with this distribution // // #include "PresetLoader.hpp" #include "Preset.hpp" #include <iostream> #include <sstream> extern "C" { #include <errno.h> #include <dirent.h> } #include <cassert> #include "projectM.hpp" const std::string PresetLoader::PROJECTM_FILE_EXTENSION(".prjm"); const std::string PresetLoader::MILKDROP_FILE_EXTENSION(".milk"); PresetLoader::PresetLoader(std::string dirname) :m_dirname(dirname), m_dir(0) { // Do one scan rescan(); } PresetLoader::~PresetLoader() { if (m_dir) closedir(m_dir); } void PresetLoader::setScanDirectory(std::string dirname) { m_dirname = dirname; } void PresetLoader::rescan() { std::cerr << "Rescanning..." << std::endl; // Clear the directory entry collection m_entries.clear(); std::cerr << "cleared!" << std::endl; // If directory already opened, close it first if (m_dir) { std::cerr << "m_dir" << std::endl; closedir(m_dir); m_dir = 0; } std::cerr << "opening " << m_dirname << std::endl; // Allocate a new a stream given the current directory name if ((m_dir = opendir(m_dirname.c_str())) == NULL) { handleDirectoryError(); abort(); } struct dirent * dir_entry; while ((dir_entry = readdir(m_dir)) != NULL) { std::ostringstream out; // Convert char * to friendly string std::string filename(dir_entry->d_name); // Verify extension is projectm or milkdrop if ((filename.rfind(PROJECTM_FILE_EXTENSION) != (filename.length() - PROJECTM_FILE_EXTENSION.length())) && (filename.rfind(MILKDROP_FILE_EXTENSION) != (filename.length() - MILKDROP_FILE_EXTENSION.length()))) continue; // Create full path name out << m_dirname << PATH_SEPARATOR << filename; // std::cerr << "[PresetLoader]" << filename << std::endl; // Add to our directory entry collection m_entries.push_back(out.str()); // the directory entry struct is freed elsewhere } } std::auto_ptr<Preset> PresetLoader::loadPreset(unsigned int index, const PresetInputs & presetInputs, PresetOutputs & presetOutputs) const { // Check that index isn't insane assert(index >= 0); assert(index < m_entries.size()); // Return a new pointer to a present return std::auto_ptr<Preset>(new Preset(m_entries[index], presetInputs, presetOutputs)); } void PresetLoader::handleDirectoryError() { switch (errno) { case ENOENT: std::cerr << "[PresetLoader] ENOENT error. The path \"" << this->m_dirname << "\" probably does not exist. \"man open\" for more info." << std::endl; break; case ENOMEM: std::cerr << "[PresetLoader] out of memory! Are you running Windows?" << std::endl; abort(); case ENOTDIR: std::cerr << "[PresetLoader] directory specified is not a preset directory! Cannot continue." << std::endl; break; case ENFILE: std::cerr << "[PresetLoader] Your system has reached its open file limit. Giving up..." << std::endl; abort(); case EMFILE: std::cerr << "[PresetLoader] too many files in use by projectM! Bailing!" << std::endl; abort(); case EACCES: std::cerr << "[PresetLoader] permissions issue reading the specified preset directory." << std::endl; break; default: break; } } <|endoftext|>
<commit_before>/* Filename: JSFS.cpp Purpose: Javascript bindings for Engine::Filesystem Part of Engine2D Copyright (C) 2014 Vbitz 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 "JSFS.hpp" #include "Util.hpp" #include "Filesystem.hpp" namespace Engine { namespace JsFS { ENGINE_JS_METHOD(ReadFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file to read"); std::string path = ENGINE_GET_ARG_CPPSTRING_VALUE(0); if (!Filesystem::FileExists(path)) { ENGINE_THROW_ARGERROR("File does not exist"); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } if (args.Length() == 2) { ENGINE_CHECK_ARG_BOOLEAN(1, "Set Arg1 if you need a raw byte array"); long fileLength = 0; char* file = Filesystem::GetFileContent(path, fileLength); v8::Handle<v8::Array> arr = v8::Array::New(); for (int i = 0; i < fileLength; i++) { arr->Set(i, v8::Number::New((unsigned char) file[i])); } ENGINE_JS_SCOPE_CLOSE(arr); } else { ENGINE_JS_SCOPE_CLOSE(v8::String::New(Filesystem::GetFileContent(path))); } } ENGINE_JS_METHOD(WriteFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file to write"); ENGINE_CHECK_ARG_STRING(1, "Arg1 is the content to write to the file"); Filesystem::WriteFile(ENGINE_GET_ARG_CPPSTRING_VALUE(0), *ENGINE_GET_ARG_CSTRING_VALUE(1), args[1]->ToString()->Length()); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } ENGINE_JS_METHOD(FileExists) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file"); ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(Filesystem::FileExists(ENGINE_GET_ARG_CPPSTRING_VALUE(0)))); } ENGINE_JS_METHOD(FileSize) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file"); ENGINE_JS_SCOPE_CLOSE(v8::Integer::New((int) Filesystem::FileSize(ENGINE_GET_ARG_CPPSTRING_VALUE(0)))); } ENGINE_JS_METHOD(MountFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(2); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the archivefile"); ENGINE_CHECK_ARG_STRING(1, "Arg1 is the path to mount the archive to"); std::string path = ENGINE_GET_ARG_CPPSTRING_VALUE(0); if (!Filesystem::FileExists(path)) { ENGINE_THROW_ARGERROR("File does not exist"); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } bool result = Filesystem::Mount(Filesystem::GetRealPath(path), ENGINE_GET_ARG_CPPSTRING_VALUE(1)); ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(result)); } ENGINE_JS_METHOD(ConfigDir) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the application name"); Filesystem::SetupUserDir(ENGINE_GET_ARG_CPPSTRING_VALUE(0)); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } ENGINE_JS_METHOD(Mkdir) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the directory to create"); Filesystem::Mkdir(ENGINE_GET_ARG_CPPSTRING_VALUE(0)); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } #define addItem(table, js_name, funct) table->Set(js_name, v8::FunctionTemplate::New(funct)) void InitFS(v8::Handle<v8::ObjectTemplate> fsTable) { addItem(fsTable, "readFile", ReadFile); addItem(fsTable, "writeFile", WriteFile); addItem(fsTable, "fileExists", FileExists); addItem(fsTable, "fileSize", FileSize); addItem(fsTable, "mountFile", MountFile); addItem(fsTable, "configDir", ConfigDir); addItem(fsTable, "mkdir", Mkdir); } #undef addItem } }<commit_msg>Added fs.lsdir<commit_after>/* Filename: JSFS.cpp Purpose: Javascript bindings for Engine::Filesystem Part of Engine2D Copyright (C) 2014 Vbitz 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 "JSFS.hpp" #include "Util.hpp" #include "Filesystem.hpp" namespace Engine { namespace JsFS { ENGINE_JS_METHOD(ReadFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file to read"); std::string path = ENGINE_GET_ARG_CPPSTRING_VALUE(0); if (!Filesystem::FileExists(path)) { ENGINE_THROW_ARGERROR("File does not exist"); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } if (args.Length() == 2) { ENGINE_CHECK_ARG_BOOLEAN(1, "Set Arg1 if you need a raw byte array"); long fileLength = 0; char* file = Filesystem::GetFileContent(path, fileLength); v8::Handle<v8::Array> arr = v8::Array::New(); for (int i = 0; i < fileLength; i++) { arr->Set(i, v8::Number::New((unsigned char) file[i])); } ENGINE_JS_SCOPE_CLOSE(arr); } else { ENGINE_JS_SCOPE_CLOSE(v8::String::New(Filesystem::GetFileContent(path))); } } ENGINE_JS_METHOD(WriteFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file to write"); ENGINE_CHECK_ARG_STRING(1, "Arg1 is the content to write to the file"); Filesystem::WriteFile(ENGINE_GET_ARG_CPPSTRING_VALUE(0), *ENGINE_GET_ARG_CSTRING_VALUE(1), args[1]->ToString()->Length()); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } ENGINE_JS_METHOD(FileExists) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file"); ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(Filesystem::FileExists(ENGINE_GET_ARG_CPPSTRING_VALUE(0)))); } ENGINE_JS_METHOD(FileSize) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the file"); ENGINE_JS_SCOPE_CLOSE(v8::Integer::New((int) Filesystem::FileSize(ENGINE_GET_ARG_CPPSTRING_VALUE(0)))); } ENGINE_JS_METHOD(MountFile) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(2); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the archivefile"); ENGINE_CHECK_ARG_STRING(1, "Arg1 is the path to mount the archive to"); std::string path = ENGINE_GET_ARG_CPPSTRING_VALUE(0); if (!Filesystem::FileExists(path)) { ENGINE_THROW_ARGERROR("File does not exist"); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } bool result = Filesystem::Mount(Filesystem::GetRealPath(path), ENGINE_GET_ARG_CPPSTRING_VALUE(1)); ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(result)); } ENGINE_JS_METHOD(ConfigDir) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the application name"); Filesystem::SetupUserDir(ENGINE_GET_ARG_CPPSTRING_VALUE(0)); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } ENGINE_JS_METHOD(Mkdir) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path to the directory to create"); Filesystem::Mkdir(ENGINE_GET_ARG_CPPSTRING_VALUE(0)); ENGINE_JS_SCOPE_CLOSE_UNDEFINED; } ENGINE_JS_METHOD(Lsdir) { ENGINE_JS_SCOPE_OPEN; ENGINE_CHECK_ARGS_LENGTH(1); ENGINE_CHECK_ARG_STRING(0, "Arg0 is the path of the directory to list"); v8::Handle<v8::Array> ret = v8::Array::New(); std::vector<std::string> files = Filesystem::GetDirectoryContent(ENGINE_GET_ARG_CPPSTRING_VALUE(0)); for (size_t i = 0; i < files.size(); i++) { ret->Set(i, v8::String::New(files[i].c_str())); } ENGINE_JS_SCOPE_CLOSE(ret); } #define addItem(table, js_name, funct) table->Set(js_name, v8::FunctionTemplate::New(funct)) void InitFS(v8::Handle<v8::ObjectTemplate> fsTable) { addItem(fsTable, "readFile", ReadFile); addItem(fsTable, "writeFile", WriteFile); addItem(fsTable, "fileExists", FileExists); addItem(fsTable, "fileSize", FileSize); addItem(fsTable, "mountFile", MountFile); addItem(fsTable, "configDir", ConfigDir); addItem(fsTable, "mkdir", Mkdir); addItem(fsTable, "lsdir", Lsdir); } #undef addItem } }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ #define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Execution/Exceptions.h" #include "BadFormatException.h" namespace Stroika { namespace Foundation { namespace DataExchangeFormat { /* ******************************************************************************** ******************* ObjectVariantMapper::StructureFieldInfo ******************** ******************************************************************************** */ inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName) : fOffset (fieldOffset) , fTypeInfo (typeInfo) , fSerializedFieldName (serializedFieldName) { } /* ******************************************************************************** ******************************** ObjectVariantMapper *************************** ******************************************************************************** */ inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const { return fSerializers_; } inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s) { fSerializers_ = s; } template <typename CLASS> inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions) { RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions)); } template <typename CLASS> inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const { ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into)); } template <typename CLASS> inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const { CLASS tmp; ToObject (v, &tmp); return tmp; } template <typename CLASS> inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const { return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from)); } template <typename T, size_t SZ> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT); for (auto i = actualMember; i < actualMember + SZ; ++i) { s.Append (mapper->FromObject<T> (*i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT); if (s.size () > SZ) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } size_t idx = 0; for (auto i : s) { actualMember[idx++] = mapper->ToObject<T> (i); } while (idx < SZ) { actualMember[idx++] = T (); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename T> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT); for (auto i : *actualMember) { s.Append (mapper->FromObject<T> (i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT); actualInto->clear (); for (auto i : s) { actualInto->Append (mapper->ToObject<T> (i)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { Sequence<VariantValue> encodedPair; encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.first)); encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.second)); s.Append (VariantValue (encodedPair)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (VariantValue encodedPair : s) { Sequence<VariantValue> p = p.As<Sequence<VariantValue>> (); if (p.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1])); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_MappingWithStringishKey () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Mapping<String, VariantValue> m; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { m.Add (mapper->FromObject<String> (i.first), mapper->FromObject<VALUE_TYPE> (i.second)); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (pair<String, VariantValue> : m) { actualInto->Add (mapper->ToObject<String> (p.first), mapper->ToObject<VALUE_TYPE> (p.second)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename RANGE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m; const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT); m.Add (L"Begin", mapper->FromObject<ElementType> (actualMember->begin ())); m.Add (L"End", mapper->FromObject<ElementType> (actualMember->end ())); return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT); if (m.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not m.ContainsKey (L"Begin") or not m.ContainsKey (L"End")) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } ElementType from = mapper->ToObject<ElementType> (*m.Lookup (L"Begin")); ElementType to = mapper->ToObject<ElementType> (*m.Lookup (L"End")); if (not (RANGE_TYPE::TraitsType::kMin <= from and from < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not (RANGE_TYPE::TraitsType::kMin <= to and to < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } * actualInto = RANGE_TYPE (from, to); }; return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper); } template <typename ENUM_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Enumeration () { /* * Note: we cannot get the enumeration print names - in general. That would be nicer to read, but we dont have * the data, and this is simple and efficient. */ Require (std::is_enum<ENUM_TYPE>::value); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type typedef typename std::underlying_type<ENUM_TYPE>::type SerializeAsType; #else typedef long long SerializeAsType; #endif auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ENUM_TYPE* actualMember = reinterpret_cast<const ENUM_TYPE*> (fromObjOfTypeT); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<ENUM_TYPE> (static_cast<SerializeAsType> (*actualMember)) == *actualMember); // no round-trip loss return VariantValue (static_cast<SerializeAsType> (*actualMember)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ENUM_TYPE* actualInto = reinterpret_cast<ENUM_TYPE*> (intoObjOfTypeT); * actualInto = static_cast<ENUM_TYPE> (d.As<SerializeAsType> ()); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<SerializeAsType> (*actualInto) == d.As<SerializeAsType> ()); // no round-trip loss if (not (ENUM_TYPE::eSTART <= *actualInto and * actualInto <= ENUM_TYPE::eEND)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (ENUM_TYPE), toVariantMapper, fromVariantMapper); } #if 0 template <typename T> inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> () { return mkSerializerInfoFor_Sequence_<T> (); } #endif } } } #endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/ <commit_msg>fixed typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ #define _Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Execution/Exceptions.h" #include "BadFormatException.h" namespace Stroika { namespace Foundation { namespace DataExchangeFormat { /* ******************************************************************************** ******************* ObjectVariantMapper::StructureFieldInfo ******************** ******************************************************************************** */ inline ObjectVariantMapper::StructureFieldInfo::StructureFieldInfo (size_t fieldOffset, type_index typeInfo, const String& serializedFieldName) : fOffset (fieldOffset) , fTypeInfo (typeInfo) , fSerializedFieldName (serializedFieldName) { } /* ******************************************************************************** ******************************** ObjectVariantMapper *************************** ******************************************************************************** */ inline Set<ObjectVariantMapper::TypeMappingDetails> ObjectVariantMapper::GetTypeMappingRegistry () const { return fSerializers_; } inline void ObjectVariantMapper::SetTypeMappingRegistry (const Set<TypeMappingDetails>& s) { fSerializers_ = s; } template <typename CLASS> inline void ObjectVariantMapper::RegisterClass (const Sequence<StructureFieldInfo>& fieldDescriptions) { RegisterTypeMapper (TypeMappingDetails (typeid (CLASS), sizeof (CLASS), fieldDescriptions)); } template <typename CLASS> inline void ObjectVariantMapper::ToObject (const Memory::VariantValue& v, CLASS* into) const { ToObject (typeid (CLASS), v, reinterpret_cast<Byte*> (into)); } template <typename CLASS> inline CLASS ObjectVariantMapper::ToObject (const Memory::VariantValue& v) const { CLASS tmp; ToObject (v, &tmp); return tmp; } template <typename CLASS> inline VariantValue ObjectVariantMapper::FromObject (const CLASS& from) const { return FromObject (typeid (CLASS), reinterpret_cast<const Byte*> (&from)); } template <typename T, size_t SZ> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Array () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const T* actualMember = reinterpret_cast<const T*> (fromObjOfTypeT); for (auto i = actualMember; i < actualMember + SZ; ++i) { s.Append (mapper->FromObject<T> (*i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); T* actualMember = reinterpret_cast<T*> (intoObjOfTypeT); if (s.size () > SZ) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } size_t idx = 0; for (auto i : s) { actualMember[idx++] = mapper->ToObject<T> (i); } while (idx < SZ) { actualMember[idx++] = T (); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename T> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Sequence () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Sequence<T>* actualMember = reinterpret_cast<const Sequence<T>*> (fromObjOfTypeT); for (auto i : *actualMember) { s.Append (mapper->FromObject<T> (i)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<T>> (); Sequence<T>* actualInto = reinterpret_cast<Sequence<T>*> (intoObjOfTypeT); actualInto->clear (); for (auto i : s) { actualInto->Append (mapper->ToObject<T> (i)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Sequence<T>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Mapping () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Sequence<VariantValue> s; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { Sequence<VariantValue> encodedPair; encodedPair.Append (mapper->FromObject<KEY_TYPE> (i.first)); encodedPair.Append (mapper->FromObject<VALUE_TYPE> (i.second)); s.Append (VariantValue (encodedPair)); } return VariantValue (s); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Sequence<VariantValue> s = d.As<Sequence<VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (VariantValue encodedPair : s) { Sequence<VariantValue> p = p.As<Sequence<VariantValue>> (); if (p.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } actualInto->Add (mapper->ToObject<KEY_TYPE> (p[0]), mapper->ToObject<VALUE_TYPE> (p[1])); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename KEY_TYPE, typename VALUE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_MappingWithStringishKey () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { Mapping<String, VariantValue> m; const Mapping<KEY_TYPE, VALUE_TYPE>* actualMember = reinterpret_cast<const Mapping<KEY_TYPE, VALUE_TYPE>*> (fromObjOfTypeT); for (auto i : *actualMember) { m.Add (mapper->FromObject<String> (i.first), mapper->FromObject<VALUE_TYPE> (i.second)); } return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); Mapping<KEY_TYPE, VALUE_TYPE>* actualInto = reinterpret_cast<Mapping<KEY_TYPE, VALUE_TYPE>*> (intoObjOfTypeT); actualInto->clear (); for (pair<String, VariantValue> p : m) { actualInto->Add (mapper->ToObject<String> (p.first), mapper->ToObject<VALUE_TYPE> (p.second)); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (Mapping<KEY_TYPE, VALUE_TYPE>), toVariantMapper, fromVariantMapper); } template <typename RANGE_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Range () { auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m; const RANGE_TYPE* actualMember = reinterpret_cast<const RANGE_TYPE*> (fromObjOfTypeT); m.Add (L"Begin", mapper->FromObject<ElementType> (actualMember->begin ())); m.Add (L"End", mapper->FromObject<ElementType> (actualMember->end ())); return VariantValue (m); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { typedef typename RANGE_TYPE::ElementType ElementType; Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> (); RANGE_TYPE* actualInto = reinterpret_cast<RANGE_TYPE*> (intoObjOfTypeT); if (m.size () != 2) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not m.ContainsKey (L"Begin") or not m.ContainsKey (L"End")) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } ElementType from = mapper->ToObject<ElementType> (*m.Lookup (L"Begin")); ElementType to = mapper->ToObject<ElementType> (*m.Lookup (L"End")); if (not (RANGE_TYPE::TraitsType::kMin <= from and from < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } if (not (RANGE_TYPE::TraitsType::kMin <= to and to < RANGE_TYPE::TraitsType::kMax)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } * actualInto = RANGE_TYPE (from, to); }; return ObjectVariantMapper::TypeMappingDetails (typeid (RANGE_TYPE), toVariantMapper, fromVariantMapper); } template <typename ENUM_TYPE> ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer_Enumeration () { /* * Note: we cannot get the enumeration print names - in general. That would be nicer to read, but we dont have * the data, and this is simple and efficient. */ Require (std::is_enum<ENUM_TYPE>::value); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type typedef typename std::underlying_type<ENUM_TYPE>::type SerializeAsType; #else typedef long long SerializeAsType; #endif auto toVariantMapper = [] (const ObjectVariantMapper * mapper, const Byte * fromObjOfTypeT) -> VariantValue { const ENUM_TYPE* actualMember = reinterpret_cast<const ENUM_TYPE*> (fromObjOfTypeT); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<ENUM_TYPE> (static_cast<SerializeAsType> (*actualMember)) == *actualMember); // no round-trip loss return VariantValue (static_cast<SerializeAsType> (*actualMember)); }; auto fromVariantMapper = [] (const ObjectVariantMapper * mapper, const VariantValue & d, Byte * intoObjOfTypeT) -> void { ENUM_TYPE* actualInto = reinterpret_cast<ENUM_TYPE*> (intoObjOfTypeT); * actualInto = static_cast<ENUM_TYPE> (d.As<SerializeAsType> ()); #if qCompilerAndStdLib_Supports_TypeTraits_underlying_type Assert (sizeof (SerializeAsType) == sizeof (ENUM_TYPE)); #endif Assert (static_cast<SerializeAsType> (*actualInto) == d.As<SerializeAsType> ()); // no round-trip loss if (not (ENUM_TYPE::eSTART <= *actualInto and * actualInto <= ENUM_TYPE::eEND)) { Execution::DoThrow<BadFormatException> (BadFormatException ()); } }; return ObjectVariantMapper::TypeMappingDetails (typeid (ENUM_TYPE), toVariantMapper, fromVariantMapper); } #if 0 template <typename T> inline ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::MakeCommonSerializer<Sequence<T>> () { return mkSerializerInfoFor_Sequence_<T> (); } #endif } } } #endif /*_Stroika_Foundation_DataExchangeFormat_ObjectVariantMapper_inl_*/ <|endoftext|>
<commit_before>#include "RDom.h" #include "Util.h" #include "IROperator.h" #include "IRPrinter.h" namespace Halide { using namespace Internal; using std::string; using std::vector; RVar::operator Expr() const { if (!min().defined() || !extent().defined()) { user_error << "Use of undefined RDom dimension: " << (name().empty() ? "<unknown>" : name()) << "\n"; } return Variable::make(Int(32), name(), domain()); } Expr RVar::min() const { if (_domain.defined()) { return _var().min; } else { return undef<int>(); } } Expr RVar::extent() const { if (_domain.defined()) { return _var().extent; } else { return undef<int>(); } } const std::string &RVar::name() const { if (_domain.defined()) { return _var().var; } else { return _name; } } template <int N> ReductionDomain build_domain(ReductionVariable (&vars)[N]) { vector<ReductionVariable> d(&vars[0], &vars[N]); ReductionDomain dom(d); return dom; } // This just initializes the predefined x, y, z, w members of RDom. void RDom::init_vars(string name) { static string var_names[] = { "x", "y", "z", "w" }; if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } const std::vector<ReductionVariable> &dom_vars = dom.domain(); RVar *vars[] = { &x, &y, &z, &w }; for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) { if (i < dom_vars.size()) { *(vars[i]) = RVar(dom, i); } else { *(vars[i]) = RVar(name + "." + var_names[i]); } } } RDom::RDom(ReductionDomain d) : dom(d) { init_vars(""); } // We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w. RDom::RDom(Expr min, Expr extent, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min), cast<int>(extent) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, Expr min7, Expr extent7, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, { name + ".7$r", cast<int>(min7), cast<int>(extent7) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Buffer b) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < b.dimensions(); i++) { ReductionVariable var = { b.name() + "." + var_names[i], b.min(i), b.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(b.name()); } RDom::RDom(ImageParam p) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < p.dimensions(); i++) { ReductionVariable var = { p.name() + "." + var_names[i], p.min(i), p.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(p.name()); } int RDom::dimensions() const { return (int)dom.domain().size(); } RVar RDom::operator[](int i) const { if (i == 0) return x; if (i == 1) return y; if (i == 2) return z; if (i == 3) return w; if (i < dimensions()) { return RVar(dom, i); } user_error << "Reduction domain index out of bounds: " << i << "\n"; return x; // Keep the compiler happy } RDom::operator Expr() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to Expr.\n"; } return Expr(x); } RDom::operator RVar() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to RVar.\n"; } return x; } /** Emit an RVar in a human-readable form */ std::ostream &operator<<(std::ostream &stream, RVar v) { stream << v.name() << "(" << v.min() << ", " << v.extent() << ")"; return stream; } /** Emit an RDom in a human-readable form. */ std::ostream &operator<<(std::ostream &stream, RDom dom) { stream << "RDom(\n"; for (int i = 0; i < dom.dimensions(); i++) { stream << " " << dom[i] << "\n"; } stream << ")\n"; return stream; } } <commit_msg>undef<int> -> Expr()<commit_after>#include "RDom.h" #include "Util.h" #include "IROperator.h" #include "IRPrinter.h" namespace Halide { using namespace Internal; using std::string; using std::vector; RVar::operator Expr() const { if (!min().defined() || !extent().defined()) { user_error << "Use of undefined RDom dimension: " << (name().empty() ? "<unknown>" : name()) << "\n"; } return Variable::make(Int(32), name(), domain()); } Expr RVar::min() const { if (_domain.defined()) { return _var().min; } else { return Expr(); } } Expr RVar::extent() const { if (_domain.defined()) { return _var().extent; } else { return Expr(); } } const std::string &RVar::name() const { if (_domain.defined()) { return _var().var; } else { return _name; } } template <int N> ReductionDomain build_domain(ReductionVariable (&vars)[N]) { vector<ReductionVariable> d(&vars[0], &vars[N]); ReductionDomain dom(d); return dom; } // This just initializes the predefined x, y, z, w members of RDom. void RDom::init_vars(string name) { static string var_names[] = { "x", "y", "z", "w" }; if (name == "") { name = make_entity_name(this, "Halide::RDom", 'r'); } const std::vector<ReductionVariable> &dom_vars = dom.domain(); RVar *vars[] = { &x, &y, &z, &w }; for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) { if (i < dom_vars.size()) { *(vars[i]) = RVar(dom, i); } else { *(vars[i]) = RVar(name + "." + var_names[i]); } } } RDom::RDom(ReductionDomain d) : dom(d) { init_vars(""); } // We suffix all RVars with $r to prevent unintentional name matches with pure vars called x, y, z, w. RDom::RDom(Expr min, Expr extent, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min), cast<int>(extent) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Expr min0, Expr extent0, Expr min1, Expr extent1, Expr min2, Expr extent2, Expr min3, Expr extent3, Expr min4, Expr extent4, Expr min5, Expr extent5, Expr min6, Expr extent6, Expr min7, Expr extent7, string name) { ReductionVariable vars[] = { { name + ".x$r", cast<int>(min0), cast<int>(extent0) }, { name + ".y$r", cast<int>(min1), cast<int>(extent1) }, { name + ".z$r", cast<int>(min2), cast<int>(extent2) }, { name + ".w$r", cast<int>(min3), cast<int>(extent3) }, { name + ".4$r", cast<int>(min4), cast<int>(extent4) }, { name + ".5$r", cast<int>(min5), cast<int>(extent5) }, { name + ".6$r", cast<int>(min6), cast<int>(extent6) }, { name + ".7$r", cast<int>(min7), cast<int>(extent7) }, }; dom = build_domain(vars); init_vars(name); } RDom::RDom(Buffer b) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < b.dimensions(); i++) { ReductionVariable var = { b.name() + "." + var_names[i], b.min(i), b.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(b.name()); } RDom::RDom(ImageParam p) { static string var_names[] = {"x$r", "y$r", "z$r", "w$r"}; std::vector<ReductionVariable> vars; for (int i = 0; i < p.dimensions(); i++) { ReductionVariable var = { p.name() + "." + var_names[i], p.min(i), p.extent(i) }; vars.push_back(var); } dom = ReductionDomain(vars); init_vars(p.name()); } int RDom::dimensions() const { return (int)dom.domain().size(); } RVar RDom::operator[](int i) const { if (i == 0) return x; if (i == 1) return y; if (i == 2) return z; if (i == 3) return w; if (i < dimensions()) { return RVar(dom, i); } user_error << "Reduction domain index out of bounds: " << i << "\n"; return x; // Keep the compiler happy } RDom::operator Expr() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to Expr.\n"; } return Expr(x); } RDom::operator RVar() const { if (dimensions() != 1) { user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n" << (*this) << "\n" << "Only single-dimensional RDoms can be cast to RVar.\n"; } return x; } /** Emit an RVar in a human-readable form */ std::ostream &operator<<(std::ostream &stream, RVar v) { stream << v.name() << "(" << v.min() << ", " << v.extent() << ")"; return stream; } /** Emit an RDom in a human-readable form. */ std::ostream &operator<<(std::ostream &stream, RDom dom) { stream << "RDom(\n"; for (int i = 0; i < dom.dimensions(); i++) { stream << " " << dom[i] << "\n"; } stream << ")\n"; return stream; } } <|endoftext|>
<commit_before>/* Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "message.h" #include "messagefetchjob.h" #include "messagemodel.h" #include "messagequery.h" #include "monitor.h" #include <kmime_message.h> #include <kdebug.h> #include <klocale.h> #include <QDebug> using namespace PIM; class MessageModel::Private { public: QList<Message*> messages; QByteArray path; MessageFetchJob *listingJob; Monitor *monitor; QList<MessageQuery*> fetchJobs, updateJobs; }; PIM::MessageModel::MessageModel( QObject *parent ) : QAbstractTableModel( parent ), d( new Private() ) { d->listingJob = 0; d->monitor = 0; } PIM::MessageModel::~MessageModel( ) { delete d->listingJob; delete d->monitor; qDeleteAll( d->fetchJobs ); qDeleteAll( d->updateJobs ); delete d; } int PIM::MessageModel::columnCount( const QModelIndex & parent ) const { Q_UNUSED( parent ); return 5; // keep in sync with the column type enum } QVariant PIM::MessageModel::data( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); if ( index.row() >= d->messages.count() ) return QVariant(); Message* msg = d->messages.at( index.row() ); Q_ASSERT( msg->mime() ); if ( role == Qt::DisplayRole ) { switch ( index.column() ) { case Subject: return msg->mime()->subject()->asUnicodeString(); case Sender: return msg->mime()->from()->asUnicodeString(); case Receiver: return msg->mime()->to()->asUnicodeString(); case Date: return msg->mime()->date()->asUnicodeString(); case Size: // TODO default: return QVariant(); } } return QVariant(); } int PIM::MessageModel::rowCount( const QModelIndex & parent ) const { Q_UNUSED( parent ); return d->messages.count(); } QVariant PIM::MessageModel::headerData( int section, Qt::Orientation orientation, int role ) const { if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) { switch ( section ) { case Subject: return i18n( "Subject" ); case Sender: return i18n( "Sender" ); case Receiver: return i18n( "Receiver" ); case Date: return i18n( "Date" ); case Size: return i18n( "Size" ); default: return QString(); } } return QAbstractTableModel::headerData( section, orientation, role ); } void PIM::MessageModel::setPath( const QByteArray& path ) { if ( d->path == path ) return; d->path = path; // the query changed, thus everything we have already is invalid d->messages.clear(); reset(); // stop all running jobs delete d->monitor; d->monitor = 0; qDeleteAll( d->updateJobs ); d->updateJobs.clear(); qDeleteAll( d->fetchJobs ); d->updateJobs.clear(); delete d->listingJob; // start listing job d->listingJob = new MessageFetchJob( path, this ); connect( d->listingJob, SIGNAL( done( PIM::Job* ) ), SLOT( listingDone( PIM::Job* ) ) ); d->listingJob->start(); } void PIM::MessageModel::listingDone( PIM::Job * job ) { Q_ASSERT( job == d->listingJob ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Message query failed!" << endl; } else { d->messages = d->listingJob->messages(); reset(); } d->listingJob->deleteLater(); d->listingJob = 0; // start monitor job // TODO error handling /*d->monitor = new Monitor( "folder=" + d->path ); connect( d->monitor, SIGNAL( changed( const DataReference::List& ) ), SLOT( messagesChanged( const DataReference::List& ) ) ); connect( d->monitor, SIGNAL( added( const DataReference::List& ) ), SLOT( messagesAdded( const DataReference::List& ) ) ); connect( d->monitor, SIGNAL( removed( const DataReference::List& ) ), SLOT( messagesRemoved( const DataReference::List& ) ) );*/ // d->monitor->start(); } void PIM::MessageModel::fetchingNewDone( PIM::Job * job ) { Q_ASSERT( d->fetchJobs.contains( static_cast<MessageQuery*>( job ) ) ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Fetching new messages failed!" << endl; } else { Message::List list = static_cast<MessageQuery*>( job )->messages(); beginInsertRows( QModelIndex(), d->messages.size(), d->messages.size() + list.size() ); d->messages += list; endInsertRows(); } d->fetchJobs.removeAll( static_cast<MessageQuery*>( job ) ); job->deleteLater(); } void PIM::MessageModel::fetchingUpdatesDone( PIM::Job * job ) { Q_ASSERT( d->updateJobs.contains( static_cast<MessageQuery*>( job ) ) ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Updating changed messages failed!" << endl; } else { Message::List list = static_cast<MessageQuery*>( job )->messages(); foreach ( Message* msg, list ) { // ### *slow* for ( int i = 0; i < d->messages.size(); ++i ) { if ( d->messages.at( i )->reference() == msg->reference() ) { delete d->messages.at( i ); d->messages.replace( i, msg ); emit dataChanged( index( i, 0 ), index( i, columnCount() ) ); break; } } } } d->updateJobs.removeAll( static_cast<MessageQuery*>( job ) ); job->deleteLater(); } void PIM::MessageModel::messagesChanged( const DataReference::List & references ) { // TODO: build query based on the reference list QString query; MessageQuery* job = new MessageQuery( query ); connect( job, SIGNAL( done( PIM::Job* ) ), SLOT( fetchingUpdatesDone( PIM::Job* job ) ) ); job->start(); d->updateJobs.append( job ); } void PIM::MessageModel::messagesAdded( const DataReference::List & references ) { // TODO: build query based on the reference list QString query; MessageQuery* job = new MessageQuery( query ); connect( job, SIGNAL( done( PIM::Job* ) ), SLOT( fetchingNewDone( PIM::Job* job ) ) ); job->start(); d->fetchJobs.append( job ); } void PIM::MessageModel::messagesRemoved( const DataReference::List & references ) { foreach ( DataReference ref, references ) { // ### *slow* int index = -1; for ( int i = 0; i < d->messages.size(); ++i ) { if ( d->messages.at( i )->reference() == ref ) { index = i; break; } } if ( index < 0 ) continue; beginRemoveRows( QModelIndex(), index, index ); Message* msg = d->messages.at( index ); d->messages.removeAt( index ); delete msg; endRemoveRows(); } } DataReference PIM::MessageModel::referenceForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return DataReference(); if ( index.row() >= d->messages.count() ) return DataReference(); Message *msg = d->messages.at( index.row() ); Q_ASSERT( msg ); return msg->reference(); } #include "messagemodel.moc" <commit_msg>This is a flat model, so don't report child items.<commit_after>/* Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "message.h" #include "messagefetchjob.h" #include "messagemodel.h" #include "messagequery.h" #include "monitor.h" #include <kmime_message.h> #include <kdebug.h> #include <klocale.h> #include <QDebug> using namespace PIM; class MessageModel::Private { public: QList<Message*> messages; QByteArray path; MessageFetchJob *listingJob; Monitor *monitor; QList<MessageQuery*> fetchJobs, updateJobs; }; PIM::MessageModel::MessageModel( QObject *parent ) : QAbstractTableModel( parent ), d( new Private() ) { d->listingJob = 0; d->monitor = 0; } PIM::MessageModel::~MessageModel( ) { delete d->listingJob; delete d->monitor; qDeleteAll( d->fetchJobs ); qDeleteAll( d->updateJobs ); delete d; } int PIM::MessageModel::columnCount( const QModelIndex & parent ) const { Q_UNUSED( parent ); return 5; // keep in sync with the column type enum } QVariant PIM::MessageModel::data( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); if ( index.row() >= d->messages.count() ) return QVariant(); Message* msg = d->messages.at( index.row() ); Q_ASSERT( msg->mime() ); if ( role == Qt::DisplayRole ) { switch ( index.column() ) { case Subject: return msg->mime()->subject()->asUnicodeString(); case Sender: return msg->mime()->from()->asUnicodeString(); case Receiver: return msg->mime()->to()->asUnicodeString(); case Date: return msg->mime()->date()->asUnicodeString(); case Size: // TODO default: return QVariant(); } } return QVariant(); } int PIM::MessageModel::rowCount( const QModelIndex & parent ) const { if ( !parent.isValid() ) return d->messages.count(); return 0; } QVariant PIM::MessageModel::headerData( int section, Qt::Orientation orientation, int role ) const { if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) { switch ( section ) { case Subject: return i18n( "Subject" ); case Sender: return i18n( "Sender" ); case Receiver: return i18n( "Receiver" ); case Date: return i18n( "Date" ); case Size: return i18n( "Size" ); default: return QString(); } } return QAbstractTableModel::headerData( section, orientation, role ); } void PIM::MessageModel::setPath( const QByteArray& path ) { if ( d->path == path ) return; d->path = path; // the query changed, thus everything we have already is invalid d->messages.clear(); reset(); // stop all running jobs delete d->monitor; d->monitor = 0; qDeleteAll( d->updateJobs ); d->updateJobs.clear(); qDeleteAll( d->fetchJobs ); d->updateJobs.clear(); delete d->listingJob; // start listing job d->listingJob = new MessageFetchJob( path, this ); connect( d->listingJob, SIGNAL( done( PIM::Job* ) ), SLOT( listingDone( PIM::Job* ) ) ); d->listingJob->start(); } void PIM::MessageModel::listingDone( PIM::Job * job ) { Q_ASSERT( job == d->listingJob ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Message query failed!" << endl; } else { d->messages = d->listingJob->messages(); reset(); } d->listingJob->deleteLater(); d->listingJob = 0; // start monitor job // TODO error handling /*d->monitor = new Monitor( "folder=" + d->path ); connect( d->monitor, SIGNAL( changed( const DataReference::List& ) ), SLOT( messagesChanged( const DataReference::List& ) ) ); connect( d->monitor, SIGNAL( added( const DataReference::List& ) ), SLOT( messagesAdded( const DataReference::List& ) ) ); connect( d->monitor, SIGNAL( removed( const DataReference::List& ) ), SLOT( messagesRemoved( const DataReference::List& ) ) );*/ // d->monitor->start(); } void PIM::MessageModel::fetchingNewDone( PIM::Job * job ) { Q_ASSERT( d->fetchJobs.contains( static_cast<MessageQuery*>( job ) ) ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Fetching new messages failed!" << endl; } else { Message::List list = static_cast<MessageQuery*>( job )->messages(); beginInsertRows( QModelIndex(), d->messages.size(), d->messages.size() + list.size() ); d->messages += list; endInsertRows(); } d->fetchJobs.removeAll( static_cast<MessageQuery*>( job ) ); job->deleteLater(); } void PIM::MessageModel::fetchingUpdatesDone( PIM::Job * job ) { Q_ASSERT( d->updateJobs.contains( static_cast<MessageQuery*>( job ) ) ); if ( job->error() ) { // TODO kWarning() << k_funcinfo << "Updating changed messages failed!" << endl; } else { Message::List list = static_cast<MessageQuery*>( job )->messages(); foreach ( Message* msg, list ) { // ### *slow* for ( int i = 0; i < d->messages.size(); ++i ) { if ( d->messages.at( i )->reference() == msg->reference() ) { delete d->messages.at( i ); d->messages.replace( i, msg ); emit dataChanged( index( i, 0 ), index( i, columnCount() ) ); break; } } } } d->updateJobs.removeAll( static_cast<MessageQuery*>( job ) ); job->deleteLater(); } void PIM::MessageModel::messagesChanged( const DataReference::List & references ) { // TODO: build query based on the reference list QString query; MessageQuery* job = new MessageQuery( query ); connect( job, SIGNAL( done( PIM::Job* ) ), SLOT( fetchingUpdatesDone( PIM::Job* job ) ) ); job->start(); d->updateJobs.append( job ); } void PIM::MessageModel::messagesAdded( const DataReference::List & references ) { // TODO: build query based on the reference list QString query; MessageQuery* job = new MessageQuery( query ); connect( job, SIGNAL( done( PIM::Job* ) ), SLOT( fetchingNewDone( PIM::Job* job ) ) ); job->start(); d->fetchJobs.append( job ); } void PIM::MessageModel::messagesRemoved( const DataReference::List & references ) { foreach ( DataReference ref, references ) { // ### *slow* int index = -1; for ( int i = 0; i < d->messages.size(); ++i ) { if ( d->messages.at( i )->reference() == ref ) { index = i; break; } } if ( index < 0 ) continue; beginRemoveRows( QModelIndex(), index, index ); Message* msg = d->messages.at( index ); d->messages.removeAt( index ); delete msg; endRemoveRows(); } } DataReference PIM::MessageModel::referenceForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return DataReference(); if ( index.row() >= d->messages.count() ) return DataReference(); Message *msg = d->messages.at( index.row() ); Q_ASSERT( msg ); return msg->reference(); } #include "messagemodel.moc" <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs01.C /// @brief Run and manage the DDR4 MRS01 loading /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs01_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs01_data::mrs01_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_dll_enable(fapi2::ENUM_ATTR_EFF_DRAM_DLL_ENABLE_YES), iv_additive_latency(0), iv_wl_enable(0), iv_tdqs(0), iv_qoff(0) { FAPI_TRY( mss::eff_dram_dll_enable(i_target, iv_dll_enable) ); FAPI_TRY( mss::vpd_mt_dram_drv_imp_dq_dqs(i_target, &(iv_odic[0])) ); FAPI_TRY( mss::eff_dram_al(i_target, iv_additive_latency) ); FAPI_TRY( mss::eff_dram_wr_lvl_enable(i_target, iv_wl_enable) ); FAPI_TRY( mss::eff_dram_rtt_nom(i_target, &(iv_rtt_nom[0])) ); FAPI_TRY( mss::eff_dram_tdqs(i_target, iv_tdqs) ); FAPI_TRY( mss::eff_dram_output_buffer(i_target, iv_qoff) ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("unable to get attributes for mrs0"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs01_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "Unable to construct MRS01 data from attributes"); FAPI_TRY( mrs01(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs01_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Little table to map Output Driver Imepdance Control. 34Ohm is index 0, // 48Ohm is index 1 // Left bit is A2, right bit is A1 constexpr uint8_t odic_map[] = { 0b00, 0b01 }; constexpr uint64_t ODIC_LENGTH = 2; constexpr uint64_t ODIC_START_BIT = 7; constexpr uint64_t ADDITIVE_LATENCE_LENGTH = 2; constexpr uint64_t ADDITIVE_LATENCE_START_BIT = 7; constexpr uint64_t RTT_NOM_LENGTH = 3; constexpr uint64_t RTT_NOM_START_BIT = 7; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_odic_buffer; fapi2::buffer<uint8_t> l_rtt_nom_buffer; //check here to make sure the rank indexes correctly into the attribute array //It's equivalent to mss::index(i_rank) < l_rtt_nom.size() if C arrays had a .size() method fapi2::Assert( mss::index(i_rank) < MAX_RANK_PER_DIMM); FAPI_ASSERT( ((i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) || (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM48)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(1) .set_PARAMETER(OUTPUT_IMPEDANCE) .set_PARAMETER_VALUE(i_data.iv_odic[mss::index(i_rank)]) .set_DIMM_IN_ERROR(i_target), "Bad value for output driver impedance: %d (%s)", i_data.iv_odic[mss::index(i_rank)], mss::c_str(i_target)); // Map from impedance to bits in MRS1 l_odic_buffer = (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) ? odic_map[0] : odic_map[1]; // Map from RTT_NOM array to the value in the map l_rtt_nom_buffer = i_data.iv_rtt_nom[mss::index(i_rank)]; // Print this here as opposed to the MRS01 ctor as we want to see the specific rtt now information FAPI_INF("MR1 rank %d attributes: DLL_ENABLE: 0x%x, ODIC: 0x%x(0x%x), AL: 0x%x, WLE: 0x%x, " "RTT_NOM:0x%x, TDQS: 0x%x, QOFF: 0x%x", i_rank, i_data.iv_dll_enable, i_data.iv_odic[mss::index(i_rank)], uint8_t(l_odic_buffer), uint8_t(l_additive_latency), i_data.iv_wl_enable, uint8_t(l_rtt_nom_buffer), i_data.iv_tdqs, i_data.iv_qoff); io_inst.arr0.writeBit<A0>(i_data.iv_dll_enable); mss::swizzle<A1, ODIC_LENGTH, ODIC_START_BIT>(l_odic_buffer, io_inst.arr0); mss::swizzle<A3, ADDITIVE_LATENCE_LENGTH, ADDITIVE_LATENCE_START_BIT>(fapi2::buffer<uint8_t> (i_data.iv_additive_latency), io_inst.arr0); io_inst.arr0.writeBit<A7>(i_data.iv_wl_enable); mss::swizzle<A8, RTT_NOM_LENGTH, RTT_NOM_START_BIT>(l_rtt_nom_buffer, io_inst.arr0); io_inst.arr0.writeBit<A11>(i_data.iv_tdqs); io_inst.arr0.writeBit<A12>(i_data.iv_qoff); FAPI_INF("MR1: 0x%016llx", uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Helper function for mrs01_decode /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @param[out] o_dll_enable the dll enable bit /// @param[out] o_wrl_enable the write leveling enable bit /// @param[out] o_tdqs the tdqs enable bit /// @param[out] o_qoff the qoff bit /// @param[out] o_odic the output driver impedance control setting /// @param[out] o_additive_latency the additive latency setting /// @param[out] o_rtt_nom the rtt_nom setting /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode_helper(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank, uint8_t& o_dll_enable, uint8_t& o_wrl_enable, uint8_t& o_tdqs, uint8_t& o_qoff, fapi2::buffer<uint8_t>& o_odic, fapi2::buffer<uint8_t>& o_additive_latency, fapi2::buffer<uint8_t>& o_rtt_nom) { o_odic = 0; o_additive_latency = 0; o_rtt_nom = 0; o_dll_enable = i_inst.arr0.getBit<A0>(); o_wrl_enable = i_inst.arr0.getBit<A7>(); o_tdqs = i_inst.arr0.getBit<A11>(); o_qoff = i_inst.arr0.getBit<A12>(); mss::swizzle<6, 2, A2>(i_inst.arr0, o_odic); mss::swizzle<6, 2, A4>(i_inst.arr0, o_additive_latency); mss::swizzle<5, 3, A10>(i_inst.arr0, o_rtt_nom); FAPI_INF("MR1 rank %d decode: DLL_ENABLE: 0x%x, ODIC: 0x%x, AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x, TDQS: 0x%x, QOFF: 0x%x", i_rank, o_dll_enable, uint8_t(o_odic), uint8_t(o_additive_latency), o_wrl_enable, uint8_t(o_rtt_nom), o_tdqs, o_qoff); return FAPI2_RC_SUCCESS; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS1, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { uint8_t l_dll_enable = 0; uint8_t l_wrl_enable = 0; uint8_t l_tdqs = 0; uint8_t l_qoff = 0; fapi2::buffer<uint8_t> l_odic; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_rtt_nom; return mrs01_decode_helper(i_inst, i_rank, l_dll_enable, l_wrl_enable, l_tdqs, l_qoff, l_odic, l_additive_latency, l_rtt_nom); } fapi2::ReturnCode (*mrs01_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) = &mrs01; fapi2::ReturnCode (*mrs01_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) = &mrs01_decode; } // ns ddr4 } // ns mss <commit_msg>L3 draminit and mss_lib<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs01.C /// @brief Run and manage the DDR4 MRS01 loading /// // *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs01_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs01_data::mrs01_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_dll_enable(fapi2::ENUM_ATTR_EFF_DRAM_DLL_ENABLE_YES), iv_additive_latency(0), iv_wl_enable(0), iv_tdqs(0), iv_qoff(0) { FAPI_TRY( mss::eff_dram_dll_enable(i_target, iv_dll_enable), "Error in mrs01_data()" ); FAPI_TRY( mss::vpd_mt_dram_drv_imp_dq_dqs(i_target, &(iv_odic[0])), "Error in mrs01_data()" ); FAPI_TRY( mss::eff_dram_al(i_target, iv_additive_latency), "Error in mrs01_data()" ); FAPI_TRY( mss::eff_dram_wr_lvl_enable(i_target, iv_wl_enable), "Error in mrs01_data()" ); FAPI_TRY( mss::eff_dram_rtt_nom(i_target, &(iv_rtt_nom[0])), "Error in mrs01_data()" ); FAPI_TRY( mss::eff_dram_tdqs(i_target, iv_tdqs), "Error in mrs01_data()" ); FAPI_TRY( mss::eff_dram_output_buffer(i_target, iv_qoff), "Error in mrs01_data()" ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("%s unable to get attributes for mrs01"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs01_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "%s Unable to construct MRS01 data from attributes", mss::c_str(i_target) ); FAPI_TRY( mrs01(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs01_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Little table to map Output Driver Imepdance Control. 34Ohm is index 0, // 48Ohm is index 1 // Left bit is A2, right bit is A1 constexpr uint8_t odic_map[] = { 0b00, 0b01 }; constexpr uint64_t ODIC_LENGTH = 2; constexpr uint64_t ODIC_START_BIT = 7; constexpr uint64_t ADDITIVE_LATENCE_LENGTH = 2; constexpr uint64_t ADDITIVE_LATENCE_START_BIT = 7; constexpr uint64_t RTT_NOM_LENGTH = 3; constexpr uint64_t RTT_NOM_START_BIT = 7; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_odic_buffer; fapi2::buffer<uint8_t> l_rtt_nom_buffer; //check here to make sure the rank indexes correctly into the attribute array //It's equivalent to mss::index(i_rank) < l_rtt_nom.size() if C arrays had a .size() method fapi2::Assert( mss::index(i_rank) < MAX_RANK_PER_DIMM); FAPI_ASSERT( ((i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) || (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM48)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(1) .set_PARAMETER(OUTPUT_IMPEDANCE) .set_PARAMETER_VALUE(i_data.iv_odic[mss::index(i_rank)]) .set_DIMM_IN_ERROR(i_target), "Bad value for output driver impedance: %d (%s)", i_data.iv_odic[mss::index(i_rank)], mss::c_str(i_target)); // Map from impedance to bits in MRS1 l_odic_buffer = (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) ? odic_map[0] : odic_map[1]; // Map from RTT_NOM array to the value in the map l_rtt_nom_buffer = i_data.iv_rtt_nom[mss::index(i_rank)]; // Print this here as opposed to the MRS01 ctor as we want to see the specific rtt now information FAPI_INF("%s MR1 rank %d attributes: DLL_ENABLE: 0x%x, ODIC: 0x%x(0x%x), AL: 0x%x, WLE: 0x%x, " "RTT_NOM:0x%x, TDQS: 0x%x, QOFF: 0x%x", mss::c_str(i_target), i_rank, i_data.iv_dll_enable, i_data.iv_odic[mss::index(i_rank)], uint8_t(l_odic_buffer), uint8_t(l_additive_latency), i_data.iv_wl_enable, uint8_t(l_rtt_nom_buffer), i_data.iv_tdqs, i_data.iv_qoff); io_inst.arr0.writeBit<A0>(i_data.iv_dll_enable); mss::swizzle<A1, ODIC_LENGTH, ODIC_START_BIT>(l_odic_buffer, io_inst.arr0); mss::swizzle<A3, ADDITIVE_LATENCE_LENGTH, ADDITIVE_LATENCE_START_BIT>(fapi2::buffer<uint8_t> (i_data.iv_additive_latency), io_inst.arr0); io_inst.arr0.writeBit<A7>(i_data.iv_wl_enable); mss::swizzle<A8, RTT_NOM_LENGTH, RTT_NOM_START_BIT>(l_rtt_nom_buffer, io_inst.arr0); io_inst.arr0.writeBit<A11>(i_data.iv_tdqs); io_inst.arr0.writeBit<A12>(i_data.iv_qoff); FAPI_INF("%s MR1: 0x%016llx", mss::c_str(i_target), uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Helper function for mrs01_decode /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @param[out] o_dll_enable the dll enable bit /// @param[out] o_wrl_enable the write leveling enable bit /// @param[out] o_tdqs the tdqs enable bit /// @param[out] o_qoff the qoff bit /// @param[out] o_odic the output driver impedance control setting /// @param[out] o_additive_latency the additive latency setting /// @param[out] o_rtt_nom the rtt_nom setting /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode_helper(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank, uint8_t& o_dll_enable, uint8_t& o_wrl_enable, uint8_t& o_tdqs, uint8_t& o_qoff, fapi2::buffer<uint8_t>& o_odic, fapi2::buffer<uint8_t>& o_additive_latency, fapi2::buffer<uint8_t>& o_rtt_nom) { o_odic = 0; o_additive_latency = 0; o_rtt_nom = 0; o_dll_enable = i_inst.arr0.getBit<A0>(); o_wrl_enable = i_inst.arr0.getBit<A7>(); o_tdqs = i_inst.arr0.getBit<A11>(); o_qoff = i_inst.arr0.getBit<A12>(); mss::swizzle<6, 2, A2>(i_inst.arr0, o_odic); mss::swizzle<6, 2, A4>(i_inst.arr0, o_additive_latency); mss::swizzle<5, 3, A10>(i_inst.arr0, o_rtt_nom); FAPI_INF("MR1 rank %d decode: DLL_ENABLE: 0x%x, ODIC: 0x%x, AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x, TDQS: 0x%x, QOFF: 0x%x", i_rank, o_dll_enable, uint8_t(o_odic), uint8_t(o_additive_latency), o_wrl_enable, uint8_t(o_rtt_nom), o_tdqs, o_qoff); return FAPI2_RC_SUCCESS; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS1, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { uint8_t l_dll_enable = 0; uint8_t l_wrl_enable = 0; uint8_t l_tdqs = 0; uint8_t l_qoff = 0; fapi2::buffer<uint8_t> l_odic; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_rtt_nom; return mrs01_decode_helper(i_inst, i_rank, l_dll_enable, l_wrl_enable, l_tdqs, l_qoff, l_odic, l_additive_latency, l_rtt_nom); } fapi2::ReturnCode (*mrs01_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) = &mrs01; fapi2::ReturnCode (*mrs01_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) = &mrs01_decode; } // ns ddr4 } // ns mss <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_get_poundv_bucket.C /// @brief Grab PM data from certain bucket in #V keyword in LRPX record /// // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_get_poundv_bucket.H> #include <mvpd_access_defs.H> #include <attribute_ids.H> fapi2::ReturnCode p9_pm_get_poundv_bucket( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, fapi2::voltageBucketData_t& o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket ...."); //Create a pointer version of the out param o_data so that // we can access bytes individually uint8_t* l_tempBuffer = reinterpret_cast<uint8_t*>(malloc(sizeof(o_data))); //Set up a char array to hold the bucket data from an attr read fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr; //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA, i_target, l_bucketAttr)); #ifndef _BIG_ENDIAN //The first byte is simply a uint8 that describes the bucket ID l_tempBuffer[0] = l_bucketAttr[0]; //Skipping the first byte (which has already been taken of) start reading //the voltage data 2 bytes at a time. for(uint8_t offset = 1; offset < sizeof(o_data); offset += 2) { //Switch from Big Endian to Little Endian l_tempBuffer[offset] = l_bucketAttr[offset + 1]; l_tempBuffer[offset + 1] = l_bucketAttr[offset]; } memcpy(&o_data, l_tempBuffer, sizeof(o_data)); #else memcpy(&o_data, l_bucketAttr, sizeof(o_data)); #endif fapi_try_exit: free(l_tempBuffer); FAPI_IMP("Exiting p9_pm_get_poundv_bucket ...."); return fapi2::current_err; } fapi2::ReturnCode p9_pm_get_poundv_bucket_attr( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, uint8_t* o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket_attr ...."); uint8_t* l_prDataPtr = NULL; uint8_t* l_fullVpdData = NULL; uint8_t l_overridePresent = 0; uint32_t l_vpdSize = 0; uint32_t l_eqFapiPos = 0; uint8_t l_bucketId; fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS; do { //To read MVPD we will need the proc parent of the inputted EQ target fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); //check if bucket num has been overriden FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE, i_target, l_overridePresent)); if(l_overridePresent != 0) { //If it has been overriden then get the override FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM, i_target, l_bucketId)); } else { //Otherwise get the bucket num from MVPD data //First read is to get size of vpd record, note the o_buffer is NULL l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI, fapi2::MVPD_KEYWORD_PR, l_procParent, NULL, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PR keyword size from VINI record"); break; } l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_vpdSize)); //Second read is to get data of vpd record l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI, fapi2::MVPD_KEYWORD_PR, l_procParent, l_prDataPtr, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PR keyword from VINI record"); break; } memcpy(&l_bucketId, (l_prDataPtr), sizeof(uint8_t)); } //Need to determine which LRP record to read from depending on which //bucket we are getting the power management data from. FapiPos will //tell us which LRP record to use. FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FAPI_POS, i_target, l_eqFapiPos)); fapi2::MvpdRecord lprRecord; switch(l_eqFapiPos) { case 0: lprRecord = fapi2::MVPD_RECORD_LRP0; break; case 1: lprRecord = fapi2::MVPD_RECORD_LRP1; break; case 2: lprRecord = fapi2::MVPD_RECORD_LRP2; break; case 3: lprRecord = fapi2::MVPD_RECORD_LRP3; break; case 4: lprRecord = fapi2::MVPD_RECORD_LRP4; break; case 5: lprRecord = fapi2::MVPD_RECORD_LRP5; break; default: FAPI_ERR("No LRP record found for EQ with fapi pos = %d", l_eqFapiPos); assert(0); break; } //Reset VPD size because we want to find size of another VPD record l_vpdSize = 0; //First read is to get size of vpd record, note the o_buffer is NULL l_rc = getMvpdField(lprRecord, fapi2::MVPD_KEYWORD_PDV, l_procParent, NULL, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword size from LRP%d record", l_eqFapiPos); break; } //Allocate memory for vpd data l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_vpdSize)); FAPI_ASSERT(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33) >= sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type), fapi2::BAD_VPD_READ() .set_EXPECTED_SIZE(sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type)) .set_ACTUAL_SIZE(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33)), "#V data read was too small!" ); //Second read is to get data of vpd record l_rc = getMvpdField(lprRecord, fapi2::MVPD_KEYWORD_PDV, l_procParent, l_fullVpdData, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword from LRP%d record", l_eqFapiPos); break; } //#V record is laid out as follows: //Name: 0x2 byte //Length: 0x2 byte //Version: 0x1 byte **buffer starts here //PNP: 0x3 byte //bucket a: 0x33 byte //bucket b: 0x33 byte //bucket c: 0x33 byte //bucket d: 0x33 byte //bucket e: 0x33 byte //bucket f: 0x33 byte if( *l_fullVpdData == 0x2) { memcpy(o_data, l_fullVpdData + 4 + (l_bucketId - 1) * 0x33, sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type)); } else { FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x", *l_fullVpdData); FAPI_ASSERT(0, fapi2::INVALID_POUNDV_VERSION() .set_POUNDV_VERSION(*l_fullVpdData), "#V is of an invalid version!" ); } } while(0); fapi_try_exit: if(l_fullVpdData != NULL) { free(l_fullVpdData); } if(l_prDataPtr != NULL) { free(l_prDataPtr); } FAPI_IMP("Exiting p9_pm_get_poundv_bucket_attr ...."); //If there is no issue in the current err, check //the local rc to see if the mvpd access methods caught anything if((fapi2::current_err == fapi2::FAPI2_RC_SUCCESS) && (l_rc != fapi2::FAPI2_RC_SUCCESS)) { fapi2::current_err = l_rc; } return fapi2::current_err; } <commit_msg>Read 4byte into PR keyword to get Bucket ID for #V data<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_get_poundv_bucket.C /// @brief Grab PM data from certain bucket in #V keyword in LRPX record /// // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_get_poundv_bucket.H> #include <mvpd_access_defs.H> #include <attribute_ids.H> fapi2::ReturnCode p9_pm_get_poundv_bucket( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, fapi2::voltageBucketData_t& o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket ...."); //Create a pointer version of the out param o_data so that // we can access bytes individually uint8_t* l_tempBuffer = reinterpret_cast<uint8_t*>(malloc(sizeof(o_data))); //Set up a char array to hold the bucket data from an attr read fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr; //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA, i_target, l_bucketAttr)); #ifndef _BIG_ENDIAN //The first byte is simply a uint8 that describes the bucket ID l_tempBuffer[0] = l_bucketAttr[0]; //Skipping the first byte (which has already been taken of) start reading //the voltage data 2 bytes at a time. for(uint8_t offset = 1; offset < sizeof(o_data); offset += 2) { //Switch from Big Endian to Little Endian l_tempBuffer[offset] = l_bucketAttr[offset + 1]; l_tempBuffer[offset + 1] = l_bucketAttr[offset]; } memcpy(&o_data, l_tempBuffer, sizeof(o_data)); #else memcpy(&o_data, l_bucketAttr, sizeof(o_data)); #endif fapi_try_exit: free(l_tempBuffer); FAPI_IMP("Exiting p9_pm_get_poundv_bucket ...."); return fapi2::current_err; } fapi2::ReturnCode p9_pm_get_poundv_bucket_attr( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, uint8_t* o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket_attr ...."); uint8_t* l_prDataPtr = NULL; uint8_t* l_fullVpdData = NULL; uint8_t l_overridePresent = 0; uint32_t l_vpdSize = 0; uint32_t l_eqFapiPos = 0; uint8_t l_bucketId; fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS; do { //To read MVPD we will need the proc parent of the inputted EQ target fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); //check if bucket num has been overriden FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE, i_target, l_overridePresent)); if(l_overridePresent != 0) { //If it has been overriden then get the override FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM, i_target, l_bucketId)); } else { //Otherwise get the bucket num from MVPD data //First read is to get size of vpd record, note the o_buffer is NULL l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI, fapi2::MVPD_KEYWORD_PR, l_procParent, NULL, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PR keyword size from VINI record"); break; } l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_vpdSize)); //Second read is to get data of vpd record l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI, fapi2::MVPD_KEYWORD_PR, l_procParent, l_prDataPtr, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PR keyword from VINI record"); break; } //Bucket ID is byte[4] of the PR keyword memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t)); } //Need to determine which LRP record to read from depending on which //bucket we are getting the power management data from. FapiPos will //tell us which LRP record to use. FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FAPI_POS, i_target, l_eqFapiPos)); fapi2::MvpdRecord lprRecord; switch(l_eqFapiPos) { case 0: lprRecord = fapi2::MVPD_RECORD_LRP0; break; case 1: lprRecord = fapi2::MVPD_RECORD_LRP1; break; case 2: lprRecord = fapi2::MVPD_RECORD_LRP2; break; case 3: lprRecord = fapi2::MVPD_RECORD_LRP3; break; case 4: lprRecord = fapi2::MVPD_RECORD_LRP4; break; case 5: lprRecord = fapi2::MVPD_RECORD_LRP5; break; default: FAPI_ERR("No LRP record found for EQ with fapi pos = %d", l_eqFapiPos); assert(0); break; } //Reset VPD size because we want to find size of another VPD record l_vpdSize = 0; //First read is to get size of vpd record, note the o_buffer is NULL l_rc = getMvpdField(lprRecord, fapi2::MVPD_KEYWORD_PDV, l_procParent, NULL, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword size from LRP%d record", l_eqFapiPos); break; } //Allocate memory for vpd data l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_vpdSize)); FAPI_ASSERT(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33) >= sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type), fapi2::BAD_VPD_READ() .set_EXPECTED_SIZE(sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type)) .set_ACTUAL_SIZE(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33)), "#V data read was too small!" ); //Second read is to get data of vpd record l_rc = getMvpdField(lprRecord, fapi2::MVPD_KEYWORD_PDV, l_procParent, l_fullVpdData, l_vpdSize); if(l_rc) { FAPI_ERR("p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword from LRP%d record", l_eqFapiPos); break; } //#V record is laid out as follows: //Name: 0x2 byte //Length: 0x2 byte //Version: 0x1 byte **buffer starts here //PNP: 0x3 byte //bucket a: 0x33 byte //bucket b: 0x33 byte //bucket c: 0x33 byte //bucket d: 0x33 byte //bucket e: 0x33 byte //bucket f: 0x33 byte if( *l_fullVpdData == 0x2) { memcpy(o_data, l_fullVpdData + 4 + (l_bucketId - 1) * 0x33, sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type)); } else { FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x", *l_fullVpdData); FAPI_ASSERT(0, fapi2::INVALID_POUNDV_VERSION() .set_POUNDV_VERSION(*l_fullVpdData), "#V is of an invalid version!" ); } } while(0); fapi_try_exit: if(l_fullVpdData != NULL) { free(l_fullVpdData); } if(l_prDataPtr != NULL) { free(l_prDataPtr); } FAPI_IMP("Exiting p9_pm_get_poundv_bucket_attr ...."); //If there is no issue in the current err, check //the local rc to see if the mvpd access methods caught anything if((fapi2::current_err == fapi2::FAPI2_RC_SUCCESS) && (l_rc != fapi2::FAPI2_RC_SUCCESS)) { fapi2::current_err = l_rc; } return fapi2::current_err; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../../StroikaPreComp.h" #include "Reader.h" //// SEEE http://www.zlib.net/zlib_how.html /// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object /// where inner loop is done each time through with a CHUNK #if qHasFeature_ZLib #include <zlib.h> #if defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "zlib.lib") #endif using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::DataExchange::Compression; using namespace Stroika::Foundation::Streams; namespace { void ThrowIfZLibErr_ (int err) { if (err != Z_OK) { Execution::Throw (Execution::StringException (L"ZLIB ERR")); // @todo embelish } } using Memory::Byte; struct MyCompressionStream_ : InputStream<Byte> { struct BaseRep_ : public _IRep { static constexpr size_t CHUNK = 16384; Streams::InputStream<Memory::Byte> fInStream_; z_stream fZStream_; Byte fInBuf_[CHUNK]; BaseRep_ (const Streams::InputStream<Memory::Byte>& in) : fInStream_ (in) , fZStream_ {} { } virtual ~BaseRep_ () = default; virtual bool IsSeekable () const { // for now - KISS return false; // SHOULD allow seekable IFF src is seekable } virtual SeekOffsetType GetReadOffset () const override { return SeekOffsetType {}; } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return SeekOffsetType {}; } void _AssureInputAvailable () { if (fZStream_.avail_in == 0) { fZStream_.avail_in = fInStream_.Read (begin (fInBuf_), end (fInBuf_)); fZStream_.next_in = begin (fInBuf_); } } }; struct DeflateRep_ : BaseRep_ { DeflateRep_ (const Streams::InputStream<Memory::Byte>& in) : BaseRep_ (in) { int level = Z_DEFAULT_COMPRESSION; ThrowIfZLibErr_ (::deflateInit (&fZStream_, level)); } virtual ~DeflateRep_ () { Verify (::deflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override { _AssureInputAvailable (); // @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data //tmphack - do 1 byte at a time Require (intoStart < intoEnd); fZStream_.avail_out = intoEnd - intoStart; fZStream_.next_out = intoStart; ThrowIfZLibErr_ (::deflate (&fZStream_, Z_NO_FLUSH)); ptrdiff_t have = CHUNK - fZStream_.avail_out; Assert (have < intoEnd - intoStart); return have; } }; struct InflateRep_ : BaseRep_ { InflateRep_ (const Streams::InputStream<Memory::Byte>& in) : BaseRep_ (in) { ThrowIfZLibErr_ (::inflateInit (&fZStream_)); } virtual ~InflateRep_ () { Verify (::inflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override { _AssureInputAvailable (); // @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data //tmphack - do 1 byte at a time Require (intoStart < intoEnd); fZStream_.avail_out = intoEnd - intoStart; fZStream_.next_out = intoStart; ThrowIfZLibErr_ (::inflate (&fZStream_, Z_NO_FLUSH)); ptrdiff_t have = CHUNK - fZStream_.avail_out; Assert (have < intoEnd - intoStart); return have; } }; enum Compression {eCompression}; enum DeCompression {eDeCompression}; MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>& in) : InputStream<Byte> (make_shared<DeflateRep_> (in)) { } MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>& in) : InputStream<Byte> (make_shared<InflateRep_> (in))/// tmphack cuz NYI otjer { } }; } #endif #if qHasFeature_ZLib class Zip::Reader::Rep_ : public Reader::_IRep { public: virtual InputStream<Byte> Compress (const InputStream<Byte>& src) const override { return MyCompressionStream_ (MyCompressionStream_::eCompression, src); } virtual InputStream<Byte> Decompress (const InputStream<Byte>& src) const override { return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src); } }; Zip::Reader::Reader () : DataExchange::Compression::Reader (make_shared<Rep_> ()) { } #endif <commit_msg>Some progress on flush param for DataExchange/Compression/Zip/Reader<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../../StroikaPreComp.h" #include "Reader.h" //// SEEE http://www.zlib.net/zlib_how.html /// THIS SHOWS PRETTY SIMPLE EXAMPLE OF HOW TO DO COMPRESS/DECOMPRESS AND WE CAN USE THAT to amke new stream object /// where inner loop is done each time through with a CHUNK #if qHasFeature_ZLib #include <zlib.h> #if defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "zlib.lib") #endif using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::DataExchange::Compression; using namespace Stroika::Foundation::Streams; namespace { void ThrowIfZLibErr_ (int err) { if (err != Z_OK) { Execution::Throw (Execution::StringException (L"ZLIB ERR")); // @todo embelish } } using Memory::Byte; struct MyCompressionStream_ : InputStream<Byte> { struct BaseRep_ : public _IRep { static constexpr size_t CHUNK = 16384; Streams::InputStream<Memory::Byte> fInStream_; z_stream fZStream_; Byte fInBuf_[CHUNK]; BaseRep_ (const Streams::InputStream<Memory::Byte>& in) : fInStream_ (in) , fZStream_ {} { } virtual ~BaseRep_ () = default; virtual bool IsSeekable () const { // for now - KISS return false; // SHOULD allow seekable IFF src is seekable } virtual SeekOffsetType GetReadOffset () const override { return SeekOffsetType {}; } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return SeekOffsetType {}; } void _AssureInputAvailable () { if (fZStream_.avail_in == 0) { fZStream_.avail_in = fInStream_.Read (begin (fInBuf_), end (fInBuf_)); fZStream_.next_in = begin (fInBuf_); } } }; struct DeflateRep_ : BaseRep_ { DeflateRep_ (const Streams::InputStream<Memory::Byte>& in) : BaseRep_ (in) { int level = Z_DEFAULT_COMPRESSION; ThrowIfZLibErr_ (::deflateInit (&fZStream_, level)); } virtual ~DeflateRep_ () { Verify (::deflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override { _AssureInputAvailable (); // @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data //tmphack - do 1 byte at a time Require (intoStart < intoEnd); //int flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; int flush = fZStream_.avail_in == 0 ? Z_FINISH : Z_NO_FLUSH; fZStream_.avail_out = intoEnd - intoStart; fZStream_.next_out = intoStart; ThrowIfZLibErr_ (::deflate (&fZStream_, flush)); ptrdiff_t have = CHUNK - fZStream_.avail_out; Assert (have < intoEnd - intoStart); return have; } }; struct InflateRep_ : BaseRep_ { InflateRep_ (const Streams::InputStream<Memory::Byte>& in) : BaseRep_ (in) { ThrowIfZLibErr_ (::inflateInit (&fZStream_)); } virtual ~InflateRep_ () { Verify (::inflateEnd (&fZStream_) == Z_OK); } virtual size_t Read (SeekOffsetType* offset, ElementType* intoStart, ElementType* intoEnd) override { _AssureInputAvailable (); // @TODO - THIS IS WRONG- in that it doesnt take into account if strm.next_in still has data //tmphack - do 1 byte at a time Require (intoStart < intoEnd); fZStream_.avail_out = intoEnd - intoStart; fZStream_.next_out = intoStart; ThrowIfZLibErr_ (::inflate (&fZStream_, Z_NO_FLUSH)); ptrdiff_t have = CHUNK - fZStream_.avail_out; Assert (have < intoEnd - intoStart); return have; } }; enum Compression {eCompression}; enum DeCompression {eDeCompression}; MyCompressionStream_ (Compression, const Streams::InputStream<Memory::Byte>& in) : InputStream<Byte> (make_shared<DeflateRep_> (in)) { } MyCompressionStream_ (DeCompression, const Streams::InputStream<Memory::Byte>& in) : InputStream<Byte> (make_shared<InflateRep_> (in))/// tmphack cuz NYI otjer { } }; } #endif #if qHasFeature_ZLib class Zip::Reader::Rep_ : public Reader::_IRep { public: virtual InputStream<Byte> Compress (const InputStream<Byte>& src) const override { return MyCompressionStream_ (MyCompressionStream_::eCompression, src); } virtual InputStream<Byte> Decompress (const InputStream<Byte>& src) const override { return MyCompressionStream_ (MyCompressionStream_::eDeCompression, src); } }; Zip::Reader::Reader () : DataExchange::Compression::Reader (make_shared<Rep_> ()) { } #endif <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Windows.hpp> # include <d3d11.h> # include <Siv3D/Array.hpp> # include <Siv3D/Vertex2D.hpp> # include "D3D11Renderer2DCommand.hpp" namespace s3d { using IndexType = Vertex2D::IndexType; struct BatchInfo { uint32 indexCount = 0; uint32 startIndexLocation = 0; uint32 baseVertexLocation = 0; }; class D3D11SpriteBatch { private: struct BatchBufferPos { uint16 vertexPos = 0; uint32 indexPos = 0; }; ID3D11Device* m_device = nullptr; ID3D11DeviceContext* m_context = nullptr; ComPtr<ID3D11Buffer> m_vertexBuffer; uint32 m_vertexBufferWritePos = 0; ComPtr<ID3D11Buffer> m_indexBuffer; uint32 m_indexBufferWritePos = 0; Array<Vertex2D> m_vertexArray; uint32 m_vertexArrayWritePos = 0; Array<IndexType> m_indexArray; uint32 m_indexArrayWritePos = 0; Array<BatchBufferPos> m_batches; static constexpr uint32 InitialVertexArraySize = 4096; static constexpr uint32 InitialIndexArraySize = 4096 * 8; // 32768 static constexpr uint32 MaxVertexArraySize = 65536 * 64; // 4,194,304 static constexpr uint32 MaxIndexArraySize = 65536 * 64; // 4,194,304 static constexpr uint32 VertexBufferSize = 65535;// 65535; static constexpr uint32 IndexBufferSize = VertexBufferSize * 4; // 524,288 public: D3D11SpriteBatch(); [[nodiscard]] bool init(ID3D11Device* device, ID3D11DeviceContext* context); [[nodiscard]] std::tuple<Vertex2D*, IndexType*, IndexType> getBuffer(const uint16 vertexSize, const uint32 indexSize, D3D11Renderer2DCommand& command); [[nodiscard]] size_t num_batches() const noexcept; void reset(); void setBuffers(); [[nodiscard]] BatchInfo updateBuffers(size_t batchIndex); }; } <commit_msg>update IndexBufferSize<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Windows.hpp> # include <d3d11.h> # include <Siv3D/Array.hpp> # include <Siv3D/Vertex2D.hpp> # include "D3D11Renderer2DCommand.hpp" namespace s3d { using IndexType = Vertex2D::IndexType; struct BatchInfo { uint32 indexCount = 0; uint32 startIndexLocation = 0; uint32 baseVertexLocation = 0; }; class D3D11SpriteBatch { private: struct BatchBufferPos { uint16 vertexPos = 0; uint32 indexPos = 0; }; ID3D11Device* m_device = nullptr; ID3D11DeviceContext* m_context = nullptr; ComPtr<ID3D11Buffer> m_vertexBuffer; uint32 m_vertexBufferWritePos = 0; ComPtr<ID3D11Buffer> m_indexBuffer; uint32 m_indexBufferWritePos = 0; Array<Vertex2D> m_vertexArray; uint32 m_vertexArrayWritePos = 0; Array<IndexType> m_indexArray; uint32 m_indexArrayWritePos = 0; Array<BatchBufferPos> m_batches; static constexpr uint32 InitialVertexArraySize = 4096; static constexpr uint32 InitialIndexArraySize = 4096 * 8; // 32768 static constexpr uint32 MaxVertexArraySize = 65536 * 64; // 4,194,304 static constexpr uint32 MaxIndexArraySize = 65536 * 64; // 4,194,304 static constexpr uint32 VertexBufferSize = 65535;// 65535; static constexpr uint32 IndexBufferSize = (VertexBufferSize + 1) * 4; // 524,288 public: D3D11SpriteBatch(); [[nodiscard]] bool init(ID3D11Device* device, ID3D11DeviceContext* context); [[nodiscard]] std::tuple<Vertex2D*, IndexType*, IndexType> getBuffer(const uint16 vertexSize, const uint32 indexSize, D3D11Renderer2DCommand& command); [[nodiscard]] size_t num_batches() const noexcept; void reset(); void setBuffers(); [[nodiscard]] BatchInfo updateBuffers(size_t batchIndex); }; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // AliFemtoCutMonitorParticleYPtWithWeights - the cut monitor for particles to study // // the difference between reconstructed and true momentum // // author: Rafal Maselek rmaselek@cern.ch // //////////////////////////////////////////////////////////////////////////////// #include "AliFemtoCutMonitorParticleYPtWithWeights.h" #include "AliFemtoModelHiddenInfo.h" #include <TH1D.h> #include <TH2D.h> #include <TList.h> #include <TMath.h> AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(TH2D *filter, int calculateWeights = 1): fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(0.13957), filterHist(filter), fCalcWeights(calculateWeights) { // Default constructor fYPt = new TH2D("YPt", "Rapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); fYPhi = new TH2D("YPhi", "Rapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); fPtPhi = new TH2D("PtPhi", "Pt vs Phi", 100, 0.0, 3.0, 100, -TMath::Pi(), TMath::Pi()); fEtaPhi = new TH2D("EtaPhi", "Pseudorapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); fEtaPt = new TH2D("EtaPt", "Pseudorapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); // fEtaPhiW = new TH2D("EtaPhiW", "Pseudorapidity vs Phi chi2/N weighted", 140, -1.4, 1.4, 100, -TMath::Pi(), TMath::Pi()); // fEtaPtW = new TH2D("EtaPtW", "Pseudorapidity vs Pt chi2/N weighted", 140, -1.4, 1.4, 100, 0.0, 5.0); fDCARPt = new TH2D("DCARPt", "DCA in XY vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); fDCAZPt = new TH2D("DCAZPt", "DCA in Z vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); } AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(const char *aName, float aMass, TH2D *filter, int calculateWeights=1): fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(aMass), filterHist(filter), fCalcWeights(calculateWeights) { // Normal constructor char name[200]; snprintf(name, 200, "YPt%s", aName); fYPt = new TH2D(name, "Rapdity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); snprintf(name, 200, "YPhi%s", aName); fYPhi = new TH2D(name, "Rapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "PtPhi%s", aName); fPtPhi = new TH2D(name, "Pt vs Phi", 100, 0.0, 3.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "EtaPhi%s", aName); fEtaPhi = new TH2D(name, "Pseudorapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "EtaPt%s", aName); fEtaPt = new TH2D(name, "Pseudorapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); // snprintf(name, 200, "EtaPhiW%s", aName); // fEtaPhiW = new TH2D(name, "Pseudorapidity vs Phi chi2/N weighted", 140, -1.4, 1.4, 100, -TMath::Pi(), TMath::Pi()); // snprintf(name, 200, "EtaPtW%s", aName); // fEtaPtW = new TH2D(name, "Pseudorapidity vs Pt chi2/N weighted", 140, -1.4, 1.4, 100, 0.0, 2.0); snprintf(name, 200, "DCARPt%s", aName); fDCARPt = new TH2D(name, "DCA in XY vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); snprintf(name, 200, "DCAZPt%s", aName); fDCAZPt = new TH2D(name, "DCA in Z vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); } AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(const AliFemtoCutMonitorParticleYPtWithWeights &aCut): fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(0.13957), filterHist(0) { // copy constructor fYPt = new TH2D(*aCut.fYPt); fYPhi = new TH2D(*aCut.fYPhi); fPtPhi = new TH2D(*aCut.fPtPhi); fEtaPhi = new TH2D(*aCut.fEtaPhi); fEtaPt = new TH2D(*aCut.fEtaPt); // fEtaPhiW = new TH2D(*aCut.fEtaPhiW); // fEtaPtW = new TH2D(*aCut.fEtaPtW); fDCARPt = new TH2D(*aCut.fDCARPt); fDCAZPt = new TH2D(*aCut.fDCAZPt); filterHist = new TH2D(*aCut.filterHist); fMass = aCut.fMass; fCalcWeights = aCut.fCalcWeights; } AliFemtoCutMonitorParticleYPtWithWeights::~AliFemtoCutMonitorParticleYPtWithWeights() { // Destructor delete fYPt; delete fYPhi; delete fPtPhi; delete fEtaPhi; delete fEtaPt; // delete fEtaPhiW; // delete fEtaPtW; delete fDCARPt; delete fDCAZPt; if(filterHist) delete filterHist; } AliFemtoCutMonitorParticleYPtWithWeights& AliFemtoCutMonitorParticleYPtWithWeights::operator=(const AliFemtoCutMonitorParticleYPtWithWeights& aCut) { // assignment operator if (this == &aCut) return *this; if (fYPt) delete fYPt; fYPt = new TH2D(*aCut.fYPt); if (fYPhi) delete fYPhi; fYPhi = new TH2D(*aCut.fYPhi); if (fPtPhi) delete fPtPhi; fPtPhi = new TH2D(*aCut.fPtPhi); if (fEtaPhi) delete fEtaPhi; fEtaPhi = new TH2D(*aCut.fEtaPhi); if (fEtaPt) delete fEtaPt; fEtaPt = new TH2D(*aCut.fEtaPt); // if (fEtaPhiW) delete fEtaPhiW; // fEtaPhiW = new TH2D(*aCut.fEtaPhiW); // if (fEtaPtW) delete fEtaPtW; // fEtaPtW = new TH2D(*aCut.fEtaPtW); if (fDCARPt) delete fDCARPt; fDCARPt = new TH2D(*aCut.fDCARPt); if (fDCAZPt) delete fDCAZPt; fDCAZPt = new TH2D(*aCut.fDCAZPt); if(filterHist) delete filterHist; filterHist = new TH2D(*aCut.filterHist); fCalcWeights = aCut.fCalcWeights; return *this; } AliFemtoString AliFemtoCutMonitorParticleYPtWithWeights::Report(){ // Prepare report from the execution string stemp = "*** AliFemtoCutMonitorParticleYPtWithWeights report"; AliFemtoString returnThis = stemp; return returnThis; } void AliFemtoCutMonitorParticleYPtWithWeights::Fill(const AliFemtoTrack* aTrack) { // Fill in the monitor histograms with the values from the current track float tEnergy = ::sqrt(aTrack->P().Mag2()+fMass*fMass); if(tEnergy==abs(aTrack->P().z())) tEnergy+=0.001; float tRapidity = -1000; if((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z())>0) tRapidity = 0.5*::log((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z())); else tRapidity = -999; float tPt = -1000; if((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y())>=0) tPt = ::sqrt((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y())); else tPt = -999; double weight = filterHist->GetBinContent(filterHist->FindBin(tRapidity, tPt)); if(fCalcWeights == 0) weight=1.0; float tEta; if(aTrack->P().Theta()==0) tEta=0; else tEta = -TMath::Log(TMath::Tan(aTrack->P().Theta()/2.0)); float tPhi = aTrack->P().Phi(); // float chi2w; float dcar = aTrack->ImpactD(); float dcaz = aTrack->ImpactZ(); // if (aTrack->TPCncls() > 0) // chi2w = aTrack->TPCchi2()/aTrack->TPCncls(); // else // chi2w = 6.0; // cout << " CMYPt: " << fYPt << " " << fYPt->GetEntries() << " " << tRapidity << " " << tPt << endl; fYPt->Fill(tRapidity, tPt, weight); fYPhi->Fill(tRapidity, tPhi, weight); fPtPhi->Fill(tPt, tPhi, weight); fEtaPhi->Fill(tEta, tPhi, weight); fEtaPt->Fill(tEta, tPt, weight); // fEtaPhiW->Fill(tEta, tPhi, chi2w); // fEtaPtW->Fill(tEta, tPt, chi2w); fDCARPt->Fill(dcar, tPt, weight); fDCAZPt->Fill(dcaz, tPt, weight); } void AliFemtoCutMonitorParticleYPtWithWeights::Write() { // Write out the relevant histograms fYPt->Write(); fYPhi->Write(); fPtPhi->Write(); fEtaPhi->Write(); fEtaPt->Write(); // fEtaPhiW->Write(); // fEtaPtW->Write(); fDCARPt->Write(); fDCAZPt->Write(); } TList *AliFemtoCutMonitorParticleYPtWithWeights::GetOutputList() { TList *tOutputList = new TList(); tOutputList->Add(fYPt); tOutputList->Add(fYPhi); tOutputList->Add(fPtPhi); tOutputList->Add(fEtaPhi); tOutputList->Add(fEtaPt); // tOutputList->Add(fEtaPhiW); // tOutputList->Add(fEtaPtW); tOutputList->Add(fDCARPt); tOutputList->Add(fDCAZPt); return tOutputList; } <commit_msg>AliFemtoCutMonitorParticleYPtWithWeights - Fix initializer parameter order<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // AliFemtoCutMonitorParticleYPtWithWeights - the cut monitor for particles to study // // the difference between reconstructed and true momentum // // author: Rafal Maselek rmaselek@cern.ch // //////////////////////////////////////////////////////////////////////////////// #include "AliFemtoCutMonitorParticleYPtWithWeights.h" #include "AliFemtoModelHiddenInfo.h" #include <TH1D.h> #include <TH2D.h> #include <TList.h> #include <TMath.h> AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(TH2D *filter, int calculateWeights = 1): filterHist(filter), fCalcWeights(calculateWeights), fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(0.13957) { // Default constructor fYPt = new TH2D("YPt", "Rapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); fYPhi = new TH2D("YPhi", "Rapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); fPtPhi = new TH2D("PtPhi", "Pt vs Phi", 100, 0.0, 3.0, 100, -TMath::Pi(), TMath::Pi()); fEtaPhi = new TH2D("EtaPhi", "Pseudorapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); fEtaPt = new TH2D("EtaPt", "Pseudorapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); // fEtaPhiW = new TH2D("EtaPhiW", "Pseudorapidity vs Phi chi2/N weighted", 140, -1.4, 1.4, 100, -TMath::Pi(), TMath::Pi()); // fEtaPtW = new TH2D("EtaPtW", "Pseudorapidity vs Pt chi2/N weighted", 140, -1.4, 1.4, 100, 0.0, 5.0); fDCARPt = new TH2D("DCARPt", "DCA in XY vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); fDCAZPt = new TH2D("DCAZPt", "DCA in Z vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); } AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(const char *aName, float aMass, TH2D *filter, int calculateWeights=1): filterHist(filter), fCalcWeights(calculateWeights), fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(aMass) { // Normal constructor char name[200]; snprintf(name, 200, "YPt%s", aName); fYPt = new TH2D(name, "Rapdity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); snprintf(name, 200, "YPhi%s", aName); fYPhi = new TH2D(name, "Rapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "PtPhi%s", aName); fPtPhi = new TH2D(name, "Pt vs Phi", 100, 0.0, 3.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "EtaPhi%s", aName); fEtaPhi = new TH2D(name, "Pseudorapidity vs Phi", 100, 0.0, 6.0, 100, -TMath::Pi(), TMath::Pi()); snprintf(name, 200, "EtaPt%s", aName); fEtaPt = new TH2D(name, "Pseudorapidity vs Pt", 100, 0.0, 6.0, 100, 0.0, 3.0); // snprintf(name, 200, "EtaPhiW%s", aName); // fEtaPhiW = new TH2D(name, "Pseudorapidity vs Phi chi2/N weighted", 140, -1.4, 1.4, 100, -TMath::Pi(), TMath::Pi()); // snprintf(name, 200, "EtaPtW%s", aName); // fEtaPtW = new TH2D(name, "Pseudorapidity vs Pt chi2/N weighted", 140, -1.4, 1.4, 100, 0.0, 2.0); snprintf(name, 200, "DCARPt%s", aName); fDCARPt = new TH2D(name, "DCA in XY vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); snprintf(name, 200, "DCAZPt%s", aName); fDCAZPt = new TH2D(name, "DCA in Z vs. Pt", 400, -3.0, 3.0, 100,0.0,3.0); } AliFemtoCutMonitorParticleYPtWithWeights::AliFemtoCutMonitorParticleYPtWithWeights(const AliFemtoCutMonitorParticleYPtWithWeights &aCut): filterHist(0), fCalcWeights(aCut.fCalcWeights), fYPt(0), fYPhi(0), fPtPhi(0), fEtaPhi(0), fEtaPt(0), fEtaPhiW(0), fEtaPtW(0), fDCARPt(0), fDCAZPt(0), fMass(aCut.fMass) { // copy constructor fYPt = new TH2D(*aCut.fYPt); fYPhi = new TH2D(*aCut.fYPhi); fPtPhi = new TH2D(*aCut.fPtPhi); fEtaPhi = new TH2D(*aCut.fEtaPhi); fEtaPt = new TH2D(*aCut.fEtaPt); // fEtaPhiW = new TH2D(*aCut.fEtaPhiW); // fEtaPtW = new TH2D(*aCut.fEtaPtW); fDCARPt = new TH2D(*aCut.fDCARPt); fDCAZPt = new TH2D(*aCut.fDCAZPt); filterHist = new TH2D(*aCut.filterHist); } AliFemtoCutMonitorParticleYPtWithWeights::~AliFemtoCutMonitorParticleYPtWithWeights() { // Destructor delete fYPt; delete fYPhi; delete fPtPhi; delete fEtaPhi; delete fEtaPt; // delete fEtaPhiW; // delete fEtaPtW; delete fDCARPt; delete fDCAZPt; if(filterHist) delete filterHist; } AliFemtoCutMonitorParticleYPtWithWeights& AliFemtoCutMonitorParticleYPtWithWeights::operator=(const AliFemtoCutMonitorParticleYPtWithWeights& aCut) { // assignment operator if (this == &aCut) return *this; if (fYPt) delete fYPt; fYPt = new TH2D(*aCut.fYPt); if (fYPhi) delete fYPhi; fYPhi = new TH2D(*aCut.fYPhi); if (fPtPhi) delete fPtPhi; fPtPhi = new TH2D(*aCut.fPtPhi); if (fEtaPhi) delete fEtaPhi; fEtaPhi = new TH2D(*aCut.fEtaPhi); if (fEtaPt) delete fEtaPt; fEtaPt = new TH2D(*aCut.fEtaPt); // if (fEtaPhiW) delete fEtaPhiW; // fEtaPhiW = new TH2D(*aCut.fEtaPhiW); // if (fEtaPtW) delete fEtaPtW; // fEtaPtW = new TH2D(*aCut.fEtaPtW); if (fDCARPt) delete fDCARPt; fDCARPt = new TH2D(*aCut.fDCARPt); if (fDCAZPt) delete fDCAZPt; fDCAZPt = new TH2D(*aCut.fDCAZPt); if(filterHist) delete filterHist; filterHist = new TH2D(*aCut.filterHist); fCalcWeights = aCut.fCalcWeights; return *this; } AliFemtoString AliFemtoCutMonitorParticleYPtWithWeights::Report(){ // Prepare report from the execution string stemp = "*** AliFemtoCutMonitorParticleYPtWithWeights report"; AliFemtoString returnThis = stemp; return returnThis; } void AliFemtoCutMonitorParticleYPtWithWeights::Fill(const AliFemtoTrack* aTrack) { // Fill in the monitor histograms with the values from the current track float tEnergy = ::sqrt(aTrack->P().Mag2()+fMass*fMass); if(tEnergy==abs(aTrack->P().z())) tEnergy+=0.001; float tRapidity = -1000; if((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z())>0) tRapidity = 0.5*::log((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z())); else tRapidity = -999; float tPt = -1000; if((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y())>=0) tPt = ::sqrt((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y())); else tPt = -999; double weight = filterHist->GetBinContent(filterHist->FindBin(tRapidity, tPt)); if(fCalcWeights == 0) weight=1.0; float tEta; if(aTrack->P().Theta()==0) tEta=0; else tEta = -TMath::Log(TMath::Tan(aTrack->P().Theta()/2.0)); float tPhi = aTrack->P().Phi(); // float chi2w; float dcar = aTrack->ImpactD(); float dcaz = aTrack->ImpactZ(); // if (aTrack->TPCncls() > 0) // chi2w = aTrack->TPCchi2()/aTrack->TPCncls(); // else // chi2w = 6.0; // cout << " CMYPt: " << fYPt << " " << fYPt->GetEntries() << " " << tRapidity << " " << tPt << endl; fYPt->Fill(tRapidity, tPt, weight); fYPhi->Fill(tRapidity, tPhi, weight); fPtPhi->Fill(tPt, tPhi, weight); fEtaPhi->Fill(tEta, tPhi, weight); fEtaPt->Fill(tEta, tPt, weight); // fEtaPhiW->Fill(tEta, tPhi, chi2w); // fEtaPtW->Fill(tEta, tPt, chi2w); fDCARPt->Fill(dcar, tPt, weight); fDCAZPt->Fill(dcaz, tPt, weight); } void AliFemtoCutMonitorParticleYPtWithWeights::Write() { // Write out the relevant histograms fYPt->Write(); fYPhi->Write(); fPtPhi->Write(); fEtaPhi->Write(); fEtaPt->Write(); // fEtaPhiW->Write(); // fEtaPtW->Write(); fDCARPt->Write(); fDCAZPt->Write(); } TList *AliFemtoCutMonitorParticleYPtWithWeights::GetOutputList() { TList *tOutputList = new TList(); tOutputList->Add(fYPt); tOutputList->Add(fYPhi); tOutputList->Add(fPtPhi); tOutputList->Add(fEtaPhi); tOutputList->Add(fEtaPt); // tOutputList->Add(fEtaPhiW); // tOutputList->Add(fEtaPtW); tOutputList->Add(fDCARPt); tOutputList->Add(fDCAZPt); return tOutputList; } <|endoftext|>
<commit_before> #include "allocore/ui/al_PresetMapper.hpp" using namespace al; void PresetMapper::readEntries(std::string path) { Dir presetDir(path); while (presetDir.read()) { FileInfo entry = presetDir.entry(); if (entry.type() == FileInfo::DIR) { readEntries(entry.name()); } else if (entry.type() == FileInfo::REG) { if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") { std::cout << "Found map: " << entry.name(); } } } } PresetMapper::~PresetMapper() { } PresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) { mPresetHandler = &handler; if (mFindAutomatically) { findPresetMaps(); } return *this; } bool PresetMapper::archive(std::string mapName, bool overwrite) { bool ok = true; std::string fullPath = mPresetHandler->buildMapPath(mapName) + "_archive"; if (overwrite) { if(File::isDirectory(fullPath)) { if (!Dir::removeRecursively(fullPath)) { std::cout << "Error removing directory: " << fullPath << " aborting preset map archiving." << std::endl; return false; } } else { if (File::remove(fullPath) != 0) { std::cout << "Error removing file: " << fullPath << " aborting preset map archiving." << std::endl; return false; } } if (!Dir::make(fullPath)) { std::cout << "Error creating preset map archive directory " << fullPath << std::endl; return false; } } else { int counter = 0; while (File::isDirectory(fullPath)) { std::string newName = mapName + "_" + std::to_string(counter++); fullPath = mPresetHandler->buildMapPath(newName) + "_archive"; if (counter == 0) { // We've wrapped and run out of names... std::cout << "Out of names for preset map archive." << std::endl; return false; } } if (!Dir::make(fullPath)) { std::cout << "Error creating preset map archive directory " << fullPath << std::endl; return false; } } std::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName); for(auto const &preset : presetMap) { std::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + ".preset"; if (!File::copy(presetFilename, fullPath)) { std::cout << "Error copying preset " << presetFilename << " when archiving preset map." << std::endl; ok = false; } } if (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + "default.presetMap")) { std::cout << "Error copying map: " << mapName << " when archiving preset map." << std::endl; ok = false; } return ok; } bool PresetMapper::load(std::string archiveName) { if (! (archiveName.size() > 8 && archiveName.substr(archiveName.size() - 8) == "_archive") ) { archiveName +="_ archive"; } std::string mapPath = mPresetHandler->getRootPath() + archiveName; if (File::isDirectory(mapPath)) { mPresetHandler->setSubDirectory(archiveName); mPresetHandler->setCurrentPresetMap("default"); } else { std::cout << "Error loading archive: " << archiveName << std::endl; return false; } return true; } std::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives) { std::vector<std::string> mapList; Dir mapperDir(mPresetHandler->getCurrentPath()); // TODO it makes more sense to sort entries alphabetically while(mapperDir.read()) { const FileInfo &info = mapperDir.entry(); if (info.type() == FileInfo::DIR && showArchives) { std::string name = info.name(); if ( (name.size() > 18 && name.substr(name.size() - 18) == ".presetMap_archive")) { mapList.push_back(name); } } else if (info.type() == FileInfo::REG && !showArchives) { std::string name = info.name(); if ( (name.size() > 4 && name.substr(name.size() - 4) == ".txt") || (name.size() > 10 && name.substr(name.size() - 10) == ".presetMap")) { mapList.push_back(name); } } } return mapList; } bool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath) { if(m.addressPattern() == rootOSCPath + "/map" && m.typeTags() == "s"){ std::string val; m >> val; std::cout << "OSC: Recall preset map: " << val << std::endl; this->restore(val); return true; } return false; } bool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate) { bool ok = true; if (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == ".presetMap_archive") { // restore from archive std::cout << "Restoring archive " << mapName << std::endl; Dir mapDirectory(mPresetHandler->getCurrentPath() + mapName); std::string mapNewName = mapName.substr(0, mapName.size() - sizeof("_archive") + 1); while (mapDirectory.read()) { const FileInfo &entry = mapDirectory.entry(); if (entry.type() == FileInfo::REG) { if (entry.name().substr(entry.name().size() - 7) == ".preset") { if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + entry.name())) { File::remove(mPresetHandler->getCurrentPath() + entry.name()); } if (!File::copy(mPresetHandler->getCurrentPath() + mapName + "/" + entry.name(), mPresetHandler->getCurrentPath() + entry.name())) { std::cout << "Error restoring preset " << entry.name() << " for " << mapName << std::endl; ok = false; } } else if (entry.name() == "default.presetMap") { if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + mapNewName)) { File::remove(mPresetHandler->getCurrentPath() + "/" + entry.name()); } if (!File::copy(mPresetHandler->getCurrentPath() + "/" + mapName + "/default.presetMap", mPresetHandler->getCurrentPath() + "/" + mapNewName)) { std::cout << "Error restoring preset map " << mapNewName << " for " << mapName << std::endl; ok = false; } } else { std::cout << "PresetMapper::restore() invalid file: " << entry.name() << std::endl; } } } mPresetHandler->setCurrentPresetMap(mapNewName, autoCreate); } else { // set preset map directly mPresetHandler->setCurrentPresetMap(mapName, autoCreate); } return ok; } void PresetMapper::findPresetMaps() { std::string presetsPath = mPresetHandler->getCurrentPath(); Dir presetDir(presetsPath); while (presetDir.read()) { FileInfo entry = presetDir.entry(); if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") { std::cout << "Found map: " << entry.name() << std::endl; } } } <commit_msg>Load preset map instead of restore in OSC server<commit_after> #include "allocore/ui/al_PresetMapper.hpp" using namespace al; void PresetMapper::readEntries(std::string path) { Dir presetDir(path); while (presetDir.read()) { FileInfo entry = presetDir.entry(); if (entry.type() == FileInfo::DIR) { readEntries(entry.name()); } else if (entry.type() == FileInfo::REG) { if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") { std::cout << "Found map: " << entry.name(); } } } } PresetMapper::~PresetMapper() { } PresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) { mPresetHandler = &handler; if (mFindAutomatically) { findPresetMaps(); } return *this; } bool PresetMapper::archive(std::string mapName, bool overwrite) { bool ok = true; std::string fullPath = mPresetHandler->buildMapPath(mapName) + "_archive"; if (overwrite) { if(File::isDirectory(fullPath)) { if (!Dir::removeRecursively(fullPath)) { std::cout << "Error removing directory: " << fullPath << " aborting preset map archiving." << std::endl; return false; } } else { if (File::remove(fullPath) != 0) { std::cout << "Error removing file: " << fullPath << " aborting preset map archiving." << std::endl; return false; } } if (!Dir::make(fullPath)) { std::cout << "Error creating preset map archive directory " << fullPath << std::endl; return false; } } else { int counter = 0; while (File::isDirectory(fullPath)) { std::string newName = mapName + "_" + std::to_string(counter++); fullPath = mPresetHandler->buildMapPath(newName) + "_archive"; if (counter == 0) { // We've wrapped and run out of names... std::cout << "Out of names for preset map archive." << std::endl; return false; } } if (!Dir::make(fullPath)) { std::cout << "Error creating preset map archive directory " << fullPath << std::endl; return false; } } std::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName); for(auto const &preset : presetMap) { std::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + ".preset"; if (!File::copy(presetFilename, fullPath)) { std::cout << "Error copying preset " << presetFilename << " when archiving preset map." << std::endl; ok = false; } } if (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + "default.presetMap")) { std::cout << "Error copying map: " << mapName << " when archiving preset map." << std::endl; ok = false; } return ok; } bool PresetMapper::load(std::string archiveName) { if (! (archiveName.size() > 8 && archiveName.substr(archiveName.size() - 8) == "_archive") ) { archiveName +="_ archive"; } std::string mapPath = mPresetHandler->getRootPath() + archiveName; if (File::isDirectory(mapPath)) { mPresetHandler->setSubDirectory(archiveName); mPresetHandler->setCurrentPresetMap("default"); } else { std::cout << "Error loading archive: " << archiveName << std::endl; return false; } return true; } std::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives) { std::vector<std::string> mapList; Dir mapperDir(mPresetHandler->getCurrentPath()); // TODO it makes more sense to sort entries alphabetically while(mapperDir.read()) { const FileInfo &info = mapperDir.entry(); if (info.type() == FileInfo::DIR && showArchives) { std::string name = info.name(); if ( (name.size() > 18 && name.substr(name.size() - 18) == ".presetMap_archive")) { mapList.push_back(name); } } else if (info.type() == FileInfo::REG && !showArchives) { std::string name = info.name(); if ( (name.size() > 4 && name.substr(name.size() - 4) == ".txt") || (name.size() > 10 && name.substr(name.size() - 10) == ".presetMap")) { mapList.push_back(name); } } } return mapList; } bool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath) { if(m.addressPattern() == rootOSCPath + "/map" && m.typeTags() == "s"){ std::string val; m >> val; std::cout << "OSC: Recall preset map: " << val << std::endl; this->load(val); return true; } return false; } bool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate) { bool ok = true; if (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == ".presetMap_archive") { // restore from archive std::cout << "Restoring archive " << mapName << std::endl; Dir mapDirectory(mPresetHandler->getCurrentPath() + mapName); std::string mapNewName = mapName.substr(0, mapName.size() - sizeof("_archive") + 1); while (mapDirectory.read()) { const FileInfo &entry = mapDirectory.entry(); if (entry.type() == FileInfo::REG) { if (entry.name().substr(entry.name().size() - 7) == ".preset") { if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + entry.name())) { File::remove(mPresetHandler->getCurrentPath() + entry.name()); } if (!File::copy(mPresetHandler->getCurrentPath() + mapName + "/" + entry.name(), mPresetHandler->getCurrentPath() + entry.name())) { std::cout << "Error restoring preset " << entry.name() << " for " << mapName << std::endl; ok = false; } } else if (entry.name() == "default.presetMap") { if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + mapNewName)) { File::remove(mPresetHandler->getCurrentPath() + "/" + entry.name()); } if (!File::copy(mPresetHandler->getCurrentPath() + "/" + mapName + "/default.presetMap", mPresetHandler->getCurrentPath() + "/" + mapNewName)) { std::cout << "Error restoring preset map " << mapNewName << " for " << mapName << std::endl; ok = false; } } else { std::cout << "PresetMapper::restore() invalid file: " << entry.name() << std::endl; } } } mPresetHandler->setCurrentPresetMap(mapNewName, autoCreate); } else { // set preset map directly mPresetHandler->setCurrentPresetMap(mapName, autoCreate); } return ok; } void PresetMapper::findPresetMaps() { std::string presetsPath = mPresetHandler->getCurrentPath(); Dir presetDir(presetsPath); while (presetDir.read()) { FileInfo entry = presetDir.entry(); if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") { std::cout << "Found map: " << entry.name() << std::endl; } } } <|endoftext|>
<commit_before><commit_msg>imgui.cc: ocd fix of NULL -> nullptr<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed usage message.<commit_after><|endoftext|>
<commit_before><commit_msg>GoldDigger Random Magic 0.7<commit_after><|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "foreachfeature.h" #include "valuefeature.h" #include "utils.h" #include <vespa/searchlib/fef/properties.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> #include <boost/algorithm/string/replace.hpp> #include <vespa/log/log.h> LOG_SETUP(".features.foreachfeature"); using namespace search::fef; namespace search::features { template <typename CO, typename OP> ForeachExecutor<CO, OP>::ForeachExecutor(const CO & condition, uint32_t numInputs) : FeatureExecutor(), _condition(condition), _operation(), _numInputs(numInputs) { } template <typename CO, typename OP> void ForeachExecutor<CO, OP>::execute(uint32_t) { _operation.reset(); for (uint32_t i = 0; i < inputs().size(); ++i) { feature_t val = inputs().get_number(i); if (_condition.useValue(val)) { _operation.onValue(val); } } outputs().set_number(0, _operation.getResult()); } bool ForeachBlueprint::decideDimension(const vespalib::string & param) { if (param == "terms") { _dimension = TERMS; } else if (param == "fields") { _dimension = FIELDS; } else if (param == "attributes") { _dimension = ATTRIBUTES; } else { LOG(error, "Expected dimension parameter to be 'terms', 'fields', or 'attributes', but was '%s'", param.c_str()); return false; } return true; } bool ForeachBlueprint::decideCondition(const vespalib::string & condition, const vespalib::string & operation) { if (condition == "true") { return decideOperation(TrueCondition(), operation); } else if (condition.size() >= 2 && condition[0] == '<') { return decideOperation(LessThanCondition(util::strToNum<feature_t>(condition.substr(1))), operation); } else if (condition.size() >= 2 && condition[0] == '>') { return decideOperation(GreaterThanCondition(util::strToNum<feature_t>(condition.substr(1))), operation); } else { LOG(error, "Expected condition parameter to be 'true', '<a', or '>a', but was '%s'", condition.c_str()); return false; } } template <typename CO> bool ForeachBlueprint::decideOperation(CO condition, const vespalib::string & operation) { if (operation == "sum") { setExecutorCreator<CO, SumOperation>(condition); } else if (operation == "product") { setExecutorCreator<CO, ProductOperation>(condition); } else if (operation == "average") { setExecutorCreator<CO, AverageOperation>(condition); } else if (operation == "max") { setExecutorCreator<CO, MaxOperation>(condition); } else if (operation == "min") { setExecutorCreator<CO, MinOperation>(condition); } else if (operation == "count") { setExecutorCreator<CO, CountOperation>(condition); } else { LOG(error, "Expected operation parameter to be 'sum', 'product', 'average', 'max', 'min', or 'count', but was '%s'", operation.c_str()); return false; } return true; } template <typename CO, typename OP> void ForeachBlueprint::setExecutorCreator(CO condition) { class ExecutorCreator : public ExecutorCreatorBase { private: CO _condition; public: ExecutorCreator(CO cond) : _condition(cond) {} search::fef::FeatureExecutor &create(uint32_t numInputs, vespalib::Stash &stash) const override { return stash.create<ForeachExecutor<CO, OP>>(_condition, numInputs); } }; _executorCreator.reset(new ExecutorCreator(condition)); } ForeachBlueprint::ForeachBlueprint() : Blueprint("foreach"), _dimension(ILLEGAL), _executorCreator(), _num_inputs(0) { } ForeachBlueprint::~ForeachBlueprint() = default; void ForeachBlueprint::visitDumpFeatures(const IIndexEnvironment &, IDumpFeatureVisitor &) const { } bool ForeachBlueprint::setup(const IIndexEnvironment & env, const ParameterList & params) { if (!decideDimension(params[0].getValue())) { return false; } if (!decideCondition(params[3].getValue(), params[4].getValue())) { return false; } const vespalib::string & variable = params[1].getValue(); const vespalib::string & feature = params[2].getValue(); if (_dimension == TERMS) { uint32_t maxTerms = util::strToNum<uint32_t>(env.getProperties().lookup(getBaseName(), "maxTerms").get("16")); for (uint32_t i = 0; i < maxTerms; ++i) { defineInput(boost::algorithm::replace_all_copy(feature, variable, vespalib::make_string("%u", i))); ++_num_inputs; } } else { for (uint32_t i = 0; i < env.getNumFields(); ++i) { const FieldInfo * info = env.getField(i); if (info->type() == FieldType::INDEX && _dimension == FIELDS) { defineInput(boost::algorithm::replace_all_copy(feature, variable, info->name())); ++_num_inputs; } else if (info->type() == FieldType::ATTRIBUTE && _dimension == ATTRIBUTES) { defineInput(boost::algorithm::replace_all_copy(feature, variable, info->name())); ++_num_inputs; } } } describeOutput("value", "The result after iterating over the input feature values using the specified operation"); return true; } Blueprint::UP ForeachBlueprint::createInstance() const { return std::make_unique<ForeachBlueprint>(); } FeatureExecutor & ForeachBlueprint::createExecutor(const IQueryEnvironment &, vespalib::Stash &stash) const { if (_executorCreator) { return _executorCreator->create(_num_inputs, stash); } return stash.create<SingleZeroValueExecutor>(); } } <commit_msg>use a more specific string replacement algorithm<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "foreachfeature.h" #include "valuefeature.h" #include "utils.h" #include <vespa/searchlib/fef/properties.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> #include <vespa/vespalib/stllike/replace_variable.h> #include <vespa/log/log.h> LOG_SETUP(".features.foreachfeature"); using namespace search::fef; namespace search::features { template <typename CO, typename OP> ForeachExecutor<CO, OP>::ForeachExecutor(const CO & condition, uint32_t numInputs) : FeatureExecutor(), _condition(condition), _operation(), _numInputs(numInputs) { } template <typename CO, typename OP> void ForeachExecutor<CO, OP>::execute(uint32_t) { _operation.reset(); for (uint32_t i = 0; i < inputs().size(); ++i) { feature_t val = inputs().get_number(i); if (_condition.useValue(val)) { _operation.onValue(val); } } outputs().set_number(0, _operation.getResult()); } bool ForeachBlueprint::decideDimension(const vespalib::string & param) { if (param == "terms") { _dimension = TERMS; } else if (param == "fields") { _dimension = FIELDS; } else if (param == "attributes") { _dimension = ATTRIBUTES; } else { LOG(error, "Expected dimension parameter to be 'terms', 'fields', or 'attributes', but was '%s'", param.c_str()); return false; } return true; } bool ForeachBlueprint::decideCondition(const vespalib::string & condition, const vespalib::string & operation) { if (condition == "true") { return decideOperation(TrueCondition(), operation); } else if (condition.size() >= 2 && condition[0] == '<') { return decideOperation(LessThanCondition(util::strToNum<feature_t>(condition.substr(1))), operation); } else if (condition.size() >= 2 && condition[0] == '>') { return decideOperation(GreaterThanCondition(util::strToNum<feature_t>(condition.substr(1))), operation); } else { LOG(error, "Expected condition parameter to be 'true', '<a', or '>a', but was '%s'", condition.c_str()); return false; } } template <typename CO> bool ForeachBlueprint::decideOperation(CO condition, const vespalib::string & operation) { if (operation == "sum") { setExecutorCreator<CO, SumOperation>(condition); } else if (operation == "product") { setExecutorCreator<CO, ProductOperation>(condition); } else if (operation == "average") { setExecutorCreator<CO, AverageOperation>(condition); } else if (operation == "max") { setExecutorCreator<CO, MaxOperation>(condition); } else if (operation == "min") { setExecutorCreator<CO, MinOperation>(condition); } else if (operation == "count") { setExecutorCreator<CO, CountOperation>(condition); } else { LOG(error, "Expected operation parameter to be 'sum', 'product', 'average', 'max', 'min', or 'count', but was '%s'", operation.c_str()); return false; } return true; } template <typename CO, typename OP> void ForeachBlueprint::setExecutorCreator(CO condition) { class ExecutorCreator : public ExecutorCreatorBase { private: CO _condition; public: ExecutorCreator(CO cond) : _condition(cond) {} search::fef::FeatureExecutor &create(uint32_t numInputs, vespalib::Stash &stash) const override { return stash.create<ForeachExecutor<CO, OP>>(_condition, numInputs); } }; _executorCreator.reset(new ExecutorCreator(condition)); } ForeachBlueprint::ForeachBlueprint() : Blueprint("foreach"), _dimension(ILLEGAL), _executorCreator(), _num_inputs(0) { } ForeachBlueprint::~ForeachBlueprint() = default; void ForeachBlueprint::visitDumpFeatures(const IIndexEnvironment &, IDumpFeatureVisitor &) const { } bool ForeachBlueprint::setup(const IIndexEnvironment & env, const ParameterList & params) { if (!decideDimension(params[0].getValue())) { return false; } if (!decideCondition(params[3].getValue(), params[4].getValue())) { return false; } const vespalib::string & variable = params[1].getValue(); const vespalib::string & feature = params[2].getValue(); if (_dimension == TERMS) { uint32_t maxTerms = util::strToNum<uint32_t>(env.getProperties().lookup(getBaseName(), "maxTerms").get("16")); for (uint32_t i = 0; i < maxTerms; ++i) { defineInput(vespalib::replace_variable(feature, variable, vespalib::make_string("%u", i))); ++_num_inputs; } } else { for (uint32_t i = 0; i < env.getNumFields(); ++i) { const FieldInfo * info = env.getField(i); if (info->type() == FieldType::INDEX && _dimension == FIELDS) { defineInput(vespalib::replace_variable(feature, variable, info->name())); ++_num_inputs; } else if (info->type() == FieldType::ATTRIBUTE && _dimension == ATTRIBUTES) { defineInput(vespalib::replace_variable(feature, variable, info->name())); ++_num_inputs; } } } describeOutput("value", "The result after iterating over the input feature values using the specified operation"); return true; } Blueprint::UP ForeachBlueprint::createInstance() const { return std::make_unique<ForeachBlueprint>(); } FeatureExecutor & ForeachBlueprint::createExecutor(const IQueryEnvironment &, vespalib::Stash &stash) const { if (_executorCreator) { return _executorCreator->create(_num_inputs, stash); } return stash.create<SingleZeroValueExecutor>(); } } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "serializer/log/extent_manager.hpp" #include <queue> #include "arch/arch.hpp" #include "logger.hpp" #include "perfmon/perfmon.hpp" #include "serializer/log/log_serializer.hpp" struct extent_info_t { public: enum state_t { state_unreserved, state_in_use, state_free }; private: state_t state_; public: void set_state(state_t new_state) { guarantee(state_ != state_in_use || extent_use_refcount == 0); state_ = new_state; } state_t state() const { return state_; } // Valid and non-zero when state_in_use. There are two ways to own a part of // this refcount. One is if you believe you're currently "using" the extent (if // you're the LBA or data_block_manager_t). The other is (at the time of // writing) for every (extent_transaction_t, block_id) for live extent // transactions that have set an i_array entry to zero (in the data block // manager) but have not yet been commmitted. The data_block_manager_t and LBA // ownership of the refcount also can get passed into the extent_transaction_t // object. int32_t extent_use_refcount; extent_info_t() : state_(state_unreserved), extent_use_refcount(0) { } }; class extent_zone_t { const size_t extent_size; unsigned int offset_to_id(int64_t extent) const { rassert(divides(extent_size, extent)); return extent / extent_size; } /* Combination free-list and extent map. Contains one entry per extent. During the state_reserving_extents phase, each extent has state state_unreserved or state state_in_use. When we transition to the state_running phase, we link all of the state_unreserved entries in each zone together into an extent free list, such that each free entry's 'next_in_free_list' field is the offset of the next free extent. */ std::vector<extent_info_t> extents; // We want to remove the minimum element from the free_queue first, leaving // free extents at the end of the file. std::priority_queue<unsigned int, std::vector<unsigned int>, std::greater<unsigned int> > free_queue; file_t *const dbfile; int held_extents_; public: int held_extents() const { return held_extents_; } extent_zone_t(file_t *_dbfile, size_t _extent_size) : extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) { // (Avoid a bunch of reallocations by resize calls (avoiding O(n log n) // work on average).) extents.reserve(dbfile->get_size() / extent_size); } extent_reference_t reserve_extent(int64_t extent) { unsigned int id = offset_to_id(extent); if (id >= extents.size()) { extents.resize(id + 1); } rassert(extents[id].state() == extent_info_t::state_unreserved); extents[id].set_state(extent_info_t::state_in_use); return make_extent_reference(extent); } void reconstruct_free_list() { // RSI: Iterate using extent id. for (int64_t extent = 0; extent < static_cast<int64_t>(extents.size() * extent_size); extent += extent_size) { const unsigned int extent_id = offset_to_id(extent); if (extents[extent_id].state() == extent_info_t::state_unreserved) { extents[extent_id].set_state(extent_info_t::state_free); free_queue.push(extent_id); ++held_extents_; } } } extent_reference_t gen_extent() { int64_t extent; if (free_queue.empty()) { extent = extents.size() * extent_size; extents.push_back(extent_info_t()); } else { extent = free_queue.top() * extent_size; free_queue.pop(); --held_extents_; } extent_info_t *info = &extents[offset_to_id(extent)]; info->set_state(extent_info_t::state_in_use); extent_reference_t extent_ref = make_extent_reference(extent); dbfile->set_size_at_least(extent + extent_size); return extent_ref; } extent_reference_t make_extent_reference(const int64_t extent) { unsigned int id = offset_to_id(extent); guarantee(id < extents.size()); extent_info_t *info = &extents[id]; guarantee(info->state() == extent_info_t::state_in_use); ++info->extent_use_refcount; return extent_reference_t(extent); } void release_extent(extent_reference_t &&extent_ref) { int64_t extent = extent_ref.release(); extent_info_t *info = &extents[offset_to_id(extent)]; guarantee(info->state() == extent_info_t::state_in_use); guarantee(info->extent_use_refcount > 0); --info->extent_use_refcount; if (info->extent_use_refcount == 0) { info->set_state(extent_info_t::state_free); free_queue.push(offset_to_id(extent)); ++held_extents_; } } }; extent_manager_t::extent_manager_t(file_t *file, const log_serializer_on_disk_static_config_t *static_config, log_serializer_stats_t *_stats) : stats(_stats), extent_size(static_config->extent_size()), state(state_reserving_extents) { guarantee(divides(DEVICE_BLOCK_SIZE, extent_size)); zone.init(new extent_zone_t(file, extent_size)); } extent_manager_t::~extent_manager_t() { rassert(state == state_reserving_extents || state == state_shut_down); } extent_reference_t extent_manager_t::reserve_extent(int64_t extent) { assert_thread(); rassert(state == state_reserving_extents); ++stats->pm_extents_in_use; stats->pm_bytes_in_use += extent_size; return zone->reserve_extent(extent); } void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) { mb->padding = 0; } void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) { assert_thread(); rassert(state == state_reserving_extents); current_transaction = NULL; zone->reconstruct_free_list(); state = state_running; } void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) { assert_thread(); rassert(state == state_running); metablock->padding = 0; } void extent_manager_t::shutdown() { assert_thread(); rassert(state == state_running); rassert(!current_transaction); state = state_shut_down; } void extent_manager_t::begin_transaction(extent_transaction_t *out) { assert_thread(); rassert(!current_transaction); current_transaction = out; out->init(); } extent_reference_t extent_manager_t::gen_extent() { assert_thread(); rassert(state == state_running); ++stats->pm_extents_in_use; stats->pm_bytes_in_use += extent_size; return zone->gen_extent(); } extent_reference_t extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) { int64_t offset = extent_ref.offset(); return zone->make_extent_reference(offset); } void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) { release_extent_preliminaries(); rassert(current_transaction); txn->push_extent(std::move(extent_ref)); } void extent_manager_t::release_extent(extent_reference_t &&extent_ref) { release_extent_preliminaries(); zone->release_extent(std::move(extent_ref)); } void extent_manager_t::release_extent_preliminaries() { assert_thread(); rassert(state == state_running); --stats->pm_extents_in_use; stats->pm_bytes_in_use -= extent_size; } void extent_manager_t::end_transaction(extent_transaction_t *t) { assert_thread(); rassert(current_transaction == t); current_transaction = NULL; t->mark_end(); } void extent_manager_t::commit_transaction(extent_transaction_t *t) { assert_thread(); std::vector<extent_reference_t> extents = t->reset(); for (auto it = extents.begin(); it != extents.end(); ++it) { zone->release_extent(std::move(*it)); } } int extent_manager_t::held_extents() { assert_thread(); return zone->held_extents(); } <commit_msg>Made reconstruct_free_list just iterate using extent ids instead of offsets.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "serializer/log/extent_manager.hpp" #include <queue> #include "arch/arch.hpp" #include "logger.hpp" #include "perfmon/perfmon.hpp" #include "serializer/log/log_serializer.hpp" struct extent_info_t { public: enum state_t { state_unreserved, state_in_use, state_free }; private: state_t state_; public: void set_state(state_t new_state) { guarantee(state_ != state_in_use || extent_use_refcount == 0); state_ = new_state; } state_t state() const { return state_; } // Valid and non-zero when state_in_use. There are two ways to own a part of // this refcount. One is if you believe you're currently "using" the extent (if // you're the LBA or data_block_manager_t). The other is (at the time of // writing) for every (extent_transaction_t, block_id) for live extent // transactions that have set an i_array entry to zero (in the data block // manager) but have not yet been commmitted. The data_block_manager_t and LBA // ownership of the refcount also can get passed into the extent_transaction_t // object. int32_t extent_use_refcount; extent_info_t() : state_(state_unreserved), extent_use_refcount(0) { } }; class extent_zone_t { const size_t extent_size; unsigned int offset_to_id(int64_t extent) const { rassert(divides(extent_size, extent)); return extent / extent_size; } /* Combination free-list and extent map. Contains one entry per extent. During the state_reserving_extents phase, each extent has state state_unreserved or state state_in_use. When we transition to the state_running phase, we link all of the state_unreserved entries in each zone together into an extent free list, such that each free entry's 'next_in_free_list' field is the offset of the next free extent. */ std::vector<extent_info_t> extents; // We want to remove the minimum element from the free_queue first, leaving // free extents at the end of the file. std::priority_queue<unsigned int, std::vector<unsigned int>, std::greater<unsigned int> > free_queue; file_t *const dbfile; int held_extents_; public: int held_extents() const { return held_extents_; } extent_zone_t(file_t *_dbfile, size_t _extent_size) : extent_size(_extent_size), dbfile(_dbfile), held_extents_(0) { // (Avoid a bunch of reallocations by resize calls (avoiding O(n log n) // work on average).) extents.reserve(dbfile->get_size() / extent_size); } extent_reference_t reserve_extent(int64_t extent) { unsigned int id = offset_to_id(extent); if (id >= extents.size()) { extents.resize(id + 1); } rassert(extents[id].state() == extent_info_t::state_unreserved); extents[id].set_state(extent_info_t::state_in_use); return make_extent_reference(extent); } void reconstruct_free_list() { // RSI: Iterate using extent id. for (unsigned int extent_id = 0; extent_id < extents.size(); ++extent_id) { if (extents[extent_id].state() == extent_info_t::state_unreserved) { extents[extent_id].set_state(extent_info_t::state_free); free_queue.push(extent_id); ++held_extents_; } } } extent_reference_t gen_extent() { int64_t extent; if (free_queue.empty()) { extent = extents.size() * extent_size; extents.push_back(extent_info_t()); } else { extent = free_queue.top() * extent_size; free_queue.pop(); --held_extents_; } extent_info_t *info = &extents[offset_to_id(extent)]; info->set_state(extent_info_t::state_in_use); extent_reference_t extent_ref = make_extent_reference(extent); dbfile->set_size_at_least(extent + extent_size); return extent_ref; } extent_reference_t make_extent_reference(const int64_t extent) { unsigned int id = offset_to_id(extent); guarantee(id < extents.size()); extent_info_t *info = &extents[id]; guarantee(info->state() == extent_info_t::state_in_use); ++info->extent_use_refcount; return extent_reference_t(extent); } void release_extent(extent_reference_t &&extent_ref) { int64_t extent = extent_ref.release(); extent_info_t *info = &extents[offset_to_id(extent)]; guarantee(info->state() == extent_info_t::state_in_use); guarantee(info->extent_use_refcount > 0); --info->extent_use_refcount; if (info->extent_use_refcount == 0) { info->set_state(extent_info_t::state_free); free_queue.push(offset_to_id(extent)); ++held_extents_; } } }; extent_manager_t::extent_manager_t(file_t *file, const log_serializer_on_disk_static_config_t *static_config, log_serializer_stats_t *_stats) : stats(_stats), extent_size(static_config->extent_size()), state(state_reserving_extents) { guarantee(divides(DEVICE_BLOCK_SIZE, extent_size)); zone.init(new extent_zone_t(file, extent_size)); } extent_manager_t::~extent_manager_t() { rassert(state == state_reserving_extents || state == state_shut_down); } extent_reference_t extent_manager_t::reserve_extent(int64_t extent) { assert_thread(); rassert(state == state_reserving_extents); ++stats->pm_extents_in_use; stats->pm_bytes_in_use += extent_size; return zone->reserve_extent(extent); } void extent_manager_t::prepare_initial_metablock(metablock_mixin_t *mb) { mb->padding = 0; } void extent_manager_t::start_existing(UNUSED metablock_mixin_t *last_metablock) { assert_thread(); rassert(state == state_reserving_extents); current_transaction = NULL; zone->reconstruct_free_list(); state = state_running; } void extent_manager_t::prepare_metablock(metablock_mixin_t *metablock) { assert_thread(); rassert(state == state_running); metablock->padding = 0; } void extent_manager_t::shutdown() { assert_thread(); rassert(state == state_running); rassert(!current_transaction); state = state_shut_down; } void extent_manager_t::begin_transaction(extent_transaction_t *out) { assert_thread(); rassert(!current_transaction); current_transaction = out; out->init(); } extent_reference_t extent_manager_t::gen_extent() { assert_thread(); rassert(state == state_running); ++stats->pm_extents_in_use; stats->pm_bytes_in_use += extent_size; return zone->gen_extent(); } extent_reference_t extent_manager_t::copy_extent_reference(const extent_reference_t &extent_ref) { int64_t offset = extent_ref.offset(); return zone->make_extent_reference(offset); } void extent_manager_t::release_extent_into_transaction(extent_reference_t &&extent_ref, extent_transaction_t *txn) { release_extent_preliminaries(); rassert(current_transaction); txn->push_extent(std::move(extent_ref)); } void extent_manager_t::release_extent(extent_reference_t &&extent_ref) { release_extent_preliminaries(); zone->release_extent(std::move(extent_ref)); } void extent_manager_t::release_extent_preliminaries() { assert_thread(); rassert(state == state_running); --stats->pm_extents_in_use; stats->pm_bytes_in_use -= extent_size; } void extent_manager_t::end_transaction(extent_transaction_t *t) { assert_thread(); rassert(current_transaction == t); current_transaction = NULL; t->mark_end(); } void extent_manager_t::commit_transaction(extent_transaction_t *t) { assert_thread(); std::vector<extent_reference_t> extents = t->reset(); for (auto it = extents.begin(); it != extents.end(); ++it) { zone->release_extent(std::move(*it)); } } int extent_manager_t::held_extents() { assert_thread(); return zone->held_extents(); } <|endoftext|>
<commit_before>/* * * Copyright 2018 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstdlib> #include "asylo/platform/primitives/trusted_runtime.h" // The newlib implementation of malloc and free in mallocr.c depends on symbols // _malloc_lock and _malloc_unlock, and requires that a thread waiting on a lock // it already holds will not pause. This file provides a implementation of that // interface inside the enclave with minimal dependencies on other runtime // components which expect to call malloc. #define CACHE_ALIGNED __attribute__((aligned(64))) // The current owner of the lock, aligned to ensure atomic instructions do not // straddle a cache line. A value of zero indicates the lock is not held by any // thread. static volatile uint64_t lock_owner CACHE_ALIGNED = kInvalidThread; // The number of times the lock has been recursively acquired, aligned to ensure // it does not fall in the same cache line as lock_owner to avoid false sharing. // Notes that the count is only accessed by the thread holding the lock and does // not need to be updated atomically. static int lock_count CACHE_ALIGNED = 0; extern "C" { void __malloc_lock(struct reent *) { const uint64_t self = enc_thread_self(); while (lock_owner != self) { uint64_t prev = 0; // Attempt to acquire the mutex by swapping the lock with the current thread // id, specifying strong memory ordering to avoid unexpected memory // ordering. Try to obtain the lock by atomically testing that it is // unlocked and exchanging it with our thread id. if (__atomic_compare_exchange_n(&lock_owner, /*expected=*/&prev, /*desired=*/self, /*weak=*/false, /*success_memorder=*/__ATOMIC_SEQ_CST, /*failure_memorder=*/__ATOMIC_SEQ_CST) != kInvalidThread) { break; } // If the lock is not free, avoid doing a synchronized read and busy wait // until it's release then try to obtain it again. while (lock_owner != kInvalidThread) { // Issue a busy-wait hint to the CPU if possible. enc_pause(); } } lock_count++; } void __malloc_unlock(struct reent *) { // Unlock should only be called by the thread that holds the lock. If this is // not the case we abort. if (lock_owner != enc_thread_self()) { abort(); } lock_count--; if (lock_count == 0) { // Release the lock with an atomic store. __ATOMIC_RELEASE ensures this // write is visible to threads obtaining the lock with __ATOMIC_SEQ_CST. __atomic_store_n(&lock_owner, kInvalidThread, __ATOMIC_RELEASE); } } } // extern "C" <commit_msg>Use constants consistently in malloc_lock<commit_after>/* * * Copyright 2018 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstdlib> #include "asylo/platform/primitives/trusted_runtime.h" // The newlib implementation of malloc and free in mallocr.c depends on symbols // _malloc_lock and _malloc_unlock, and requires that a thread waiting on a lock // it already holds will not pause. This file provides a implementation of that // interface inside the enclave with minimal dependencies on other runtime // components which expect to call malloc. #define CACHE_ALIGNED __attribute__((aligned(64))) // The current owner of the lock, aligned to ensure atomic instructions do not // straddle a cache line. A value of zero indicates the lock is not held by any // thread. static volatile uint64_t lock_owner CACHE_ALIGNED = kInvalidThread; // The number of times the lock has been recursively acquired, aligned to ensure // it does not fall in the same cache line as lock_owner to avoid false sharing. // Notes that the count is only accessed by the thread holding the lock and does // not need to be updated atomically. static int lock_count CACHE_ALIGNED = 0; extern "C" { void __malloc_lock(struct reent *) { const uint64_t self = enc_thread_self(); while (lock_owner != self) { uint64_t unlocked_value = kInvalidThread; // Attempt to acquire the mutex by swapping the lock with the current thread // id, specifying strong memory ordering to avoid unexpected memory // ordering. Try to obtain the lock by atomically testing that it is // unlocked and exchanging it with our thread id. if (__atomic_compare_exchange_n(&lock_owner, /*expected=*/&unlocked_value, /*desired=*/self, /*weak=*/false, /*success_memorder=*/__ATOMIC_SEQ_CST, /*failure_memorder=*/__ATOMIC_SEQ_CST)) { break; } // If the lock is not free, avoid doing a synchronized read and busy wait // until it's released then try to obtain it again. while (lock_owner != kInvalidThread) { // Issue a busy-wait hint to the CPU if possible. enc_pause(); } } lock_count++; } void __malloc_unlock(struct reent *) { // Unlock should only be called by the thread that holds the lock. If this is // not the case we abort. if (lock_owner != enc_thread_self()) { abort(); } lock_count--; if (lock_count == 0) { // Release the lock with an atomic store. __ATOMIC_RELEASE ensures this // write is visible to threads obtaining the lock with __ATOMIC_SEQ_CST. __atomic_store_n(&lock_owner, kInvalidThread, __ATOMIC_RELEASE); } } } // extern "C" <|endoftext|>
<commit_before><commit_msg>BZOJ 4712<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Red Hat, Inc., Stephan Bergmann <sbergman@redhat.com> * (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include <cassert> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <stdio.h> // vsnprintf #include <string.h> // strdup #include "osl/thread.hxx" #include "rtl/string.h" #include "sal/detail/log.h" #include "sal/log.hxx" #include "sal/types.h" #include "logformat.hxx" #if defined WNT #include <process.h> #define OSL_DETAIL_GETPID _getpid() #else #include <unistd.h> #define OSL_DETAIL_GETPID getpid() #endif #ifdef HAVE_SYSLOG_H #include <syslog.h> // sal/osl/unx/salinit.cxx::sal_detail_initialize updates this: bool sal_use_syslog; #endif // Avoid the use of other sal code in this file as much as possible, so that // this code can be called from other sal code without causing endless // recursion. namespace { bool equalStrings( char const * string1, std::size_t length1, char const * string2, std::size_t length2) { return length1 == length2 && std::memcmp(string1, string2, length1) == 0; } char const * toString(sal_detail_LogLevel level) { switch (level) { default: assert(false); // this cannot happen // fall through case SAL_DETAIL_LOG_LEVEL_INFO: return "info"; case SAL_DETAIL_LOG_LEVEL_WARN: return "warn"; case SAL_DETAIL_LOG_LEVEL_DEBUG: return "debug"; } } // getenv is not thread safe, so minimize use of result; except on Android and // iOS, see 60628799633ffde502cb105b98d3f254f93115aa "Notice if SAL_LOG is // changed while the process is running": #if defined ANDROID || defined IOS char const * getEnvironmentVariable() { return std::getenv("SAL_LOG"); } #else char const * getEnvironmentVariable_() { char const * p1 = std::getenv("SAL_LOG"); if (p1 == 0) { return 0; } char const * p2 = strdup(p1); // leaked if (p2 == 0) { std::abort(); // cannot do much here } return p2; } char const * getEnvironmentVariable() { static char const * env = getEnvironmentVariable_(); return env; } #endif #ifdef HAVE_SYSLOG_H int toSyslogPriority(sal_detail_LogLevel level) { switch (level) { default: assert(false); // this cannot happen // fall through case SAL_DETAIL_LOG_LEVEL_INFO: return LOG_INFO; case SAL_DETAIL_LOG_LEVEL_WARN: return LOG_WARNING; case SAL_DETAIL_LOG_LEVEL_DEBUG: return LOG_DEBUG; } } #endif bool report(sal_detail_LogLevel level, char const * area) { if (level == SAL_DETAIL_LOG_LEVEL_DEBUG) return true; assert(area != 0); char const * env = getEnvironmentVariable(); if (env == 0) { env = "+WARN"; } std::size_t areaLen = std::strlen(area); enum Sense { POSITIVE = 0, NEGATIVE = 1 }; std::size_t senseLen[2] = { 0, 1 }; // initial senseLen[POSITIVE] < senseLen[NEGATIVE], so that if there are // no matching switches at all, the result will be negative (and // initializing with 1 is safe as the length of a valid switch, even // without the "+"/"-" prefix, will always be > 1) for (char const * p = env;;) { Sense sense; switch (*p++) { case '\0': return senseLen[POSITIVE] >= senseLen[NEGATIVE]; // if a specific item is both postiive and negative // (senseLen[POSITIVE] == senseLen[NEGATIVE]), default to // positive case '+': sense = POSITIVE; break; case '-': sense = NEGATIVE; break; default: return true; // upon an illegal SAL_LOG value, enable everything } char const * p1 = p; while (*p1 != '.' && *p1 != '+' && *p1 != '-' && *p1 != '\0') { ++p1; } bool match; if (equalStrings(p, p1 - p, RTL_CONSTASCII_STRINGPARAM("INFO"))) { match = level == SAL_DETAIL_LOG_LEVEL_INFO; } else if (equalStrings(p, p1 - p, RTL_CONSTASCII_STRINGPARAM("WARN"))) { match = level == SAL_DETAIL_LOG_LEVEL_WARN; } else { return true; // upon an illegal SAL_LOG value, everything is considered // positive } char const * p2 = p1; while (*p2 != '+' && *p2 != '-' && *p2 != '\0') { ++p2; } if (match) { if (*p1 == '.') { ++p1; std::size_t n = p2 - p1; if ((n == areaLen && equalStrings(p1, n, area, areaLen)) || (n < areaLen && area[n] == '.' && equalStrings(p1, n, area, n))) { senseLen[sense] = p2 - p; } } else { senseLen[sense] = p1 - p; } } p = p2; } } void log( sal_detail_LogLevel level, char const * area, char const * where, char const * message) { std::ostringstream s; #ifdef HAVE_SYSLOG_H if (!sal_use_syslog) #endif s << toString(level) << ':'; if (level == SAL_DETAIL_LOG_LEVEL_DEBUG) { s << /*no where*/' ' << message << '\n'; } else { s << area << ':' << OSL_DETAIL_GETPID << ':' << osl::Thread::getCurrentIdentifier() << ':'; if (strncmp(where, SRCDIR, sizeof(SRCDIR)-1) == 0) s << where+sizeof(SRCDIR); else s << where; s << message << '\n'; } #ifdef HAVE_SYSLOG_H if (sal_use_syslog) syslog(toSyslogPriority(level), "%s", s.str().c_str()); else #endif std::fputs(s.str().c_str(), stderr); } } void sal_detail_log( sal_detail_LogLevel level, char const * area, char const * where, char const * message) { if (report(level, area)) { log(level, area, where, message); } } void sal_detail_logFormat( sal_detail_LogLevel level, char const * area, char const * where, char const * format, ...) { if (report(level, area)) { std::va_list args; va_start(args, format); osl::detail::logFormat(level, area, where, format, args); va_end(args); } } void osl::detail::logFormat( sal_detail_LogLevel level, char const * area, char const * where, char const * format, std::va_list arguments) { char buf[1024]; int const len = sizeof buf - RTL_CONSTASCII_LENGTH("..."); int n = vsnprintf(buf, len, format, arguments); if (n < 0) { std::strcpy(buf, "???"); } else if (n >= len) { std::strcpy(buf + len - 1, "..."); } log(level, area, where, buf); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Pass log output directly to the Android log mechanism<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Red Hat, Inc., Stephan Bergmann <sbergman@redhat.com> * (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "sal/config.h" #include <cassert> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <stdio.h> // vsnprintf #include <string.h> // strdup #include "osl/thread.hxx" #include "rtl/string.h" #include "sal/detail/log.h" #include "sal/log.hxx" #include "sal/types.h" #include "logformat.hxx" #if defined WNT #include <process.h> #define OSL_DETAIL_GETPID _getpid() #else #include <unistd.h> #define OSL_DETAIL_GETPID getpid() #endif #ifdef HAVE_SYSLOG_H #include <syslog.h> // sal/osl/unx/salinit.cxx::sal_detail_initialize updates this: bool sal_use_syslog; #endif #ifdef ANDROID #include <android/log.h> #endif // Avoid the use of other sal code in this file as much as possible, so that // this code can be called from other sal code without causing endless // recursion. namespace { bool equalStrings( char const * string1, std::size_t length1, char const * string2, std::size_t length2) { return length1 == length2 && std::memcmp(string1, string2, length1) == 0; } char const * toString(sal_detail_LogLevel level) { switch (level) { default: assert(false); // this cannot happen // fall through case SAL_DETAIL_LOG_LEVEL_INFO: return "info"; case SAL_DETAIL_LOG_LEVEL_WARN: return "warn"; case SAL_DETAIL_LOG_LEVEL_DEBUG: return "debug"; } } // getenv is not thread safe, so minimize use of result; except on Android and // iOS, see 60628799633ffde502cb105b98d3f254f93115aa "Notice if SAL_LOG is // changed while the process is running": #if defined ANDROID || defined IOS char const * getEnvironmentVariable() { return std::getenv("SAL_LOG"); } #else char const * getEnvironmentVariable_() { char const * p1 = std::getenv("SAL_LOG"); if (p1 == 0) { return 0; } char const * p2 = strdup(p1); // leaked if (p2 == 0) { std::abort(); // cannot do much here } return p2; } char const * getEnvironmentVariable() { static char const * env = getEnvironmentVariable_(); return env; } #endif #ifdef HAVE_SYSLOG_H int toSyslogPriority(sal_detail_LogLevel level) { switch (level) { default: assert(false); // this cannot happen // fall through case SAL_DETAIL_LOG_LEVEL_INFO: return LOG_INFO; case SAL_DETAIL_LOG_LEVEL_WARN: return LOG_WARNING; case SAL_DETAIL_LOG_LEVEL_DEBUG: return LOG_DEBUG; } } #endif bool report(sal_detail_LogLevel level, char const * area) { if (level == SAL_DETAIL_LOG_LEVEL_DEBUG) return true; assert(area != 0); char const * env = getEnvironmentVariable(); if (env == 0) { env = "+WARN"; } std::size_t areaLen = std::strlen(area); enum Sense { POSITIVE = 0, NEGATIVE = 1 }; std::size_t senseLen[2] = { 0, 1 }; // initial senseLen[POSITIVE] < senseLen[NEGATIVE], so that if there are // no matching switches at all, the result will be negative (and // initializing with 1 is safe as the length of a valid switch, even // without the "+"/"-" prefix, will always be > 1) for (char const * p = env;;) { Sense sense; switch (*p++) { case '\0': return senseLen[POSITIVE] >= senseLen[NEGATIVE]; // if a specific item is both postiive and negative // (senseLen[POSITIVE] == senseLen[NEGATIVE]), default to // positive case '+': sense = POSITIVE; break; case '-': sense = NEGATIVE; break; default: return true; // upon an illegal SAL_LOG value, enable everything } char const * p1 = p; while (*p1 != '.' && *p1 != '+' && *p1 != '-' && *p1 != '\0') { ++p1; } bool match; if (equalStrings(p, p1 - p, RTL_CONSTASCII_STRINGPARAM("INFO"))) { match = level == SAL_DETAIL_LOG_LEVEL_INFO; } else if (equalStrings(p, p1 - p, RTL_CONSTASCII_STRINGPARAM("WARN"))) { match = level == SAL_DETAIL_LOG_LEVEL_WARN; } else { return true; // upon an illegal SAL_LOG value, everything is considered // positive } char const * p2 = p1; while (*p2 != '+' && *p2 != '-' && *p2 != '\0') { ++p2; } if (match) { if (*p1 == '.') { ++p1; std::size_t n = p2 - p1; if ((n == areaLen && equalStrings(p1, n, area, areaLen)) || (n < areaLen && area[n] == '.' && equalStrings(p1, n, area, n))) { senseLen[sense] = p2 - p; } } else { senseLen[sense] = p1 - p; } } p = p2; } } void log( sal_detail_LogLevel level, char const * area, char const * where, char const * message) { std::ostringstream s; #ifndef ANDROID #ifdef HAVE_SYSLOG_H if (!sal_use_syslog) #endif s << toString(level) << ':'; #endif if (level == SAL_DETAIL_LOG_LEVEL_DEBUG) { s << /*no area or where */ ' ' << message << '\n'; } else { #ifdef ANDROID // The area will be used as the "tag", and log info already contgains the pid on Android #else s << area << ':' << OSL_DETAIL_GETPID << ':'; #endif s << osl::Thread::getCurrentIdentifier() << ':'; if (strncmp(where, SRCDIR, sizeof(SRCDIR)-1) == 0) s << where+sizeof(SRCDIR); else s << where; s << message << '\n'; } #ifdef ANDROID int android_log_level; switch (level) { case SAL_DETAIL_LOG_LEVEL_INFO: android_log_level = ANDROID_LOG_INFO; break; case SAL_DETAIL_LOG_LEVEL_WARN: android_log_level = ANDROID_LOG_WARN; break; case SAL_DETAIL_LOG_LEVEL_DEBUG: android_log_level = ANDROID_LOG_DEBUG; break; default: android_log_level = ANDROID_LOG_INFO; break; } if (area == NULL) area = "LibreOffice"; __android_log_print(android_log_level, area, "%s", s.str().c_str()); #else #ifdef HAVE_SYSLOG_H if (sal_use_syslog) syslog(toSyslogPriority(level), "%s", s.str().c_str()); else #endif std::fputs(s.str().c_str(), stderr); #endif } } void sal_detail_log( sal_detail_LogLevel level, char const * area, char const * where, char const * message) { if (report(level, area)) { log(level, area, where, message); } } void sal_detail_logFormat( sal_detail_LogLevel level, char const * area, char const * where, char const * format, ...) { if (report(level, area)) { std::va_list args; va_start(args, format); osl::detail::logFormat(level, area, where, format, args); va_end(args); } } void osl::detail::logFormat( sal_detail_LogLevel level, char const * area, char const * where, char const * format, std::va_list arguments) { char buf[1024]; int const len = sizeof buf - RTL_CONSTASCII_LENGTH("..."); int n = vsnprintf(buf, len, format, arguments); if (n < 0) { std::strcpy(buf, "???"); } else if (n >= len) { std::strcpy(buf + len - 1, "..."); } log(level, area, where, buf); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "Commander.h" #include <iostream> #include <string> using namespace std; Commander::Commander(CmdContext *v_context) : context(v_context) { if (this->context == NULL) throw CmdException("Uninitialized commander context!"); addCommand("q", new QuitCommand()); } void Commander::clearCommands() { std::map<std::string, Command*>::iterator itr; for (itr = cmds.begin(); itr != cmds.end(); itr++) { Command* cmd = itr->second; delete cmd; } this->cmds.clear(); } void Commander::printHelp() { std::cout << "Avaliable commands: " << cmds.size() << endl; std::map<std::string, Command*>::iterator itr; for (itr = cmds.begin(); itr != cmds.end(); itr++) { Command *cmd = itr->second; if (cmd == NULL) continue; std::cout << itr->first << " \t- " << cmd->getDescription() << endl; } } Command* Commander::getCommand(std::string line) { std::string name = line; //TODO: split the line... if (cmds.find(name) == cmds.end() ) { std::cerr << "No such command" << endl; return NULL; } Command *cmd = this->cmds[name]; return cmd; } bool Commander::addCommand(std::string name, Command *cmd, bool overwrite) { if ( cmds.find(name) != cmds.end() ) { if (!overwrite) return false; // already exist delete this->cmds[name]; this->cmds[name] = NULL; } this->cmds[name] = cmd; return true; } void Commander::parseCommands() { const std::string PROMPT = "$ "; Command *cmd = NULL; while (true) { if (this->context == NULL) throw CmdException("Uninitialized commander context!"); if (this->context->isEndProcessing()) break; std::cout << PROMPT; std::string line; std::cin >> line; Command *cmd = getCommand(line); if (cmd == NULL) { this->printHelp(); continue; } try { CmdParams *params = cmd->fetchParams(line); cmd->execute(params, this->context); } catch (CustomException e) { std::cerr << "ERROR: " << e.what() << endl; } } } <commit_msg>Fix typo<commit_after>#include "Commander.h" #include <iostream> #include <string> using namespace std; Commander::Commander(CmdContext *v_context) : context(v_context) { if (this->context == NULL) throw CmdException("Uninitialized commander context!"); addCommand("q", new QuitCommand()); } void Commander::clearCommands() { std::map<std::string, Command*>::iterator itr; for (itr = cmds.begin(); itr != cmds.end(); itr++) { Command* cmd = itr->second; delete cmd; } this->cmds.clear(); } void Commander::printHelp() { std::cout << "Available commands: " << cmds.size() << endl; std::map<std::string, Command*>::iterator itr; for (itr = cmds.begin(); itr != cmds.end(); itr++) { Command *cmd = itr->second; if (cmd == NULL) continue; std::cout << itr->first << " \t- " << cmd->getDescription() << endl; } } Command* Commander::getCommand(std::string line) { std::string name = line; //TODO: split the line... if (cmds.find(name) == cmds.end() ) { std::cerr << "No such command" << endl; return NULL; } Command *cmd = this->cmds[name]; return cmd; } bool Commander::addCommand(std::string name, Command *cmd, bool overwrite) { if ( cmds.find(name) != cmds.end() ) { if (!overwrite) return false; // already exist delete this->cmds[name]; this->cmds[name] = NULL; } this->cmds[name] = cmd; return true; } void Commander::parseCommands() { const std::string PROMPT = "$ "; Command *cmd = NULL; while (true) { if (this->context == NULL) throw CmdException("Uninitialized commander context!"); if (this->context->isEndProcessing()) break; std::cout << PROMPT; std::string line; std::cin >> line; Command *cmd = getCommand(line); if (cmd == NULL) { this->printHelp(); continue; } try { CmdParams *params = cmd->fetchParams(line); cmd->execute(params, this->context); } catch (CustomException e) { std::cerr << "ERROR: " << e.what() << endl; } } } <|endoftext|>
<commit_before>// converts scf names into mmap file // #include "lvvlib/mmap.h" // LIBC #include <fcntl.h> #include <time.h> // THRIFT #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/protocol/TDenseProtocol.h> #include <thrift/protocol/TJSONProtocol.h> #include <thrift/transport/TTransportUtils.h> #include <thrift/transport/TFDTransport.h> #include <thrift/transport/TFileTransport.h> namespace atp = apache::thrift::protocol; namespace att = apache::thrift::transport; // THRIFT -- FILTERNAMES #include "filternames_types.h" #include "filternames_constants.h" namespace fn = filternames; // STD #include <iostream> using std::cerr; using std::cout; using std::endl; #include <algorithm> using std::copy; #include <iterator> using std::back_inserter; #include <unordered_map> using std::unordered_map; #include <set> using std::set; #include <string> using std::string; #include <vector> using std::vector; #include <fstream> // BOOST #include <boost/program_options.hpp> namespace po = boost::program_options; // LVVLIB (http://github.com/lvv/lvvlib) //#ifdef LVV //#include <ro/ro.h> //#include <scc/simple.h> //#endif #include "lvvlib/token.h" int main(int argc, char **argv) { /////////////////////////////////////////////////////////////////////////////// OPTIONS // options string filtername_path; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "help message") ("filternames,f", po::value<string>(&filtername_path), "filternames file") ; // Parse command line options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } ////////////////////////////////////////////////////////////// THRIFT READS FILTERNAMES int scf_fh = open(filtername_path.c_str(), O_RDONLY); if(scf_fh==-1) { cerr << "error: cann't open scf file -- '" << filtername_path << "'\n"; exit(1); } boost::shared_ptr<att::TFDTransport> innerTransportScf(new att::TFDTransport(scf_fh)); boost::shared_ptr<att::TBufferedTransport> transportScf(new att::TBufferedTransport(innerTransportScf)); boost::shared_ptr<atp::TBinaryProtocol> protocolScf(new atp::TBinaryProtocol(transportScf)); transportScf->open(); fn::FilterNames filter_names; filter_names.read(protocolScf.get()); unordered_map<string, set<string>> target_text_map; #ifdef LVV // a hack to release some memory filter_names.target_id_to_names = std::map<std::string, std::vector<std::string>>(); #endif ////////////////////////////////////////////////////////////////////////////////// FILTER AND ADD TO NAMES vector<char> names_data; vector<char> name; vector<size_t> names_begin{0}; // names_begin[0] starts at pos 0 size_t name_min=9999999999; size_t name_max=0; size_t good_names = 0; set<vector<char>> uniq_set; long total_tokens = 0; // for all names in filter_names for(auto& pr : filter_names.name_to_target_ids) { auto s = pr.first.data(); size_t sz = pr.first.size(); #ifdef DISPLAY_NAMES cout << "\nscf name: \t(" << string(s,s+sz) << ")\n"; #endif // split into tokens pos_t tb, te = s; pos_t e = s + sz; name.clear(); long tokens = 0; while ((tb=get_tb(te,e)) != e) { te=get_te(tb,e); if (!name.empty()) name.push_back(token_separator); copy (tb, te, back_inserter(name)); ++tokens; } // good / bad name constexpr long max_name_length = 1000; constexpr long min_name_length = 3; constexpr long min_name_tokens = 1; if ( ( min_name_length <= name.size() && name.size() <= max_name_length ) && ( min_name_tokens <= tokens ) && ( uniq_set.find(name) == uniq_set.end() ) ) { ++good_names; } else { continue; } uniq_set.insert(name); #ifdef DISPLAY_NAMES cout << "added name: \t(" << string(name.begin(), name.end()) << ")\n"; #endif // statistics name_min = std::min(name_min, name.size()); name_max = std::max(name_max, name.size()); total_tokens += tokens; // append name to names_data copy (name.begin(), name.end(), back_inserter(names_data)); names_begin.push_back(names_data.size()); } transportScf->close(); cerr << "NAMES: " << filter_names.name_to_target_ids.size() << ";\n\t good: " << good_names << ";\n\t min length: " << name_min << ";\n\t max length: " << name_max << ";\n\t avg length: " << double(names_data.size())/(names_begin.size()-1) << ";\n\t avg tokens: " << double(total_tokens)/(names_begin.size()-1) << ";\n\t total names length: " << names_data.size() << endl; ///////////////////////////////////////////////////////////////////////////////// WRITE MMAP cerr << "writing names memory map file ... "; lvv::mmap_write<char> ("data/names_data.mmap", &names_data[0], names_data.size()); lvv::mmap_write<size_t>("data/names_begin.mmap", &names_begin[0], names_begin.size()); cerr << "done\n"; } <commit_msg>-- added comments<commit_after>// converts filternames.scf names into mmap file // LIBC #include <fcntl.h> #include <time.h> // THRIFT #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/protocol/TDenseProtocol.h> #include <thrift/protocol/TJSONProtocol.h> #include <thrift/transport/TTransportUtils.h> #include <thrift/transport/TFDTransport.h> #include <thrift/transport/TFileTransport.h> namespace atp = apache::thrift::protocol; namespace att = apache::thrift::transport; // THRIFT -- FILTERNAMES #include "filternames_types.h" #include "filternames_constants.h" namespace fn = filternames; // STD #include <iostream> using std::cerr; using std::cout; using std::endl; #include <algorithm> using std::copy; #include <iterator> using std::back_inserter; #include <unordered_map> using std::unordered_map; #include <set> using std::set; #include <string> using std::string; #include <vector> using std::vector; #include <fstream> // BOOST #include <boost/program_options.hpp> namespace po = boost::program_options; // LVVLIB (http://github.com/lvv/lvvlib) //#ifdef LVV //#include <ro/ro.h> //#include <scc/simple.h> //#endif #include "lvvlib/token.h" #include "lvvlib/mmap.h" int main(int argc, char **argv) { /////////////////////////////////////////////////////////////////////////////// OPTIONS string filtername_path; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "help message") ("filternames,f", po::value<string>(&filtername_path), "filternames file") ; // Parse command line options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } ////////////////////////////////////////////////////////////// THRIFT READS FILTERNAMES int scf_fh = open(filtername_path.c_str(), O_RDONLY); if(scf_fh==-1) { cerr << "error: cann't open scf file -- '" << filtername_path << "'\n"; exit(1); } boost::shared_ptr<att::TFDTransport> innerTransportScf(new att::TFDTransport(scf_fh)); boost::shared_ptr<att::TBufferedTransport> transportScf(new att::TBufferedTransport(innerTransportScf)); boost::shared_ptr<atp::TBinaryProtocol> protocolScf(new atp::TBinaryProtocol(transportScf)); transportScf->open(); fn::FilterNames filter_names; filter_names.read(protocolScf.get()); unordered_map<string, set<string>> target_text_map; #ifdef LVV // a hack to release some memory filter_names.target_id_to_names = std::map<std::string, std::vector<std::string>>(); #endif ////////////////////////////////////////////////////////////////////////////////// FILTER AND ADD TO NAMES vector<char> names_data; // cancantenated content of names vector<char> name; // temp name vector<size_t> names_begin{0}; // array of indexes in names_data which point to begining of a names. // a name i is from names_begin[i] to names_begin[i+1] size_t name_min=9999999999; size_t name_max=0; size_t good_names = 0; set<vector<char>> uniq_set; // used in check for uniqness long total_tokens = 0; // for all names in filter_names for(auto& pr : filter_names.name_to_target_ids) { auto s = pr.first.data(); // name size_t sz = pr.first.size(); // is size #ifdef DISPLAY_NAMES cout << "\nscf name: \t(" << string(s,s+sz) << ")\n"; #endif // split into tokens pos_t tb, te = s; // token begin, end pos_t e = s + sz; name.clear(); long tokens = 0; while ((tb=get_tb(te,e)) != e) { te=get_te(tb,e); if (!name.empty()) name.push_back(token_separator); copy (tb, te, back_inserter(name)); ++tokens; } // filter out bad names constexpr long max_name_length = 1000; constexpr long min_name_length = 3; constexpr long min_name_tokens = 1; if ( ( min_name_length <= name.size() && name.size() <= max_name_length ) && ( min_name_tokens <= tokens ) && ( uniq_set.find(name) == uniq_set.end() ) ) { ++good_names; } else { continue; } uniq_set.insert(name); #ifdef DISPLAY_NAMES cout << "added name: \t(" << string(name.begin(), name.end()) << ")\n"; #endif // statistics name_min = std::min(name_min, name.size()); name_max = std::max(name_max, name.size()); total_tokens += tokens; // append name to names_data copy (name.begin(), name.end(), back_inserter(names_data)); names_begin.push_back(names_data.size()); } transportScf->close(); cerr << "NAMES: " << filter_names.name_to_target_ids.size() << ";\n\t good: " << good_names << ";\n\t min length: " << name_min << ";\n\t max length: " << name_max << ";\n\t avg length: " << double(names_data.size())/(names_begin.size()-1) << ";\n\t avg tokens: " << double(total_tokens)/(names_begin.size()-1) << ";\n\t total names length: " << names_data.size() << endl; ///////////////////////////////////////////////////////////////////////////////// WRITE MMAP cerr << "writing names memory map file ... "; lvv::mmap_write<char> ("data/names_data.mmap", &names_data[0], names_data.size()); lvv::mmap_write<size_t>("data/names_begin.mmap", &names_begin[0], names_begin.size()); cerr << "done\n"; } // vim: ts=8 sw=8 <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_CONFIG_HPP #define CPPA_CONFIG_HPP // uncomment this line or use // ./configure CXXFLAGS="-DCPPA_DISABLE_CONTEXT_SWITCHING" // if ucontext_t is not available on your platform //#define CPPA_DISABLE_CONTEXT_SWITCHING #if defined(__GNUC__) # define CPPA_GCC #endif #if defined(__APPLE__) # define CPPA_MACOS # ifndef _GLIBCXX_HAS_GTHREADS # define _GLIBCXX_HAS_GTHREADS # endif #elif defined(__GNUC__) && defined(__linux__) # define CPPA_LINUX #elif defined(WIN32) # define CPPA_WINDOWS #else # error Plattform and/or compiler not supportet #endif #if defined(__amd64__) || defined(__LP64__) # define CPPA_64BIT #endif #include <cstdio> #include <cstdlib> #ifdef CPPA_DEBUG #include <execinfo.h> #define CPPA_REQUIRE__(stmt, file, line) \ printf("%s:%u: requirement failed '%s'\n", file, line, stmt); \ { \ void *array[10]; \ size_t size = backtrace(array, 10); \ backtrace_symbols_fd(array, size, 2); \ } \ abort() #define CPPA_REQUIRE(stmt) \ if ((stmt) == false) { \ CPPA_REQUIRE__(#stmt, __FILE__, __LINE__); \ }((void) 0) #else // CPPA_DEBUG #define CPPA_REQUIRE(unused) ((void) 0) #endif // CPPA_DEBUG #define CPPA_CRITICAL__(error, file, line) { \ printf("%s:%u: critical error: '%s'\n", file, line, error); \ exit(7); \ } ((void) 0) #define CPPA_CRITICAL(error) CPPA_CRITICAL__(error, __FILE__, __LINE__) #endif // CPPA_CONFIG_HPP <commit_msg>removed obsolete macro<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_CONFIG_HPP #define CPPA_CONFIG_HPP // uncomment this line or use // ./configure CXXFLAGS="-DCPPA_DISABLE_CONTEXT_SWITCHING" // if ucontext_t is not available on your platform //#define CPPA_DISABLE_CONTEXT_SWITCHING #if defined(__GNUC__) # define CPPA_GCC #endif #if defined(__APPLE__) # define CPPA_MACOS # ifndef _GLIBCXX_HAS_GTHREADS # define _GLIBCXX_HAS_GTHREADS # endif #elif defined(__GNUC__) && defined(__linux__) # define CPPA_LINUX #elif defined(WIN32) # define CPPA_WINDOWS #else # error Plattform and/or compiler not supportet #endif #include <cstdio> #include <cstdlib> #ifdef CPPA_DEBUG #include <execinfo.h> #define CPPA_REQUIRE__(stmt, file, line) \ printf("%s:%u: requirement failed '%s'\n", file, line, stmt); \ { \ void *array[10]; \ size_t size = backtrace(array, 10); \ backtrace_symbols_fd(array, size, 2); \ } \ abort() #define CPPA_REQUIRE(stmt) \ if ((stmt) == false) { \ CPPA_REQUIRE__(#stmt, __FILE__, __LINE__); \ }((void) 0) #else // CPPA_DEBUG #define CPPA_REQUIRE(unused) ((void) 0) #endif // CPPA_DEBUG #define CPPA_CRITICAL__(error, file, line) { \ printf("%s:%u: critical error: '%s'\n", file, line, error); \ exit(7); \ } ((void) 0) #define CPPA_CRITICAL(error) CPPA_CRITICAL__(error, __FILE__, __LINE__) #endif // CPPA_CONFIG_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2003 The Regents of The University of Michigan * 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 copyright holders 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. */ #include <string> #include <sstream> #include <iostream> #include "cpu/base_cpu.hh" #include "base/cprintf.hh" #include "cpu/exec_context.hh" #include "base/misc.hh" #include "sim/param.hh" #include "sim/sim_events.hh" using namespace std; vector<BaseCPU *> BaseCPU::cpuList; // This variable reflects the max number of threads in any CPU. Be // careful to only use it once all the CPUs that you care about have // been initialized int maxThreadsPerCPU = 1; #ifdef FULL_SYSTEM BaseCPU::BaseCPU(const string &_name, int _number_of_threads, Counter max_insts_any_thread, Counter max_insts_all_threads, Counter max_loads_any_thread, Counter max_loads_all_threads, System *_system, Tick freq) : SimObject(_name), frequency(freq), number_of_threads(_number_of_threads), system(_system) #else BaseCPU::BaseCPU(const string &_name, int _number_of_threads, Counter max_insts_any_thread, Counter max_insts_all_threads, Counter max_loads_any_thread, Counter max_loads_all_threads) : SimObject(_name), number_of_threads(_number_of_threads) #endif { // add self to global list of CPUs cpuList.push_back(this); if (number_of_threads > maxThreadsPerCPU) maxThreadsPerCPU = number_of_threads; // allocate per-thread instruction-based event queues comInstEventQueue = new (EventQueue *)[number_of_threads]; for (int i = 0; i < number_of_threads; ++i) comInstEventQueue[i] = new EventQueue("instruction-based event queue"); // // set up instruction-count-based termination events, if any // if (max_insts_any_thread != 0) for (int i = 0; i < number_of_threads; ++i) new SimExitEvent(comInstEventQueue[i], max_insts_any_thread, "a thread reached the max instruction count"); if (max_insts_all_threads != 0) { // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = number_of_threads; for (int i = 0; i < number_of_threads; ++i) new CountedExitEvent(comInstEventQueue[i], "all threads reached the max instruction count", max_insts_all_threads, *counter); } // allocate per-thread load-based event queues comLoadEventQueue = new (EventQueue *)[number_of_threads]; for (int i = 0; i < number_of_threads; ++i) comLoadEventQueue[i] = new EventQueue("load-based event queue"); // // set up instruction-count-based termination events, if any // if (max_loads_any_thread != 0) for (int i = 0; i < number_of_threads; ++i) new SimExitEvent(comLoadEventQueue[i], max_loads_any_thread, "a thread reached the max load count"); if (max_loads_all_threads != 0) { // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = number_of_threads; for (int i = 0; i < number_of_threads; ++i) new CountedExitEvent(comLoadEventQueue[i], "all threads reached the max load count", max_loads_all_threads, *counter); } #ifdef FULL_SYSTEM memset(interrupts, 0, sizeof(interrupts)); intstatus = 0; #endif } void BaseCPU::regStats() { int size = execContexts.size(); if (size > 1) { for (int i = 0; i < size; ++i) { stringstream namestr; ccprintf(namestr, "%s.ctx%d", name(), i); execContexts[i]->regStats(namestr.str()); } } else if (size == 1) execContexts[0]->regStats(name()); } void BaseCPU::registerExecContexts() { for (int i = 0; i < execContexts.size(); ++i) { ExecContext *xc = execContexts[i]; int cpu_id; #ifdef FULL_SYSTEM cpu_id = system->registerExecContext(xc); #else cpu_id = xc->process->registerExecContext(xc); #endif xc->cpu_id = cpu_id; } } void BaseCPU::switchOut() { // default: do nothing } void BaseCPU::takeOverFrom(BaseCPU *oldCPU) { assert(execContexts.size() == oldCPU->execContexts.size()); for (int i = 0; i < execContexts.size(); ++i) { ExecContext *newXC = execContexts[i]; ExecContext *oldXC = oldCPU->execContexts[i]; newXC->takeOverFrom(oldXC); assert(newXC->cpu_id == oldXC->cpu_id); #ifdef FULL_SYSTEM system->replaceExecContext(newXC->cpu_id, newXC); #else assert(newXC->process == oldXC->process); newXC->process->replaceExecContext(newXC->cpu_id, newXC); #endif } for (int i = 0; i < NumInterruptLevels; ++i) interrupts[i] = oldCPU->interrupts[i]; intstatus = oldCPU->intstatus; } #ifdef FULL_SYSTEM void BaseCPU::post_interrupt(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d posted\n", int_num, index); if (int_num < 0 || int_num >= NumInterruptLevels) panic("int_num out of bounds\n"); if (index < 0 || index >= sizeof(uint8_t) * 8) panic("int_num out of bounds\n"); AlphaISA::check_interrupts = 1; interrupts[int_num] |= 1 << index; intstatus |= (ULL(1) << int_num); } void BaseCPU::clear_interrupt(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d cleared\n", int_num, index); if (int_num < 0 || int_num >= NumInterruptLevels) panic("int_num out of bounds\n"); if (index < 0 || index >= sizeof(uint8_t) * 8) panic("int_num out of bounds\n"); interrupts[int_num] &= ~(1 << index); if (interrupts[int_num] == 0) intstatus &= ~(ULL(1) << int_num); } void BaseCPU::clear_interrupts() { DPRINTF(Interrupt, "Interrupts all cleared\n"); memset(interrupts, 0, sizeof(interrupts)); intstatus = 0; } #endif // FULL_SYSTEM // // This declaration is not needed now that SamplingCPU provides a // BaseCPUBuilder object. // #if 0 DEFINE_SIM_OBJECT_CLASS_NAME("BaseCPU", BaseCPU) #endif <commit_msg>Fix the swichover code. It's only for FULL_SYSTEM<commit_after>/* * Copyright (c) 2003 The Regents of The University of Michigan * 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 copyright holders 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. */ #include <string> #include <sstream> #include <iostream> #include "cpu/base_cpu.hh" #include "base/cprintf.hh" #include "cpu/exec_context.hh" #include "base/misc.hh" #include "sim/param.hh" #include "sim/sim_events.hh" using namespace std; vector<BaseCPU *> BaseCPU::cpuList; // This variable reflects the max number of threads in any CPU. Be // careful to only use it once all the CPUs that you care about have // been initialized int maxThreadsPerCPU = 1; #ifdef FULL_SYSTEM BaseCPU::BaseCPU(const string &_name, int _number_of_threads, Counter max_insts_any_thread, Counter max_insts_all_threads, Counter max_loads_any_thread, Counter max_loads_all_threads, System *_system, Tick freq) : SimObject(_name), frequency(freq), number_of_threads(_number_of_threads), system(_system) #else BaseCPU::BaseCPU(const string &_name, int _number_of_threads, Counter max_insts_any_thread, Counter max_insts_all_threads, Counter max_loads_any_thread, Counter max_loads_all_threads) : SimObject(_name), number_of_threads(_number_of_threads) #endif { // add self to global list of CPUs cpuList.push_back(this); if (number_of_threads > maxThreadsPerCPU) maxThreadsPerCPU = number_of_threads; // allocate per-thread instruction-based event queues comInstEventQueue = new (EventQueue *)[number_of_threads]; for (int i = 0; i < number_of_threads; ++i) comInstEventQueue[i] = new EventQueue("instruction-based event queue"); // // set up instruction-count-based termination events, if any // if (max_insts_any_thread != 0) for (int i = 0; i < number_of_threads; ++i) new SimExitEvent(comInstEventQueue[i], max_insts_any_thread, "a thread reached the max instruction count"); if (max_insts_all_threads != 0) { // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = number_of_threads; for (int i = 0; i < number_of_threads; ++i) new CountedExitEvent(comInstEventQueue[i], "all threads reached the max instruction count", max_insts_all_threads, *counter); } // allocate per-thread load-based event queues comLoadEventQueue = new (EventQueue *)[number_of_threads]; for (int i = 0; i < number_of_threads; ++i) comLoadEventQueue[i] = new EventQueue("load-based event queue"); // // set up instruction-count-based termination events, if any // if (max_loads_any_thread != 0) for (int i = 0; i < number_of_threads; ++i) new SimExitEvent(comLoadEventQueue[i], max_loads_any_thread, "a thread reached the max load count"); if (max_loads_all_threads != 0) { // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = number_of_threads; for (int i = 0; i < number_of_threads; ++i) new CountedExitEvent(comLoadEventQueue[i], "all threads reached the max load count", max_loads_all_threads, *counter); } #ifdef FULL_SYSTEM memset(interrupts, 0, sizeof(interrupts)); intstatus = 0; #endif } void BaseCPU::regStats() { int size = execContexts.size(); if (size > 1) { for (int i = 0; i < size; ++i) { stringstream namestr; ccprintf(namestr, "%s.ctx%d", name(), i); execContexts[i]->regStats(namestr.str()); } } else if (size == 1) execContexts[0]->regStats(name()); } void BaseCPU::registerExecContexts() { for (int i = 0; i < execContexts.size(); ++i) { ExecContext *xc = execContexts[i]; int cpu_id; #ifdef FULL_SYSTEM cpu_id = system->registerExecContext(xc); #else cpu_id = xc->process->registerExecContext(xc); #endif xc->cpu_id = cpu_id; } } void BaseCPU::switchOut() { // default: do nothing } void BaseCPU::takeOverFrom(BaseCPU *oldCPU) { assert(execContexts.size() == oldCPU->execContexts.size()); for (int i = 0; i < execContexts.size(); ++i) { ExecContext *newXC = execContexts[i]; ExecContext *oldXC = oldCPU->execContexts[i]; newXC->takeOverFrom(oldXC); assert(newXC->cpu_id == oldXC->cpu_id); #ifdef FULL_SYSTEM system->replaceExecContext(newXC->cpu_id, newXC); #else assert(newXC->process == oldXC->process); newXC->process->replaceExecContext(newXC->cpu_id, newXC); #endif } #ifdef FULL_SYSTEM for (int i = 0; i < NumInterruptLevels; ++i) interrupts[i] = oldCPU->interrupts[i]; intstatus = oldCPU->intstatus; #endif } #ifdef FULL_SYSTEM void BaseCPU::post_interrupt(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d posted\n", int_num, index); if (int_num < 0 || int_num >= NumInterruptLevels) panic("int_num out of bounds\n"); if (index < 0 || index >= sizeof(uint8_t) * 8) panic("int_num out of bounds\n"); AlphaISA::check_interrupts = 1; interrupts[int_num] |= 1 << index; intstatus |= (ULL(1) << int_num); } void BaseCPU::clear_interrupt(int int_num, int index) { DPRINTF(Interrupt, "Interrupt %d:%d cleared\n", int_num, index); if (int_num < 0 || int_num >= NumInterruptLevels) panic("int_num out of bounds\n"); if (index < 0 || index >= sizeof(uint8_t) * 8) panic("int_num out of bounds\n"); interrupts[int_num] &= ~(1 << index); if (interrupts[int_num] == 0) intstatus &= ~(ULL(1) << int_num); } void BaseCPU::clear_interrupts() { DPRINTF(Interrupt, "Interrupts all cleared\n"); memset(interrupts, 0, sizeof(interrupts)); intstatus = 0; } #endif // FULL_SYSTEM // // This declaration is not needed now that SamplingCPU provides a // BaseCPUBuilder object. // #if 0 DEFINE_SIM_OBJECT_CLASS_NAME("BaseCPU", BaseCPU) #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <set> #include <boost/test/unit_test.hpp> #include <seastar/core/thread.hh> #include "sstables/sstables.hh" #include "compress.hh" #include "schema_builder.hh" #include "tests/test-utils.hh" using namespace sstables; class sstable_assertions final { shared_sstable _sst; public: sstable_assertions(schema_ptr schema, const sstring& path, int generation = 1) : _sst(make_sstable(std::move(schema), path, generation, sstable_version_types::mc, sstable_format_types::big)) { } void read_toc() { _sst->read_toc().get(); } void read_summary() { _sst->read_summary(default_priority_class()).get(); } void assert_toc(const std::set<component_type>& expected_components) { for (auto& expected : expected_components) { if(_sst->_recognized_components.count(expected) == 0) { BOOST_FAIL(sprint("Expected component of TOC missing: %s\n ... in: %s", expected, std::set<component_type>( cbegin(_sst->_recognized_components), cend(_sst->_recognized_components)))); } } for (auto& present : _sst->_recognized_components) { if (expected_components.count(present) == 0) { BOOST_FAIL(sprint("Unexpected component of TOC: %s\n ... when expecting: %s", present, expected_components)); } } } }; // Following tests run on files in tests/sstables/3.x/uncompressed/simple // They were created using following CQL statements: // // CREATE KEYSPACE test_ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; // // CREATE TABLE test_ks.test_table ( pk INT, ck INT, val INT, PRIMARY KEY(pk, ck)) // WITH compression = { 'enabled' : false }; // // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(1, 101, 1001); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(2, 102, 1002); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(3, 103, 1003); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(4, 104, 1004); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(5, 105, 1005); static thread_local const sstring UNCOMPRESSED_SIMPLE_PATH = "tests/sstables/3.x/uncompressed/simple"; static thread_local const schema_ptr UNCOMPRESSED_SIMPLE_SCHEMA = schema_builder("test_ks", "test_table") .with_column("pk", int32_type, column_kind::partition_key) .with_column("ck", int32_type, column_kind::clustering_key) .with_column("val", int32_type) .build(); SEASTAR_TEST_CASE(test_uncompressed_simple_read_toc) { return seastar::async([] { sstable_assertions sst(UNCOMPRESSED_SIMPLE_SCHEMA, UNCOMPRESSED_SIMPLE_PATH); sst.read_toc(); using ct = component_type; sst.assert_toc({ct::Index, ct::Data, ct::TOC, ct::Summary, ct::Digest, ct::CRC, ct::Filter, ct::Statistics}); }); } SEASTAR_TEST_CASE(test_uncompressed_simple_read_summary) { return seastar::async([] { sstable_assertions sst(UNCOMPRESSED_SIMPLE_SCHEMA, UNCOMPRESSED_SIMPLE_PATH); sst.read_toc(); sst.read_summary(); }); } <commit_msg>Add test for reading filter<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <set> #include <boost/test/unit_test.hpp> #include <seastar/core/thread.hh> #include "sstables/sstables.hh" #include "compress.hh" #include "schema_builder.hh" #include "tests/test-utils.hh" using namespace sstables; class sstable_assertions final { shared_sstable _sst; public: sstable_assertions(schema_ptr schema, const sstring& path, int generation = 1) : _sst(make_sstable(std::move(schema), path, generation, sstable_version_types::mc, sstable_format_types::big)) { } void read_toc() { _sst->read_toc().get(); } void read_summary() { _sst->read_summary(default_priority_class()).get(); } void read_filter() { _sst->read_filter(default_priority_class()).get(); } void assert_toc(const std::set<component_type>& expected_components) { for (auto& expected : expected_components) { if(_sst->_recognized_components.count(expected) == 0) { BOOST_FAIL(sprint("Expected component of TOC missing: %s\n ... in: %s", expected, std::set<component_type>( cbegin(_sst->_recognized_components), cend(_sst->_recognized_components)))); } } for (auto& present : _sst->_recognized_components) { if (expected_components.count(present) == 0) { BOOST_FAIL(sprint("Unexpected component of TOC: %s\n ... when expecting: %s", present, expected_components)); } } } }; // Following tests run on files in tests/sstables/3.x/uncompressed/simple // They were created using following CQL statements: // // CREATE KEYSPACE test_ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; // // CREATE TABLE test_ks.test_table ( pk INT, ck INT, val INT, PRIMARY KEY(pk, ck)) // WITH compression = { 'enabled' : false }; // // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(1, 101, 1001); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(2, 102, 1002); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(3, 103, 1003); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(4, 104, 1004); // INSERT INTO test_ks.test_table(pk, ck, val) VALUES(5, 105, 1005); static thread_local const sstring UNCOMPRESSED_SIMPLE_PATH = "tests/sstables/3.x/uncompressed/simple"; static thread_local const schema_ptr UNCOMPRESSED_SIMPLE_SCHEMA = schema_builder("test_ks", "test_table") .with_column("pk", int32_type, column_kind::partition_key) .with_column("ck", int32_type, column_kind::clustering_key) .with_column("val", int32_type) .build(); SEASTAR_TEST_CASE(test_uncompressed_simple_read_toc) { return seastar::async([] { sstable_assertions sst(UNCOMPRESSED_SIMPLE_SCHEMA, UNCOMPRESSED_SIMPLE_PATH); sst.read_toc(); using ct = component_type; sst.assert_toc({ct::Index, ct::Data, ct::TOC, ct::Summary, ct::Digest, ct::CRC, ct::Filter, ct::Statistics}); }); } SEASTAR_TEST_CASE(test_uncompressed_simple_read_summary) { return seastar::async([] { sstable_assertions sst(UNCOMPRESSED_SIMPLE_SCHEMA, UNCOMPRESSED_SIMPLE_PATH); sst.read_toc(); sst.read_summary(); }); } SEASTAR_TEST_CASE(test_uncompressed_simple_read_filter) { return seastar::async([] { sstable_assertions sst(UNCOMPRESSED_SIMPLE_SCHEMA, UNCOMPRESSED_SIMPLE_PATH); sst.read_toc(); sst.read_filter(); }); } <|endoftext|>
<commit_before> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <Eigen/Dense> #include <Eigen/Sparse> #include <boost/random/normal_distribution.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/variate_generator.hpp> using namespace Eigen; using namespace std; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 30; unsigned num_p = 0; unsigned num_m = 0; const int alpha = 2; const int nsims = 2; const int burnin = 5; double mean_rating; SparseMatrixD M; MatrixXd sample_u; MatrixXd sample_m; VectorXd mu_u(num_feat); VectorXd mu_m(num_feat); MatrixXd Lambda_u(num_feat, num_feat); MatrixXd Lambda_m(num_feat, num_feat); // parameters of Inv-Whishart distribution (see paper for details) MatrixXd WI_u(num_feat, num_feat); const int b0_u = 2; const int df_u = num_feat; VectorXd mu0_u(num_feat); MatrixXd WI_m(num_feat, num_feat); const int b0_m = 2; const int df_m = num_feat; VectorXd mu0_m(num_feat); void loadChemo() { typedef Eigen::Triplet<double> T; std::vector<T> lst; lst.reserve(100000); FILE *f = fopen("../data/chembl_19_mf1/chembl-IC50-360targets.csv", "r"); assert(f); // skip header char buf[2048]; fscanf(f, "%s\n", buf); // data unsigned i, j; double v_ij; while (!feof(f)) { if (!fscanf(f, "%d,%d,%lg\n", &i, &j, &v_ij)) continue; num_p = std::max(num_p, i); num_m = std::max(num_m, j); lst.push_back(T(i,j,v_ij)); } num_p++; num_m++; fclose(f); M = SparseMatrix<double>(num_p, num_m); M.setFromTriplets(lst.begin(), lst.end()); } void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); sample_u = MatrixXd(num_p, num_feat); sample_u.setZero(); sample_m = MatrixXd(num_m, num_feat); sample_m.setZero(); } /* function pred(probe_vec, sample_m, sample_u, mean_rating) sum(sample_m[probe_vec[:,2],:].*sample_u[probe_vec[:,1],:],2) + mean_rating end */ double rand(double mean = 0.5, double sigma = 1) { boost::mt19937 gen; boost::random::normal_distribution<> dist(mean,sigma); return dist(gen); } VectorXd randn(int n, double mean = 0.5, double sigma = 1) { VectorXd ret(n); boost::mt19937 gen; boost::random::normal_distribution<> dist(mean,sigma); for(int i=0; i<n; ++i) ret(i) = dist(gen); return ret; } MatrixXd sample_movie(int mm, SparseMatrixD &mat, double mean_rating, MatrixXd sample_u, int alpha, MatrixXd mu_u, MatrixXd Lambda_u) { int i = 0; MatrixXd E(mat.col(mm).nonZeros(), num_feat); VectorXd rr(mat.col(mm).nonZeros()); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { //cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; E.row(i) = sample_u.row(it.row()); rr(i) = it.value() - mean_rating; } auto MM = E.transpose() * E; MatrixXd MMs = alpha * MM.array(); assert(MMs.cols() == num_feat && MMs.rows() == num_feat); auto covar = (Lambda_u + MMs).inverse(); auto MMrr = E.transpose() * rr; MMrr.array() *= alpha; auto U = Lambda_u * mu_u; auto mu = covar * (MMrr + U); auto chol = covar.llt().matrixL().transpose(); auto result = chol * randn(num_feat) + mu; return result.transpose(); } MatrixXd WishartUnit(MatrixXd sigma, int df) { auto m = sigma.cols(); MatrixXd c(m,m); c.setZero(); for ( int i = 0; i < m; i++ ) { boost::gamma_distribution<> chi(0.5*(df - i)); boost::mt19937 rng; boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> > gen(rng, chi); c(i,i) = sqrt(2.0 * chi(gen)); c.block(i,i+1,1,m-i) = randn(m-i); } return c.transpose() * c; } MatrixXd Wishart(MatrixXd sigma, int df) { MatrixXd r = sigma.llt().matrixU(); auto u = WishartUnit(sigma, df); return r.transpose() * u; } void run() { double err_avg = 0.0; double err = 0.0; SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { #if 0 // Sample from movie hyperparams mu_m, Lambda_m = rand( ConditionalNormalWishart(sample_m, vec(mu0_m), b0_m, WI_m, df_m) ) // Sample from user hyperparams mu_u, Lambda_u = rand( ConditionalNormalWishart(sample_u, vec(mu0_u), b0_u, WI_u, df_u) ) #endif #pragma omp parallel for for(int mm = 1; mm < num_m; ++mm) { sample_m.row(mm) = sample_movie(mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } for(int uu = 1; uu < num_p; ++uu) { sample_u.row(uu) = sample_movie(uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } #if 0 probe_rat = pred(probe_vec, sample_m, sample_u, mean_rating) if i > burnin probe_rat_all = (counter_prob*probe_rat_all + probe_rat)/(counter_prob+1) counter_prob = counter_prob + 1 else probe_rat_all = probe_rat counter_prob = 1 end err_avg = mean(ratings_test .== (probe_rat_all .< log10(200))) err = mean(ratings_test .== (probe_rat .< log10(200))) printf("Iteration %d:\t avg RMSE %6.4f RMSE %6.4f FU(%6.4f) FM(%6.4f)\n", i, err_avg, err, vecnorm(sample_u), vecnorm(sample_m)); #endif } } int main() { loadChemo(); init(); run(); return 0; } <commit_msg>bpmf: c++ updates<commit_after> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <Eigen/Dense> #include <Eigen/Sparse> #include <boost/random/normal_distribution.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/variate_generator.hpp> using namespace Eigen; using namespace std; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 30; unsigned num_p = 0; unsigned num_m = 0; const int alpha = 2; const int nsims = 2; const int burnin = 5; double mean_rating; SparseMatrixD M; MatrixXd sample_u; MatrixXd sample_m; VectorXd mu_u(num_feat); VectorXd mu_m(num_feat); MatrixXd Lambda_u(num_feat, num_feat); MatrixXd Lambda_m(num_feat, num_feat); // parameters of Inv-Whishart distribution (see paper for details) MatrixXd WI_u(num_feat, num_feat); const int b0_u = 2; const int df_u = num_feat; VectorXd mu0_u(num_feat); MatrixXd WI_m(num_feat, num_feat); const int b0_m = 2; const int df_m = num_feat; VectorXd mu0_m(num_feat); void loadChemo() { typedef Eigen::Triplet<double> T; std::vector<T> lst; lst.reserve(100000); FILE *f = fopen("../data/chembl_19_mf1/chembl-IC50-360targets.csv", "r"); assert(f); // skip header char buf[2048]; fscanf(f, "%s\n", buf); // data unsigned i, j; double v_ij; while (!feof(f)) { if (!fscanf(f, "%d,%d,%lg\n", &i, &j, &v_ij)) continue; num_p = std::max(num_p, i); num_m = std::max(num_m, j); lst.push_back(T(i,j,v_ij)); } num_p++; num_m++; fclose(f); M = SparseMatrix<double>(num_p, num_m); M.setFromTriplets(lst.begin(), lst.end()); } void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); sample_u = MatrixXd(num_p, num_feat); sample_u.setZero(); sample_m = MatrixXd(num_m, num_feat); sample_m.setZero(); } /* function pred(probe_vec, sample_m, sample_u, mean_rating) sum(sample_m[probe_vec[:,2],:].*sample_u[probe_vec[:,1],:],2) + mean_rating end */ double rand(double mean = 0.5, double sigma = 1) { boost::mt19937 gen; boost::random::normal_distribution<> dist(mean,sigma); return dist(gen); } VectorXd randn(int n, double mean = 0.5, double sigma = 1) { VectorXd ret(n); boost::mt19937 gen; boost::random::normal_distribution<> dist(mean,sigma); for(int i=0; i<n; ++i) ret(i) = dist(gen); return ret; } MatrixXd sample_movie(int mm, SparseMatrixD &mat, double mean_rating, MatrixXd sample_u, int alpha, MatrixXd mu_u, MatrixXd Lambda_u) { int i = 0; MatrixXd E(mat.col(mm).nonZeros(), num_feat); VectorXd rr(mat.col(mm).nonZeros()); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { //cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; E.row(i) = sample_u.row(it.row()); rr(i) = it.value() - mean_rating; } auto MM = E.transpose() * E; MatrixXd MMs = alpha * MM.array(); assert(MMs.cols() == num_feat && MMs.rows() == num_feat); auto covar = (Lambda_u + MMs).inverse(); auto MMrr = E.transpose() * rr; MMrr.array() *= alpha; auto U = Lambda_u * mu_u; auto mu = covar * (MMrr + U); auto chol = covar.llt().matrixL().transpose(); auto result = chol * randn(num_feat) + mu; return result.transpose(); } MatrixXd WishartUnit(MatrixXd sigma, int df) { auto m = sigma.cols(); MatrixXd c(m,m); c.setZero(); for ( int i = 0; i < m; i++ ) { boost::gamma_distribution<> chi(0.5*(df - i)); boost::mt19937 rng; boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> > gen(rng, chi); c(i,i) = sqrt(2.0 * chi(gen)); c.block(i,i+1,1,m-i) = randn(m-i); } return c.transpose() * c; } MatrixXd Wishart(MatrixXd sigma, int df) { MatrixXd r = sigma.llt().matrixU(); auto u = WishartUnit(sigma, df); return r.transpose() * u; } MatrixXd NormalWishart( WI_u = eye(num_feat); b0_u = 2; df_u = num_feat; mu0_u = zeros(num_feat,1); WI_u = eye(num_feat); b0_u = 2; df_u = num_feat; mu0_u = zeros(num_feat,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Sample from user hyperparams N = size(w1_P1_sample,1); x_bar = mean(w1_P1_sample)'; S_bar = cov(w1_P1_sample); WI_post = inv(inv(WI_u) + N/1*S_bar + ... N*b0_u*(mu0_u - x_bar)*(mu0_u - x_bar)'/(1*(b0_u+N))); WI_post = (WI_post + WI_post')/2; df_mpost = df_u+N; alpha_u = wishrnd(WI_post,df_mpost); mu_temp = (b0_u*mu0_u + N*x_bar)/(b0_u+N); lam = chol( inv((b0_u+N)*alpha_u) ); lam=lam'; mu_u = lam*randn(num_feat,1)+mu_temp; MatrixXd CondWishart(MatrixXd sigma, int df) { MatrixXd r = sigma.llt().matrixU(); auto u = WishartUnit(sigma, df); return r.transpose() * u; } void run() { double err_avg = 0.0; double err = 0.0; SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { #if 0 // Sample from movie hyperparams mu_m, Lambda_m = rand( ConditionalNormalWishart(sample_m, vec(mu0_m), b0_m, WI_m, df_m) ) // Sample from user hyperparams mu_u, Lambda_u = rand( ConditionalNormalWishart(sample_u, vec(mu0_u), b0_u, WI_u, df_u) ) #endif #pragma omp parallel for for(int mm = 1; mm < num_m; ++mm) { sample_m.row(mm) = sample_movie(mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } for(int uu = 1; uu < num_p; ++uu) { sample_u.row(uu) = sample_movie(uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } #if 0 probe_rat = pred(probe_vec, sample_m, sample_u, mean_rating) if i > burnin probe_rat_all = (counter_prob*probe_rat_all + probe_rat)/(counter_prob+1) counter_prob = counter_prob + 1 else probe_rat_all = probe_rat counter_prob = 1 end err_avg = mean(ratings_test .== (probe_rat_all .< log10(200))) err = mean(ratings_test .== (probe_rat .< log10(200))) printf("Iteration %d:\t avg RMSE %6.4f RMSE %6.4f FU(%6.4f) FM(%6.4f)\n", i, err_avg, err, vecnorm(sample_u), vecnorm(sample_m)); #endif } } int main() { loadChemo(); init(); run(); return 0; } <|endoftext|>