text
stringlengths
54
60.6k
<commit_before>#ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <gl/glew.h> #include <gl/gl.h> #endif #include "qglwidget.hpp" #include <cmath> #include <cstddef> #include <iostream> #include <memory> #include <GL/gl.h> #include <QApplication> #include <QBitmap> #include <QDesktopWidget> #include <QMoveEvent> #include <QGLShader> #define LOG_ENTER_FUNC() qDebug() << __FUNCTION__ namespace qtfullscreensystem { typedef QGLShaderProgram Shader; typedef std::shared_ptr<Shader> ShaderPtr; /** * * @param vert Path to vertex shader * @param frag Path to fragment shader */ ShaderPtr loadShader( QString vert, QString frag ) { qDebug() << "loadShader("<< vert << "|" << frag << ")"; ShaderPtr program = std::make_shared<Shader>(); if( !program->addShaderFromSourceFile(QGLShader::Vertex, vert) ) { qWarning() << "Failed to load vertex shader (" << vert << ")\n" << program->log(); return ShaderPtr(); } if( !program->addShaderFromSourceFile(QGLShader::Fragment, frag) ) { qWarning() << "Failed to load fragment shader (" << frag << ")\n" << program->log(); return ShaderPtr(); } if( !program->link() ) { qWarning() << "Failed to link shader (" << vert << "|" << frag << ")\n" << program->log(); return ShaderPtr(); } return program; } //---------------------------------------------------------------------------- GLWidget::GLWidget(int& argc, char *argv[]) { //-------------------------------- // Setup opengl and window //-------------------------------- if( !QGLFormat::hasOpenGL() ) qFatal("OpenGL not supported!"); if( !QGLFramebufferObject::hasOpenGLFramebufferObjects() ) qFatal("OpenGL framebufferobjects not supported!"); // fullscreen setGeometry( QApplication::desktop()->screenGeometry(this) ); // don't allow user to change the window size setFixedSize( size() ); // transparent, always on top window without any decoration setWindowFlags( Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::MSWindowsOwnDC //| Qt::X11BypassWindowManagerHint ); setWindowOpacity(0.5); setMask(QRegion(-1, -1, 1, 1)); if( !isValid() ) qFatal("Unable to create OpenGL context (not valid)"); qDebug ( "Created GLWidget with OpenGL %d.%d", format().majorVersion(), format().minorVersion() ); //-------------------------------- // Setup component system //-------------------------------- if( argc != 2 ) qFatal("Usage: %s <config>", argv[0]); assert(argc == 2 && argv && argv[1]); publishSlots(_core.getSlotCollector()); _core.startup(argv[1]); _core.attachComponent(&_config); _core.attachComponent(&_cost_analysis); //_core.attachComponent(&_routing); _core.attachComponent(&_renderer); _core.init(); _subscribe_links = _core.getSlotSubscriber().getSlot<LinksRouting::SlotType::Image>("/rendered-links"); _subscribe_costmap = _core.getSlotSubscriber().getSlot<LinksRouting::SlotType::Image>("/costmap"); } //---------------------------------------------------------------------------- GLWidget::~GLWidget() { } //---------------------------------------------------------------------------- void GLWidget::captureScreen() { LOG_ENTER_FUNC(); _screenshot = QPixmap::grabWindow(QApplication::desktop()->winId()); } //---------------------------------------------------------------------------- void GLWidget::publishSlots(LinksRouting::SlotCollector slot_collector) { _slot_desktop = slot_collector.create<LinksRouting::SlotType::Image>("/desktop"); _slot_desktop->_data->type = LinksRouting::SlotType::Image::OpenGLTexture; } ShaderPtr shader; //------------------------------------------------------------------------------ void GLWidget::initializeGL() { LOG_ENTER_FUNC(); #if WIN32 if(glewInit() != GLEW_OK) qFatal("Unable to init Glew"); #endif if( _fbo_desktop ) qDebug("FBO already initialized!"); _fbo_desktop.reset ( new QGLFramebufferObject ( size(), QGLFramebufferObject::Depth ) ); if( !_fbo_desktop->isValid() ) qFatal("Failed to create framebufferobject!"); _slot_desktop->_data->id = _fbo_desktop->texture(); _slot_desktop->_data->width = size().width(); _slot_desktop->_data->height = size().height(); shader = loadShader("simple.vert", "remove_links.frag"); if( !shader ) qFatal("Failed to load shader."); glClearColor(0, 0, 0, 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); _core.initGL(); } //---------------------------------------------------------------------------- void GLWidget::paintGL() { // X11: Window decorators add decoration after creating the window. So we // need to get the new position of the window before drawing... QPoint window_offset = mapToGlobal(QPoint()); LOG_ENTER_FUNC() << "window offset=" << window_offset; _core.process(); updateScreenShot(window_offset); // normal draw... glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_links->_data->id); glBegin( GL_QUADS ); glColor3f(1,1,1); glTexCoord2f(0,0); glVertex2f(-1,-1); glTexCoord2f(1,0); glVertex2f(1,-1); glTexCoord2f(1,1); glVertex2f(1,1); glTexCoord2f(0,1); glVertex2f(-1,1); glEnd(); glDisable(GL_TEXTURE_2D); static QImage links(size(), QImage::Format_RGB888); static QImage costmap(QSize(_subscribe_costmap->_data->width, _subscribe_costmap->_data->height), QImage::Format_RGB888); static QImage desktop(size(), QImage::Format_RGB888); glPushAttrib(GL_CLIENT_PIXEL_STORE_BIT); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, width(), height(), GL_RGB, GL_UNSIGNED_BYTE, links.bits()); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_costmap->_data->id); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, costmap.bits()); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _slot_desktop->_data->id); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, desktop.bits()); glDisable(GL_TEXTURE_2D); glPopAttrib(); //links.save("fbo.png"); QBitmap mask = QBitmap::fromImage( links.mirrored().createMaskFromColor( qRgb(0,0,0) ) ); //mask.save("mask.png"); setMask(mask); static int counter = 0; desktop.mirrored().save(QString("desktop%1.png").arg(counter)); costmap.mirrored().save(QString("costmap%1.png").arg(counter)); links.mirrored().save(QString("links%1.png").arg(counter)); ++counter; // TODO render flipped to not need mirror anymore } //---------------------------------------------------------------------------- void GLWidget::resizeGL(int w, int h) { LOG_ENTER_FUNC() << "(" << w << "|" << h << ")" << static_cast<float>(w)/h << ":" << 1; glViewport(0,0,w,h); //glOrtho(0, static_cast<float>(w)/h, 0, 1, -1.0, 1.0); } //---------------------------------------------------------------------------- void GLWidget::moveEvent(QMoveEvent *event) { if( event->pos() != QPoint(0,0) ) move( QPoint(0,0) ); } //---------------------------------------------------------------------------- void GLWidget::updateScreenShot(QPoint window_offset) { if( _screenshot.isNull() ) { qWarning("No screenshot available..."); return; } qDebug("Update screenshot..."); _slot_desktop->setValid(false); // remove links from screenshot _fbo_desktop->bind(); shader->bind(); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); bindTexture( _screenshot ); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_links->_data->id); float dx = static_cast<float>(window_offset.x()) / width(), dy = static_cast<float>(window_offset.y()) / height(); shader->setUniformValue("desktop", 0); shader->setUniformValue("links", 1); shader->setUniformValue("offset", dx, dy); glBegin( GL_QUADS ); glTexCoord2f(dx,dy); glVertex2f(-1 + 2 * dx, -1 + 2 * dy); glTexCoord2f(1,dy); glVertex2f(1,-1 + 2 * dy); glTexCoord2f(1,1); glVertex2f(1,1); glTexCoord2f(dx,1); glVertex2f(-1 + 2 * dx, 1); glEnd(); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); shader->release(); _fbo_desktop->release(); _slot_desktop->setValid(true); // static int counter = 0; //if( !(counter++ % 5) ) // _fbo_desktop->toImage().save( QString("desktop%1.png").arg(counter++) ); _screenshot = QPixmap(); } } // namespace qtfullscreensystem <commit_msg>routing component back in<commit_after>#ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <gl/glew.h> #include <gl/gl.h> #endif #include "qglwidget.hpp" #include <cmath> #include <cstddef> #include <iostream> #include <memory> #include <GL/gl.h> #include <QApplication> #include <QBitmap> #include <QDesktopWidget> #include <QMoveEvent> #include <QGLShader> #define LOG_ENTER_FUNC() qDebug() << __FUNCTION__ namespace qtfullscreensystem { typedef QGLShaderProgram Shader; typedef std::shared_ptr<Shader> ShaderPtr; /** * * @param vert Path to vertex shader * @param frag Path to fragment shader */ ShaderPtr loadShader( QString vert, QString frag ) { qDebug() << "loadShader("<< vert << "|" << frag << ")"; ShaderPtr program = std::make_shared<Shader>(); if( !program->addShaderFromSourceFile(QGLShader::Vertex, vert) ) { qWarning() << "Failed to load vertex shader (" << vert << ")\n" << program->log(); return ShaderPtr(); } if( !program->addShaderFromSourceFile(QGLShader::Fragment, frag) ) { qWarning() << "Failed to load fragment shader (" << frag << ")\n" << program->log(); return ShaderPtr(); } if( !program->link() ) { qWarning() << "Failed to link shader (" << vert << "|" << frag << ")\n" << program->log(); return ShaderPtr(); } return program; } //---------------------------------------------------------------------------- GLWidget::GLWidget(int& argc, char *argv[]) { //-------------------------------- // Setup opengl and window //-------------------------------- if( !QGLFormat::hasOpenGL() ) qFatal("OpenGL not supported!"); if( !QGLFramebufferObject::hasOpenGLFramebufferObjects() ) qFatal("OpenGL framebufferobjects not supported!"); // fullscreen setGeometry( QApplication::desktop()->screenGeometry(this) ); // don't allow user to change the window size setFixedSize( size() ); // transparent, always on top window without any decoration setWindowFlags( Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::MSWindowsOwnDC //| Qt::X11BypassWindowManagerHint ); setWindowOpacity(0.5); setMask(QRegion(-1, -1, 1, 1)); if( !isValid() ) qFatal("Unable to create OpenGL context (not valid)"); qDebug ( "Created GLWidget with OpenGL %d.%d", format().majorVersion(), format().minorVersion() ); //-------------------------------- // Setup component system //-------------------------------- if( argc != 2 ) qFatal("Usage: %s <config>", argv[0]); assert(argc == 2 && argv && argv[1]); publishSlots(_core.getSlotCollector()); _core.startup(argv[1]); _core.attachComponent(&_config); _core.attachComponent(&_cost_analysis); _core.attachComponent(&_routing); _core.attachComponent(&_renderer); _core.init(); _subscribe_links = _core.getSlotSubscriber().getSlot<LinksRouting::SlotType::Image>("/rendered-links"); _subscribe_costmap = _core.getSlotSubscriber().getSlot<LinksRouting::SlotType::Image>("/costmap"); } //---------------------------------------------------------------------------- GLWidget::~GLWidget() { } //---------------------------------------------------------------------------- void GLWidget::captureScreen() { LOG_ENTER_FUNC(); _screenshot = QPixmap::grabWindow(QApplication::desktop()->winId()); } //---------------------------------------------------------------------------- void GLWidget::publishSlots(LinksRouting::SlotCollector slot_collector) { _slot_desktop = slot_collector.create<LinksRouting::SlotType::Image>("/desktop"); _slot_desktop->_data->type = LinksRouting::SlotType::Image::OpenGLTexture; } ShaderPtr shader; //------------------------------------------------------------------------------ void GLWidget::initializeGL() { LOG_ENTER_FUNC(); #if WIN32 if(glewInit() != GLEW_OK) qFatal("Unable to init Glew"); #endif if( _fbo_desktop ) qDebug("FBO already initialized!"); _fbo_desktop.reset ( new QGLFramebufferObject ( size(), QGLFramebufferObject::Depth ) ); if( !_fbo_desktop->isValid() ) qFatal("Failed to create framebufferobject!"); _slot_desktop->_data->id = _fbo_desktop->texture(); _slot_desktop->_data->width = size().width(); _slot_desktop->_data->height = size().height(); shader = loadShader("simple.vert", "remove_links.frag"); if( !shader ) qFatal("Failed to load shader."); glClearColor(0, 0, 0, 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); _core.initGL(); } //---------------------------------------------------------------------------- void GLWidget::paintGL() { // X11: Window decorators add decoration after creating the window. So we // need to get the new position of the window before drawing... QPoint window_offset = mapToGlobal(QPoint()); LOG_ENTER_FUNC() << "window offset=" << window_offset; _core.process(); updateScreenShot(window_offset); // normal draw... glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_links->_data->id); glBegin( GL_QUADS ); glColor3f(1,1,1); glTexCoord2f(0,0); glVertex2f(-1,-1); glTexCoord2f(1,0); glVertex2f(1,-1); glTexCoord2f(1,1); glVertex2f(1,1); glTexCoord2f(0,1); glVertex2f(-1,1); glEnd(); glDisable(GL_TEXTURE_2D); static QImage links(size(), QImage::Format_RGB888); static QImage costmap(QSize(_subscribe_costmap->_data->width, _subscribe_costmap->_data->height), QImage::Format_RGB888); static QImage desktop(size(), QImage::Format_RGB888); glPushAttrib(GL_CLIENT_PIXEL_STORE_BIT); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, width(), height(), GL_RGB, GL_UNSIGNED_BYTE, links.bits()); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_costmap->_data->id); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, costmap.bits()); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _slot_desktop->_data->id); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, desktop.bits()); glDisable(GL_TEXTURE_2D); glPopAttrib(); //links.save("fbo.png"); QBitmap mask = QBitmap::fromImage( links.mirrored().createMaskFromColor( qRgb(0,0,0) ) ); //mask.save("mask.png"); setMask(mask); static int counter = 0; desktop.mirrored().save(QString("desktop%1.png").arg(counter)); costmap.mirrored().save(QString("costmap%1.png").arg(counter)); links.mirrored().save(QString("links%1.png").arg(counter)); ++counter; // TODO render flipped to not need mirror anymore } //---------------------------------------------------------------------------- void GLWidget::resizeGL(int w, int h) { LOG_ENTER_FUNC() << "(" << w << "|" << h << ")" << static_cast<float>(w)/h << ":" << 1; glViewport(0,0,w,h); //glOrtho(0, static_cast<float>(w)/h, 0, 1, -1.0, 1.0); } //---------------------------------------------------------------------------- void GLWidget::moveEvent(QMoveEvent *event) { if( event->pos() != QPoint(0,0) ) move( QPoint(0,0) ); } //---------------------------------------------------------------------------- void GLWidget::updateScreenShot(QPoint window_offset) { if( _screenshot.isNull() ) { qWarning("No screenshot available..."); return; } qDebug("Update screenshot..."); _slot_desktop->setValid(false); // remove links from screenshot _fbo_desktop->bind(); shader->bind(); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); bindTexture( _screenshot ); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, _subscribe_links->_data->id); float dx = static_cast<float>(window_offset.x()) / width(), dy = static_cast<float>(window_offset.y()) / height(); shader->setUniformValue("desktop", 0); shader->setUniformValue("links", 1); shader->setUniformValue("offset", dx, dy); glBegin( GL_QUADS ); glTexCoord2f(dx,dy); glVertex2f(-1 + 2 * dx, -1 + 2 * dy); glTexCoord2f(1,dy); glVertex2f(1,-1 + 2 * dy); glTexCoord2f(1,1); glVertex2f(1,1); glTexCoord2f(dx,1); glVertex2f(-1 + 2 * dx, 1); glEnd(); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); shader->release(); _fbo_desktop->release(); _slot_desktop->setValid(true); // static int counter = 0; //if( !(counter++ % 5) ) // _fbo_desktop->toImage().save( QString("desktop%1.png").arg(counter++) ); _screenshot = QPixmap(); } } // namespace qtfullscreensystem <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/url_request/url_request_simple_job.h" #include <vector> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" #include "base/profiler/scoped_tracker.h" #include "base/threading/worker_pool.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "net/http/http_util.h" #include "net/url_request/url_request_status.h" namespace net { namespace { void CopyData(const scoped_refptr<IOBuffer>& buf, int buf_size, const scoped_refptr<base::RefCountedMemory>& data, int64 data_offset) { memcpy(buf->data(), data->front() + data_offset, buf_size); } } // namespace URLRequestSimpleJob::URLRequestSimpleJob(URLRequest* request, NetworkDelegate* network_delegate) : URLRangeRequestJob(request, network_delegate), next_data_offset_(0), task_runner_(base::WorkerPool::GetTaskRunner(false)), weak_factory_(this) { } void URLRequestSimpleJob::Start() { // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&URLRequestSimpleJob::StartAsync, weak_factory_.GetWeakPtr())); } bool URLRequestSimpleJob::GetMimeType(std::string* mime_type) const { *mime_type = mime_type_; return true; } bool URLRequestSimpleJob::GetCharset(std::string* charset) { *charset = charset_; return true; } URLRequestSimpleJob::~URLRequestSimpleJob() {} bool URLRequestSimpleJob::ReadRawData(IOBuffer* buf, int buf_size, int* bytes_read) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::ReadRawData")); DCHECK(bytes_read); buf_size = static_cast<int>( std::min(static_cast<int64>(buf_size), byte_range_.last_byte_position() - next_data_offset_ + 1)); DCHECK_GE(buf_size, 0); if (buf_size == 0) { *bytes_read = 0; return true; } // Do memory copy on a background thread. See crbug.com/422489. GetTaskRunner()->PostTaskAndReply( FROM_HERE, base::Bind(&CopyData, make_scoped_refptr(buf), buf_size, data_, next_data_offset_), base::Bind(&URLRequestSimpleJob::OnReadCompleted, weak_factory_.GetWeakPtr(), buf_size)); next_data_offset_ += buf_size; SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); return false; } void URLRequestSimpleJob::OnReadCompleted(int bytes_read) { SetStatus(net::URLRequestStatus()); NotifyReadComplete(bytes_read); } base::TaskRunner* URLRequestSimpleJob::GetTaskRunner() const { return task_runner_.get(); } int URLRequestSimpleJob::GetData(std::string* mime_type, std::string* charset, std::string* data, const CompletionCallback& callback) const { NOTREACHED(); return ERR_UNEXPECTED; } int URLRequestSimpleJob::GetRefCountedData( std::string* mime_type, std::string* charset, scoped_refptr<base::RefCountedMemory>* data, const CompletionCallback& callback) const { scoped_refptr<base::RefCountedString> str_data(new base::RefCountedString()); int result = GetData(mime_type, charset, &str_data->data(), callback); *data = str_data; return result; } void URLRequestSimpleJob::StartAsync() { if (!request_) return; if (ranges().size() > 1) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 1")); NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } if (!ranges().empty() && range_parse_result() == OK) byte_range_ = ranges().front(); int result; { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. // Remove the block and assign 'result' in its declaration. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 2")); result = GetRefCountedData(&mime_type_, &charset_, &data_, base::Bind(&URLRequestSimpleJob::OnGetDataCompleted, weak_factory_.GetWeakPtr())); } if (result != ERR_IO_PENDING) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 3")); OnGetDataCompleted(result); } } void URLRequestSimpleJob::OnGetDataCompleted(int result) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::OnGetDataCompleted")); if (result == OK) { // Notify that the headers are complete if (!byte_range_.ComputeBounds(data_->size())) { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } next_data_offset_ = byte_range_.first_byte_position(); set_expected_content_size(byte_range_.last_byte_position() - next_data_offset_ + 1); NotifyHeadersComplete(); } else { NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result)); } } } // namespace net <commit_msg>Instrumenting CopyData to analyze its slowing down The previous CL moved the copy part from IO thread. Now, in the worker thread, copying data 15ms on average, instead of the old 5ms in IO thread, which I want to investigate. I want to separate possible slowness from the task wrapper (what if params are copied in an inefficient way?) from the slowness from the memcpy.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/url_request/url_request_simple_job.h" #include <vector> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/memory/ref_counted_memory.h" #include "base/message_loop/message_loop.h" #include "base/profiler/scoped_tracker.h" #include "base/threading/worker_pool.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "net/http/http_util.h" #include "net/url_request/url_request_status.h" namespace net { namespace { void CopyData(const scoped_refptr<IOBuffer>& buf, int buf_size, const scoped_refptr<base::RefCountedMemory>& data, int64 data_offset) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION("422489 CopyData")); memcpy(buf->data(), data->front() + data_offset, buf_size); } } // namespace URLRequestSimpleJob::URLRequestSimpleJob(URLRequest* request, NetworkDelegate* network_delegate) : URLRangeRequestJob(request, network_delegate), next_data_offset_(0), task_runner_(base::WorkerPool::GetTaskRunner(false)), weak_factory_(this) { } void URLRequestSimpleJob::Start() { // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&URLRequestSimpleJob::StartAsync, weak_factory_.GetWeakPtr())); } bool URLRequestSimpleJob::GetMimeType(std::string* mime_type) const { *mime_type = mime_type_; return true; } bool URLRequestSimpleJob::GetCharset(std::string* charset) { *charset = charset_; return true; } URLRequestSimpleJob::~URLRequestSimpleJob() {} bool URLRequestSimpleJob::ReadRawData(IOBuffer* buf, int buf_size, int* bytes_read) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::ReadRawData")); DCHECK(bytes_read); buf_size = static_cast<int>( std::min(static_cast<int64>(buf_size), byte_range_.last_byte_position() - next_data_offset_ + 1)); DCHECK_GE(buf_size, 0); if (buf_size == 0) { *bytes_read = 0; return true; } // Do memory copy on a background thread. See crbug.com/422489. GetTaskRunner()->PostTaskAndReply( FROM_HERE, base::Bind(&CopyData, make_scoped_refptr(buf), buf_size, data_, next_data_offset_), base::Bind(&URLRequestSimpleJob::OnReadCompleted, weak_factory_.GetWeakPtr(), buf_size)); next_data_offset_ += buf_size; SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); return false; } void URLRequestSimpleJob::OnReadCompleted(int bytes_read) { SetStatus(net::URLRequestStatus()); NotifyReadComplete(bytes_read); } base::TaskRunner* URLRequestSimpleJob::GetTaskRunner() const { return task_runner_.get(); } int URLRequestSimpleJob::GetData(std::string* mime_type, std::string* charset, std::string* data, const CompletionCallback& callback) const { NOTREACHED(); return ERR_UNEXPECTED; } int URLRequestSimpleJob::GetRefCountedData( std::string* mime_type, std::string* charset, scoped_refptr<base::RefCountedMemory>* data, const CompletionCallback& callback) const { scoped_refptr<base::RefCountedString> str_data(new base::RefCountedString()); int result = GetData(mime_type, charset, &str_data->data(), callback); *data = str_data; return result; } void URLRequestSimpleJob::StartAsync() { if (!request_) return; if (ranges().size() > 1) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 1")); NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } if (!ranges().empty() && range_parse_result() == OK) byte_range_ = ranges().front(); int result; { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. // Remove the block and assign 'result' in its declaration. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 2")); result = GetRefCountedData(&mime_type_, &charset_, &data_, base::Bind(&URLRequestSimpleJob::OnGetDataCompleted, weak_factory_.GetWeakPtr())); } if (result != ERR_IO_PENDING) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::StartAsync 3")); OnGetDataCompleted(result); } } void URLRequestSimpleJob::OnGetDataCompleted(int result) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/422489 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "422489 URLRequestSimpleJob::OnGetDataCompleted")); if (result == OK) { // Notify that the headers are complete if (!byte_range_.ComputeBounds(data_->size())) { NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } next_data_offset_ = byte_range_.first_byte_position(); set_expected_content_size(byte_range_.last_byte_position() - next_data_offset_ + 1); NotifyHeadersComplete(); } else { NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result)); } } } // namespace net <|endoftext|>
<commit_before>#ifndef CPP2SIR_REG_HPP #define CPP2SIR_REG_HPP #include "cfg.hpp" #include <clang/AST/Decl.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/Stmt.h> #include <clang/AST/StmtCXX.h> #include <boost/assert.hpp> #include <boost/variant.hpp> #include <boost/utility.hpp> #include <vector> #include <list> #include <map> #include <cstdlib> // TODO: put these to a more reasonable header enum eop_type { eot_none, eot_func, eot_oper, eot_const, eot_member, eot_node, eot_var, eot_varptr, eot_nodetgt, eot_vartgt }; struct eop { eop_type type; cfg::op_id id; eop(cfg::operand op) : type(static_cast<eop_type>(op.type)), id(op.id) { } eop(eop_type type = eot_none, cfg::op_id id = boost::none) : type(type), id(id) { } }; struct enode { cfg::node_type type; std::vector<eop> ops; clang::Stmt const * data; enode(cfg::node_type type, clang::Stmt const * data = 0) : type(type), data(data) { } enode & operator()(eop const & op) { ops.push_back(op); return *this; } enode & operator()(eop_type type, cfg::op_id id) { ops.push_back(eop(type, id)); return *this; } }; // There are two types of registration records---an except clause registration and // the more common automatic variable registration. // // The former is used to introduce try-except statement into the block scope chain. // These registrations are used during the final exception path generation crawl // to direct exceptions to their respective handlers. // // The latter is used to register variables with automatic lifetime and // non-trivial destructors so as to allow the CFG generator to emit a call to it // when a scope (either a full expression scope or a block scope) is left. // This includes break, continue and return statements, throw statements and exception forwarding. struct except_regrec { cfg::vertex_descriptor entry_node; }; struct var_regrec { clang::CXXDestructorDecl const * destr; eop varptr; }; struct exc_object_regrec { eop exc_obj_ptr; }; typedef boost::variant<boost::none_t, var_regrec, except_regrec, exc_object_regrec> regrec; // A registration context is a chain of registration records. As the AST of a function body // is crawled and new declarations and try statements are encountered, the registration // context changes. class context_registry { public: typedef std::list<std::size_t>::iterator node_descriptor; typedef std::size_t context_type; context_registry() : m_nodes(1), m_context(1) { } node_descriptor add(regrec const & r) { BOOST_ASSERT(!m_context.empty()); node n = { r, m_context.back() }; m_nodes.push_back(n); m_context.push_back(m_nodes.size() - 1); return boost::prior(m_context.end()); } void remove(node_descriptor nd) { // TODO: exception guarantees std::size_t parent = m_nodes[*nd].parent; nd = m_context.erase(nd); for (; nd != m_context.end(); ++nd) { node n = { m_nodes[*nd].rec, parent }; m_nodes.push_back(n); *nd = m_nodes.size() - 1; parent = *nd; } } context_type empty_context() const { return 0; } context_type current_context() const { return m_context.back(); } context_type parent(context_type ctx) const { // FIXME: assert return m_nodes[ctx].parent; } context_type begin() const { return 0; } context_type end() const { return m_nodes.size(); } context_type context(node_descriptor n) const { return *n; } template <typename Visitor> void visit_all(Visitor & visitor) { for (std::size_t ctx = m_nodes.size() - 1; ctx != 0; --ctx) m_nodes[ctx].rec.apply_visitor(visitor); } regrec const & value(context_type ctx) const { return m_nodes[ctx].rec; } template <typename Visitor> void visit_range(context_type ctx, context_type ancestor, Visitor & visitor) { BOOST_ASSERT(ctx > 0 && ctx < m_nodes.size()); for (; ctx != ancestor; ctx = m_nodes[ctx].parent) { BOOST_ASSERT(ctx != 0); m_nodes[ctx].rec.apply_visitor(visitor); } } template <typename T> T get(context_type ctx) const { return boost::get<T>(m_nodes[ctx].rec); } private: struct node { regrec rec; std::size_t parent; }; std::vector<node> m_nodes; std::list<std::size_t> m_context; }; // A jump registration records a request for an out-of-flow control redirection. // Break, continue, goto, return and throw statements generate jump registrations. struct jump_sentinel { jump_sentinel() { } jump_sentinel(cfg::vertex_descriptor sentinel, eop const & value = eop()) : sentinel(sentinel), value(value) { } cfg::vertex_descriptor sentinel; eop value; }; typedef std::map<context_registry::context_type, std::vector<jump_sentinel> > jump_registry; #endif <commit_msg>Added a missing assert.<commit_after>#ifndef CPP2SIR_REG_HPP #define CPP2SIR_REG_HPP #include "cfg.hpp" #include <clang/AST/Decl.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/Stmt.h> #include <clang/AST/StmtCXX.h> #include <boost/assert.hpp> #include <boost/variant.hpp> #include <boost/utility.hpp> #include <vector> #include <list> #include <map> #include <cstdlib> // TODO: put these to a more reasonable header enum eop_type { eot_none, eot_func, eot_oper, eot_const, eot_member, eot_node, eot_var, eot_varptr, eot_nodetgt, eot_vartgt }; struct eop { eop_type type; cfg::op_id id; eop(cfg::operand op) : type(static_cast<eop_type>(op.type)), id(op.id) { } eop(eop_type type = eot_none, cfg::op_id id = boost::none) : type(type), id(id) { } }; struct enode { cfg::node_type type; std::vector<eop> ops; clang::Stmt const * data; enode(cfg::node_type type, clang::Stmt const * data = 0) : type(type), data(data) { } enode & operator()(eop const & op) { ops.push_back(op); return *this; } enode & operator()(eop_type type, cfg::op_id id) { ops.push_back(eop(type, id)); return *this; } }; // There are two types of registration records---an except clause registration and // the more common automatic variable registration. // // The former is used to introduce try-except statement into the block scope chain. // These registrations are used during the final exception path generation crawl // to direct exceptions to their respective handlers. // // The latter is used to register variables with automatic lifetime and // non-trivial destructors so as to allow the CFG generator to emit a call to it // when a scope (either a full expression scope or a block scope) is left. // This includes break, continue and return statements, throw statements and exception forwarding. struct except_regrec { cfg::vertex_descriptor entry_node; }; struct var_regrec { clang::CXXDestructorDecl const * destr; eop varptr; }; struct exc_object_regrec { eop exc_obj_ptr; }; typedef boost::variant<boost::none_t, var_regrec, except_regrec, exc_object_regrec> regrec; // A registration context is a chain of registration records. As the AST of a function body // is crawled and new declarations and try statements are encountered, the registration // context changes. class context_registry { public: typedef std::list<std::size_t>::iterator node_descriptor; typedef std::size_t context_type; context_registry() : m_nodes(1), m_context(1) { } node_descriptor add(regrec const & r) { BOOST_ASSERT(!m_context.empty()); node n = { r, m_context.back() }; m_nodes.push_back(n); m_context.push_back(m_nodes.size() - 1); return boost::prior(m_context.end()); } void remove(node_descriptor nd) { // TODO: exception guarantees std::size_t parent = m_nodes[*nd].parent; nd = m_context.erase(nd); for (; nd != m_context.end(); ++nd) { node n = { m_nodes[*nd].rec, parent }; m_nodes.push_back(n); *nd = m_nodes.size() - 1; parent = *nd; } } context_type empty_context() const { return 0; } context_type current_context() const { return m_context.back(); } context_type parent(context_type ctx) const { BOOST_ASSERT(ctx > 0 && ctx < m_nodes.size()); return m_nodes[ctx].parent; } context_type begin() const { return 0; } context_type end() const { return m_nodes.size(); } context_type context(node_descriptor n) const { return *n; } template <typename Visitor> void visit_all(Visitor & visitor) { for (std::size_t ctx = m_nodes.size() - 1; ctx != 0; --ctx) m_nodes[ctx].rec.apply_visitor(visitor); } regrec const & value(context_type ctx) const { return m_nodes[ctx].rec; } template <typename Visitor> void visit_range(context_type ctx, context_type ancestor, Visitor & visitor) { BOOST_ASSERT(ctx > 0 && ctx < m_nodes.size()); for (; ctx != ancestor; ctx = m_nodes[ctx].parent) { BOOST_ASSERT(ctx != 0); m_nodes[ctx].rec.apply_visitor(visitor); } } template <typename T> T get(context_type ctx) const { return boost::get<T>(m_nodes[ctx].rec); } private: struct node { regrec rec; std::size_t parent; }; std::vector<node> m_nodes; std::list<std::size_t> m_context; }; // A jump registration records a request for an out-of-flow control redirection. // Break, continue, goto, return and throw statements generate jump registrations. struct jump_sentinel { jump_sentinel() { } jump_sentinel(cfg::vertex_descriptor sentinel, eop const & value = eop()) : sentinel(sentinel), value(value) { } cfg::vertex_descriptor sentinel; eop value; }; typedef std::map<context_registry::context_type, std::vector<jump_sentinel> > jump_registry; #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_hcd_memmap_occ_sram.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_hcd_memmap_occ_sram.H /// @brief defines region constants of occ sram. /// // *HWP HWP Owner: David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: PM:Hostboot: Phyp #ifndef __P9_HCD_MEMMAP_OCC_SRAM_H__ #define __P9_HCD_MEMMAP_OCC_SRAM_H__ #include <p9_hcd_header_defs.H> #include <p9_hcd_memmap_base.H> // ------------------------------------------------------------------- // Note: There can be NO semicolons(";") at end of macros in this file // There can ONLY have HCD_CONST/HCD_CONST64 macros in this file // ------------------------------------------------------------------- /// OCC SRAM HCD_CONST(OCC_SRAM_BASE_ADDR, 0xFFF00000) HCD_CONST(GPE0_SRAM_BASE_ADDR, 0xFFF01000) HCD_CONST(GPE1_SRAM_BASE_ADDR, 0xFFF10000) /// Base Addresses for various debug/trace regions in OCC SRAM HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_ERR, 0xFFFB4000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_INF, 0xFFFB6000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_IMP, 0xFFFB8000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_SSX_PTR, 0xFFF40824) // Offset to trace buf ptr and trace buffer size from base HCD_CONST(GPE_DEBUG_PTR_OFFSET, 0x180) // Size of various traces regions in OCC SRAM HCD_CONST(OCC_SRAM_TRACE_BUF_SSX_SIZE_PTR, 0xFFF40828) HCD_CONST(OCC_SRAM_TRACE_BUF_ERR_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_TRACE_BUF_INF_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_TRACE_BUF_IMP_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_IPC_REGION_SIZE, (4 * ONE_KB)) HCD_CONST(OCC_SRAM_GPE0_REGION_SIZE, (60 * ONE_KB)) HCD_CONST(OCC_SRAM_GPE1_REGION_SIZE, (64 * ONE_KB)) HCD_CONST(OCC_SRAM_PGPE_REGION_SIZE, (48 * ONE_KB )) HCD_CONST(OCC_SRAM_SGPE_REGION_SIZE, SGPE_IMAGE_SIZE) HCD_CONST(OCC_SRAM_OCC_REGION_SIZE, (512 * ONE_KB)) HCD_CONST(OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL, (OCC_SRAM_IPC_REGION_SIZE + OCC_SRAM_GPE0_REGION_SIZE + OCC_SRAM_GPE1_REGION_SIZE)) //-------------------------------------------------------------------------------------- /// PGPE Base HCD_CONST(OCC_SRAM_PGPE_BASE_ADDR, (OCC_SRAM_BASE_ADDR + OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL)) HCD_CONST(OCC_SRAM_PGPE_END_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + OCC_SRAM_PGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_PGPE_HCODE_RESET_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + PGPE_HCODE_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_PGPE_HEADER_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + PGPE_INT_VECTOR_SIZE)) /// PGPE Boot HCD_CONST(OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_PGPE_COPY_PPMR_HEADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_PGPE_BOOT_LOADER_ADDR, (OCC_SRAM_PGPE_END_ADDR - OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE)) HCD_CONST(OCC_SRAM_PGPE_BOOT_LOADER_RESET_ADDR, (OCC_SRAM_PGPE_BOOT_LOADER_ADDR + PGPE_BOOT_LOADER_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_PGPE_PPMR_HEADER_ADDR, (OCC_SRAM_PGPE_BOOT_LOADER_ADDR - OCC_SRAM_PGPE_COPY_PPMR_HEADER_SIZE)) HCD_CONST(OCC_SRAM_AUX_TASK_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR - PGPE_AUX_TASK_SIZE)) HCD_CONST(OCC_SRAM_PGPE_OPTRACE_ADDR, OCC_SRAM_PGPE_BOOT_LOADER_ADDR) HCD_CONST(OCC_SRAM_PGPE_OPTRACE_SIZE, OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE) /// PGPE Copy HCD_CONST(OCC_SRAM_PGPE_HCODE_OFFSET_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_HCODE_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_PGPE_HCODE_LENGTH_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_HCODE_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_PGPE_IMAGE_LENGTH_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_SRAM_IMAGE_SIZE_BYTE)) // Misc constants used in PGPE boot loader and boot copier. HCD_CONST(PGPE_BOOT_COPY_SUCCESS, 0x42432d53 ) // ASCII code for BC-S HCD_CONST(PGPE_BOOT_COPIER_FAIL, 0x42432d46 ) // ASCII code for BC-F HCD_CONST(PGPE_BOOT_LOADER_SUCCESS, 0x424c2d53 ) // ASCII code for BL-S HCD_CONST(PGPE_BOOT_LOADER_FAIL, 0x424c2d46 ) // ASCII code for BL-F //-------------------------------------------------------------------------------------- // Misc constants used in SGPE boot loader and boot copier. HCD_CONST(DIVDE_BY_8, 3) HCD_CONST(DOUBLE_WORD_SIZE, 8) HCD_CONST(SGPE_BOOT_PROG_CODE_POS, QPMR_SGPE_BOOT_PROG_CODE) HCD_CONST(SGPE_SRAM_IMG_SIZE_POS, QPMR_SGPE_IMAGE_SIZE) HCD_CONST(SGPE_IMG_OFFSET_POS, 40) HCD_CONST(BOOT_COPIER_LEN_ZERO, 0) HCD_CONST(ENABLE_TRAP, 0) HCD_CONST(SGPE_BOOT_COPY_SUCCESS, 0x42432d53 ) // ASCII code for BC-S HCD_CONST(SGPE_BOOT_COPIER_FAIL, 0x42432d46 ) // ASCII code for BC-F HCD_CONST(SGPE_BOOT_LOADER_SUCCESS, 0x424c2d53 ) // ASCII code for BL-S HCD_CONST(SGPE_BOOT_LOADER_FAIL, 0x424c2d46 ) // ASCII code for BL-F /// SGPE Base HCD_CONST(OCC_SRAM_SGPE_BASE_ADDR, (OCC_SRAM_BASE_ADDR + OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL + OCC_SRAM_PGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_SGPE_END_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + OCC_SRAM_SGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_SGPE_HCODE_RESET_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + SGPE_HCODE_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_SGPE_HEADER_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + SGPE_INT_VECTOR_SIZE)) /// SGPE Persistent Data Area(PDA) HCD_CONST(OCC_SRAM_SGPE_PDA_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_PDA_ADDR, (OCC_SRAM_SGPE_END_ADDR - OCC_SRAM_SGPE_PDA_SIZE)) /// SGPE Boot HCD_CONST(OCC_SRAM_SGPE_COPY_BOOT_LOADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_COPY_QPMR_HEADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_BOOT_LOADER_ADDR, (OCC_SRAM_SGPE_PDA_ADDR - OCC_SRAM_SGPE_COPY_BOOT_LOADER_SIZE)) HCD_CONST(OCC_SRAM_SGPE_BOOT_LOADER_RESET_ADDR, (OCC_SRAM_SGPE_BOOT_LOADER_ADDR + SGPE_BOOT_LOADER_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_SGPE_QPMR_HEADER_ADDR, (OCC_SRAM_SGPE_BOOT_LOADER_ADDR - OCC_SRAM_SGPE_COPY_QPMR_HEADER_SIZE)) /// SGPE Copy HCD_CONST(OCC_SRAM_SGPE_HCODE_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_SGPE_HCODE_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_SGPE_HCODE_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_SGPE_HCODE_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_QUAD_COMMON_RINGS_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_COMMON_RINGS_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_QUAD_COMMON_RINGS_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_COMMON_RINGS_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_QUAD_SPECIFIC_RINGS_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_SPECIFIC_RINGS_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_QUAD_SPECIFIC_RINGS_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_SPECIFIC_RINGS_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_SGPE_DASHBOARD_START, ( OCC_SRAM_SGPE_HEADER_ADDR + SGPE_HEADER_SIZE + SGPE_DEBUG_PTRS_SIZE - 4 )); // For 8B alignment HCD_CONST( OCC_SRAM_SGPE_DASHBOARD_SIZE, 0x134 ); HCD_CONST( OCC_SRAM_SGPE_TRACE_START, (OCC_SRAM_SGPE_HEADER_ADDR + SGPE_HEADER_SIZE)); // PGPE HCD_CONST(OCC_SRAM_PGPE_DASHBOARD_START, ( OCC_SRAM_PGPE_HEADER_ADDR + PGPE_HEADER_SIZE + SGPE_DEBUG_PTRS_SIZE - 4 )); // For 8B alignment HCD_CONST( OCC_SRAM_PGPE_DASHBOARD_SIZE, 0xfc ); HCD_CONST( OCC_SRAM_PGPE_TRACE_START, (OCC_SRAM_PGPE_HEADER_ADDR + PGPE_HEADER_SIZE)); #endif /* __P9_HCD_MEMMAP_OCC_SRAM_H__ */ <commit_msg>PM: Move SGPE/PGPE Region and update QPMR/PPMR(2/4)<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_hcd_memmap_occ_sram.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_hcd_memmap_occ_sram.H /// @brief defines region constants of occ sram. /// // *HWP HWP Owner: David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: PM:Hostboot: Phyp #ifndef __P9_HCD_MEMMAP_OCC_SRAM_H__ #define __P9_HCD_MEMMAP_OCC_SRAM_H__ #include <p9_hcd_header_defs.H> #include <p9_hcd_memmap_base.H> // ------------------------------------------------------------------- // Note: There can be NO semicolons(";") at end of macros in this file // There can ONLY have HCD_CONST/HCD_CONST64 macros in this file // ------------------------------------------------------------------- /// OCC SRAM HCD_CONST(OCC_SRAM_BASE_ADDR, 0xFFF00000) HCD_CONST(GPE0_SRAM_BASE_ADDR, 0xFFF01000) HCD_CONST(GPE1_SRAM_BASE_ADDR, 0xFFF10000) /// Base Addresses for various debug/trace regions in OCC SRAM HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_ERR, 0xFFFB4000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_INF, 0xFFFB6000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_IMP, 0xFFFB8000) HCD_CONST(OCC_SRAM_TRACE_BUF_BASE_SSX_PTR, 0xFFF40824) // Offset to trace buf ptr and trace buffer size from base HCD_CONST(GPE_DEBUG_PTR_OFFSET, 0x180) // Size of various traces regions in OCC SRAM HCD_CONST(OCC_SRAM_TRACE_BUF_SSX_SIZE_PTR, 0xFFF40828) HCD_CONST(OCC_SRAM_TRACE_BUF_ERR_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_TRACE_BUF_INF_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_TRACE_BUF_IMP_SIZE, (8 * ONE_KB)) HCD_CONST(OCC_SRAM_IPC_REGION_SIZE, (4 * ONE_KB)) HCD_CONST(OCC_SRAM_GPE0_REGION_SIZE, (60 * ONE_KB)) HCD_CONST(OCC_SRAM_GPE1_REGION_SIZE, (64 * ONE_KB)) HCD_CONST(OCC_SRAM_PGPE_REGION_SIZE, (PGPE_IMAGE_SIZE + PGPE_AUX_TASK_SIZE + PGPE_OCC_SHARED_SRAM_SIZE )) HCD_CONST(OCC_SRAM_SGPE_REGION_SIZE, SGPE_IMAGE_SIZE) HCD_CONST(OCC_SRAM_OCC_REGION_SIZE, (512 * ONE_KB)) HCD_CONST(OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL, (OCC_SRAM_IPC_REGION_SIZE + OCC_SRAM_GPE0_REGION_SIZE + OCC_SRAM_GPE1_REGION_SIZE)) //-------------------------------------------------------------------------------------- /// PGPE Base HCD_CONST(OCC_SRAM_PGPE_BASE_ADDR, (OCC_SRAM_BASE_ADDR + OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL)) HCD_CONST(OCC_SRAM_PGPE_END_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + OCC_SRAM_PGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_PGPE_HCODE_RESET_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + PGPE_HCODE_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_PGPE_HEADER_ADDR, (OCC_SRAM_PGPE_BASE_ADDR + PGPE_INT_VECTOR_SIZE)) /// PGPE Boot HCD_CONST(OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_PGPE_COPY_PPMR_HEADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_PGPE_BOOT_LOADER_ADDR, (OCC_SRAM_PGPE_END_ADDR - OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE)) HCD_CONST(OCC_SRAM_PGPE_BOOT_LOADER_RESET_ADDR, (OCC_SRAM_PGPE_BOOT_LOADER_ADDR + PGPE_BOOT_LOADER_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_PGPE_PPMR_HEADER_ADDR, (OCC_SRAM_PGPE_BOOT_LOADER_ADDR - OCC_SRAM_PGPE_COPY_PPMR_HEADER_SIZE)) HCD_CONST(OCC_SRAM_AUX_TASK_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR - PGPE_AUX_TASK_SIZE)) HCD_CONST(OCC_SRAM_PGPE_OPTRACE_ADDR, OCC_SRAM_PGPE_BOOT_LOADER_ADDR) HCD_CONST(OCC_SRAM_PGPE_OPTRACE_SIZE, OCC_SRAM_PGPE_COPY_BOOT_LOADER_SIZE) /// PGPE Copy HCD_CONST(OCC_SRAM_PGPE_HCODE_OFFSET_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_HCODE_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_PGPE_HCODE_LENGTH_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_HCODE_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_PGPE_IMAGE_LENGTH_ADDR, (OCC_SRAM_PGPE_PPMR_HEADER_ADDR + PPMR_PGPE_SRAM_IMAGE_SIZE_BYTE)) // Misc constants used in PGPE boot loader and boot copier. HCD_CONST(PGPE_BOOT_COPY_SUCCESS, 0x42432d53 ) // ASCII code for BC-S HCD_CONST(PGPE_BOOT_COPIER_FAIL, 0x42432d46 ) // ASCII code for BC-F HCD_CONST(PGPE_BOOT_LOADER_SUCCESS, 0x424c2d53 ) // ASCII code for BL-S HCD_CONST(PGPE_BOOT_LOADER_FAIL, 0x424c2d46 ) // ASCII code for BL-F //-------------------------------------------------------------------------------------- // Misc constants used in SGPE boot loader and boot copier. HCD_CONST(DIVDE_BY_8, 3) HCD_CONST(DOUBLE_WORD_SIZE, 8) HCD_CONST(SGPE_BOOT_PROG_CODE_POS, QPMR_SGPE_BOOT_PROG_CODE) HCD_CONST(SGPE_SRAM_IMG_SIZE_POS, QPMR_SGPE_IMAGE_SIZE) HCD_CONST(SGPE_IMG_OFFSET_POS, 40) HCD_CONST(BOOT_COPIER_LEN_ZERO, 0) HCD_CONST(ENABLE_TRAP, 0) HCD_CONST(SGPE_BOOT_COPY_SUCCESS, 0x42432d53 ) // ASCII code for BC-S HCD_CONST(SGPE_BOOT_COPIER_FAIL, 0x42432d46 ) // ASCII code for BC-F HCD_CONST(SGPE_BOOT_LOADER_SUCCESS, 0x424c2d53 ) // ASCII code for BL-S HCD_CONST(SGPE_BOOT_LOADER_FAIL, 0x424c2d46 ) // ASCII code for BL-F /// SGPE Base HCD_CONST(OCC_SRAM_SGPE_BASE_ADDR, (OCC_SRAM_BASE_ADDR + OCC_SRAM_BEFORE_PGPE_REGION_SIZE_TOTAL + OCC_SRAM_PGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_SGPE_END_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + OCC_SRAM_SGPE_REGION_SIZE)) HCD_CONST(OCC_SRAM_SGPE_HCODE_RESET_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + SGPE_HCODE_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_SGPE_HEADER_ADDR, (OCC_SRAM_SGPE_BASE_ADDR + SGPE_INT_VECTOR_SIZE)) /// SGPE Persistent Data Area(PDA) HCD_CONST(OCC_SRAM_SGPE_PDA_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_PDA_ADDR, (OCC_SRAM_SGPE_END_ADDR - OCC_SRAM_SGPE_PDA_SIZE)) /// SGPE Boot HCD_CONST(OCC_SRAM_SGPE_COPY_BOOT_LOADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_COPY_QPMR_HEADER_SIZE, ONE_KB) HCD_CONST(OCC_SRAM_SGPE_BOOT_LOADER_ADDR, (OCC_SRAM_SGPE_PDA_ADDR - OCC_SRAM_SGPE_COPY_BOOT_LOADER_SIZE)) HCD_CONST(OCC_SRAM_SGPE_BOOT_LOADER_RESET_ADDR, (OCC_SRAM_SGPE_BOOT_LOADER_ADDR + SGPE_BOOT_LOADER_RESET_ADDR_VAL)) HCD_CONST(OCC_SRAM_SGPE_QPMR_HEADER_ADDR, (OCC_SRAM_SGPE_BOOT_LOADER_ADDR - OCC_SRAM_SGPE_COPY_QPMR_HEADER_SIZE)) /// SGPE Copy HCD_CONST(OCC_SRAM_SGPE_HCODE_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_SGPE_HCODE_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_SGPE_HCODE_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_SGPE_HCODE_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_QUAD_COMMON_RINGS_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_COMMON_RINGS_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_QUAD_COMMON_RINGS_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_COMMON_RINGS_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_QUAD_SPECIFIC_RINGS_OFFSET_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_SPECIFIC_RINGS_OFFSET_BYTE)) HCD_CONST(OCC_SRAM_QUAD_SPECIFIC_RINGS_LENGTH_ADDR, (OCC_SRAM_SGPE_QPMR_HEADER_ADDR + QPMR_QUAD_SPECIFIC_RINGS_LENGTH_BYTE)) HCD_CONST(OCC_SRAM_SGPE_DASHBOARD_START, ( OCC_SRAM_SGPE_HEADER_ADDR + SGPE_HEADER_SIZE + SGPE_DEBUG_PTRS_SIZE - 4 )); // For 8B alignment HCD_CONST( OCC_SRAM_SGPE_DASHBOARD_SIZE, 0x134 ); HCD_CONST( OCC_SRAM_SGPE_TRACE_START, (OCC_SRAM_SGPE_HEADER_ADDR + SGPE_HEADER_SIZE)); // PGPE HCD_CONST(OCC_SRAM_PGPE_DASHBOARD_START, ( OCC_SRAM_PGPE_HEADER_ADDR + PGPE_HEADER_SIZE + PGPE_DEBUG_PTRS_SIZE - 4 )); // For 8B alignment HCD_CONST( OCC_SRAM_PGPE_DASHBOARD_SIZE, 0xfc ); HCD_CONST( OCC_SRAM_PGPE_TRACE_START, (OCC_SRAM_PGPE_HEADER_ADDR + PGPE_HEADER_SIZE)); #endif /* __P9_HCD_MEMMAP_OCC_SRAM_H__ */ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_tod_move_tod_to_tb.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_tod_move_tod_to_tb.H /// @brief Procedures to initialize the TOD to 'running' state /// // *HWP HWP Owner: Christina Graves clgraves@us.ibm.com // *HWP FW Owner: Thi Tran thi@us.ibm.com // *HWP Team: Nest // *HWP Level: 2 // *HWP Consumed by: // ---------------------------------------------------------------------------------- // // *! ADDITIONAL COMMENTS : // *! // *! // *! //----------------------------------------------------------------------------------- #ifndef _P9_TOD_MOVE_TOD_TO_TB_H_ #define _P9_TOD_MOVE_TOD_TO_TB_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> #include <p9_tod_utils.H> //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_tod_move_tod_to_tb_FP_t) (const tod_topology_node*, const uint8_t, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* ); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief move_tod_to_tb /// @param[in] i_tod_node => Reference to TOD topology (FAPI targets are included in this) /// @param[in] i_failingTodProc => Pointer to the fapi target, the memory location addressed by this parameter will be populated with processor target which is not able ot receive proper signals from OSC. Caller needs to look at this parameter only when p9_tod_move_tod_to_tb fail and reason code indicated OSC failure. Defaulted to NULL. /// @param[in] i_thread_num => the thread number to complete the transaction on /// @return FAPI_RC_SUCCESS if TOD topology is successfully initialized else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_move_tod_to_tb(const tod_topology_node* i_tod_node, const uint8_t i_thread_num, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* i_failingTodProc = NULL); /// @brief Gets the value in the TFMR register /// @param[in] i_target => P9 chip target /// @param[in] i_thread_num => The thread number we want to run on /// @param[out] o_tfmr_val => Value that is in the TFMR register /// @return FAPI_RC_SUCCESS if TFMR read is successful else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_utils_get_tfmr_reg( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target, const uint8_t i_thread_num, fapi2::buffer<uint64_t>& o_tfmr_val); /// @brief Sets the value in the TFMR register /// @param[in] i_target => P9 chip target /// @param[in] i_thread_num => The thread number we want to run on /// @param[in] i_tfmr_val => Value that will be put in the TFMR register /// @return FAPI_RC_SUCCESS if TFMR write is successful else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_utils_set_tfmr_reg( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target, const uint8_t i_thread_num, fapi2::buffer<uint64_t>& i_tfmr_val); } //extern "C" #endif //_P9_TOD_MOVE_TOD_TO_TB_H_ <commit_msg>L3 update -- TOD HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_tod_move_tod_to_tb.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_tod_move_tod_to_tb.H /// @brief Procedures to initialize the TOD to 'running' state /// // *HWP HWP Owner: Nick Klazynski jklazyns@us.ibm.com // *HWP HWP Owner: Joachim Fenkes fenkes@de.ibm.com // *HWP FW Owner: Manish Chowdhary manichow@in.ibm.com // *HWP Team: Nest // *HWP Level: 3 // *HWP Consumed by: Cronus only // // ----------------------------------------------------------------------------- #ifndef _P9_TOD_MOVE_TOD_TO_TB_H_ #define _P9_TOD_MOVE_TOD_TO_TB_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> #include <p9_tod_utils.H> //------------------------------------------------------------------------------ // Structure definitions //------------------------------------------------------------------------------ //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_tod_move_tod_to_tb_FP_t) ( const tod_topology_node*, const uint8_t, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>*); //------------------------------------------------------------------------------ // Function prototype //------------------------------------------------------------------------------ extern "C" { /// @brief HWP entry point -- move_tod_to_tb /// @param[in] i_tod_node Reference to TOD topology (including FAPI targets) /// @param[in] i_thread_num The thread number to complete the transaction on /// @param[in] i_failingTodProc Pointer to the fapi target, will be populated /// with processor processor target which is not able ot receive /// proper signals from OSC. Caller needs to look at this parameter /// only when p9_tod_move_tod_to_tb fails and reason code indicated /// OSC failure. Defaulted to NULL. /// @return FAPI_RC_SUCCESS if TOD topology is successfully initialized else /// error fapi2::ReturnCode p9_tod_move_tod_to_tb( const tod_topology_node* i_tod_node, const uint8_t i_thread_num, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* o_failingTodProc = NULL); } //extern "C" #endif //_P9_TOD_MOVE_TOD_TO_TB_H_ <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <stdio.h> #include <cassert> #include <lest.hpp> #define MYINFO(X,...) INFO("Test exceptions",X,##__VA_ARGS__) const lest::test tests[] = { { SCENARIO("exceptions can be thrown and caught") { GIVEN ("a custom exception class") { class CustomException : public std::runtime_error { using runtime_error::runtime_error; }; THEN("a runtime exception should be caught") { const char *error_msg = "Crazy Error!"; bool caught = false; try { // We want to always throw, but avoid the compiler optimizing // away the test. Also nice to have this test talk to the OS a little. if (OS::uptime()){ std::runtime_error myexception(error_msg); throw myexception; } } catch(std::runtime_error e) { caught = std::string(e.what()) == std::string(error_msg); } EXPECT(caught); } AND_THEN("a custom exception should also be caught") { std::string custom_msg = "Custom exceptions are useful"; std::string caught_msg = ""; try { throw CustomException(custom_msg); } catch (CustomException e){ caught_msg = e.what(); } EXPECT(caught_msg == custom_msg); }; } } }, }; void Service::start(const std::string&) { MYINFO ("Running LEST-tests"); auto failed = lest::run(tests, {"-p"}); assert(not failed); MYINFO("SUCCESS"); } <commit_msg>test: fixed exception test<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <stdio.h> #include <cassert> #include <lest.hpp> #define MYINFO(X,...) INFO("Test exceptions",X,##__VA_ARGS__) const lest::test tests[] = { { SCENARIO("exceptions can be thrown and caught") { GIVEN ("a custom exception class") { class CustomException : public std::runtime_error { using runtime_error::runtime_error; }; THEN("a runtime exception should be caught") { const char *error_msg = "Crazy Error!"; bool caught = false; try { // We want to always throw, but avoid the compiler optimizing // away the test. Also nice to have this test talk to the OS a little. if (rand()){ std::runtime_error myexception(error_msg); throw myexception; } } catch(std::runtime_error e) { caught = std::string(e.what()) == std::string(error_msg); } EXPECT(caught); } AND_THEN("a custom exception should also be caught") { std::string custom_msg = "Custom exceptions are useful"; std::string caught_msg = ""; try { throw CustomException(custom_msg); } catch (CustomException e){ caught_msg = e.what(); } EXPECT(caught_msg == custom_msg); }; } } }, }; void Service::start(const std::string&) { MYINFO ("Running LEST-tests"); auto failed = lest::run(tests, {"-p"}); assert(not failed); MYINFO("SUCCESS"); } <|endoftext|>
<commit_before>/* * FILE: m.cpp * PURPOSE: 4D maze game * AUTHOR: Geoffrey Card * DATE: 2014-02-06 - 2014-02-06 * NOTES: Controls are un-intuitive. * Graphics are too big. */ #include <cstdio> #include <cstdlib> #include <ctime> #include "m4.hpp" int main (void) { //printf("Hello, brave new world!\n\n"); srand((int) time(NULL)); printf( "2D terminal 4D maze game\n" "(3D window 4D maze game\n" "\n" "press enter"); char c = 0; do { c = getchar(); } while (c != '\n'); for (int i = 0; i < 200; i++) { printf("\n"); } m4 maze; maze.test(); //printf("\n\nGood-bye, cruel world!\n"); return 0; } <commit_msg>improved title screen<commit_after>/* * FILE: m.cpp * PURPOSE: 4D maze game * AUTHOR: Geoffrey Card * DATE: 2014-02-06 - 2014-02-06 * NOTES: Controls are un-intuitive. * Graphics are too big. */ #include <cstdio> #include <cstdlib> #include <ctime> #include "m4.hpp" int main (void) { //printf("Hello, brave new world!\n\n"); srand((int) time(NULL)); // clear screen for (int i = 0; i < 200; i++) { printf("\n"); } // title screen printf( "2D Terminal 4D Maze Game\n" " \n" " By Geoffrey Card \n" " \n" " press enter \n" " \n" ); // press enter char c = 0; do { c = getchar(); } while (c != '\n'); for (int i = 0; i < 200; i++) { printf("\n"); } m4 maze; maze.test(); //printf("\n\nGood-bye, cruel world!\n"); return 0; } <|endoftext|>
<commit_before>/** * @file UxAsyncTest.cpp * @brief UxAsync class tester. * @author zer0 * @date 2018-12-06 */ #include <gtest/gtest.h> #include <libtbag/uvxx/UxLoop.hpp> #include <libtbag/uvxx/UxAsync.hpp> using namespace libtbag; using namespace libtbag::uvxx; TEST(UxAsyncTest, Default) { int async_counter = 0; int close_counter = 0; UxAsync async; ASSERT_FALSE(async.isInit()); UxLoop loop; ASSERT_TRUE(loop.empty()); ASSERT_EQ(Err::E_SUCCESS, async.init(loop)); ASSERT_TRUE(async.isInit()); ASSERT_FALSE(loop.empty()); ASSERT_EQ(1, loop.size()); ASSERT_EQ(Err::E_SUCCESS, async.init(loop)); ASSERT_TRUE(async.isInit()); ASSERT_FALSE(loop.empty()); ASSERT_EQ(2, loop.size()); async.setOnAsync([&](){ ++async_counter; async.close(); }); async.setOnClose([&](){ ++close_counter; }); ASSERT_EQ(Err::E_SUCCESS, async.send()); ASSERT_EQ(Err::E_SUCCESS, loop.run()); ASSERT_TRUE(loop.empty()); ASSERT_EQ(1, async_counter); ASSERT_EQ(1, close_counter); } TEST(UxAsyncTest, AsyncCloseAsync) { // ASYNC -> CLOSE -> ASYNC = CLOSE int async_counter = 0; int close_counter = 0; UxLoop loop; UxAsync async(loop); ASSERT_TRUE(async.isInit()); async.setOnAsync([&](){ ++async_counter; }); async.setOnClose([&](){ ++close_counter; }); ASSERT_EQ(Err::E_SUCCESS, async.send()); async.close(); ASSERT_EQ(Err::E_SUCCESS, async.send()); ASSERT_EQ(Err::E_SUCCESS, loop.run()); ASSERT_TRUE(loop.empty()); ASSERT_EQ(0, async_counter); ASSERT_EQ(1, close_counter); } <commit_msg>Remove UxAsyncTest.AsyncCloseAsync tester.<commit_after>/** * @file UxAsyncTest.cpp * @brief UxAsync class tester. * @author zer0 * @date 2018-12-06 */ #include <gtest/gtest.h> #include <libtbag/uvxx/UxLoop.hpp> #include <libtbag/uvxx/UxAsync.hpp> using namespace libtbag; using namespace libtbag::uvxx; TEST(UxAsyncTest, Default) { int async_counter = 0; int close_counter = 0; UxAsync async; ASSERT_FALSE(async.isInit()); UxLoop loop; ASSERT_TRUE(loop.empty()); ASSERT_EQ(Err::E_SUCCESS, async.init(loop)); ASSERT_TRUE(async.isInit()); ASSERT_FALSE(loop.empty()); ASSERT_EQ(1, loop.size()); ASSERT_EQ(Err::E_SUCCESS, async.init(loop)); ASSERT_TRUE(async.isInit()); ASSERT_FALSE(loop.empty()); ASSERT_EQ(2, loop.size()); async.setOnAsync([&](){ ++async_counter; async.close(); }); async.setOnClose([&](){ ++close_counter; }); ASSERT_EQ(Err::E_SUCCESS, async.send()); ASSERT_EQ(Err::E_SUCCESS, loop.run()); ASSERT_TRUE(loop.empty()); ASSERT_EQ(1, async_counter); ASSERT_EQ(1, close_counter); } <|endoftext|>
<commit_before>/* * opencog/persist/sql/SQLPersistSCM.cc * * Copyright (c) 2008 by OpenCog Foundation * Copyright (c) 2008, 2009, 2013, 2015 Linas Vepstas <linasvepstas@gmail.com> * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_GUILE #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/BackingStore.h> #include <opencog/guile/SchemePrimitive.h> #include <opencog/persist/sql/SQLBackingStore.h> #include "ODBCAtomStorage.h" #include "SQLPersistSCM.h" using namespace opencog; // ================================================================= SQLPersistSCM::SQLPersistSCM(AtomSpace *as) { _as = as; _store = NULL; _backing = new SQLBackingStore(); // XXX FIXME Huge hack alert. // As of 2013, no one uses this thing, except for NLP processing. // Since I'm too lazy to find an elegant solution right now, I'm // just going to hack this in. Fix this someday. // // Anyway, what the below does is to ignore these certain types, // when they are to be fetched from the backing store. This can // speed up document processing, since we know that word instances // and documents and sentences will not be stored in the database. // Thus, we don't even try to fetch these. #define NLP_HACK 0 #if NLP_HACK _backing->_ignored_types.insert(VARIABLE_NODE); _backing->_ignored_types.insert(TYPE_NODE); _backing->_ignored_types.insert(TYPED_VARIABLE_LINK); _backing->_ignored_types.insert(BIND_LINK); _backing->_ignored_types.insert(DOCUMENT_NODE); _backing->_ignored_types.insert(SENTENCE_NODE); _backing->_ignored_types.insert(PARSE_NODE); _backing->_ignored_types.insert(PARSE_LINK); _backing->_ignored_types.insert(WORD_INSTANCE_NODE); _backing->_ignored_types.insert(WORD_INSTANCE_LINK); #endif // NLP_HACK static bool is_init = false; if (is_init) return; is_init = true; scm_with_guile(init_in_guile, this); } void* SQLPersistSCM::init_in_guile(void* self) { scm_c_define_module("opencog persist-sql", init_in_module, self); scm_c_use_module("opencog persist-sql"); return NULL; } void SQLPersistSCM::init_in_module(void* data) { SQLPersistSCM* self = (SQLPersistSCM*) data; self->init(); } void SQLPersistSCM::init(void) { define_scheme_primitive("sql-open", &SQLPersistSCM::do_open, this, "persist-sql"); define_scheme_primitive("sql-close", &SQLPersistSCM::do_close, this, "persist-sql"); define_scheme_primitive("sql-load", &SQLPersistSCM::do_load, this, "persist-sql"); define_scheme_primitive("sql-store", &SQLPersistSCM::do_store, this, "persist-sql"); #ifdef STORAGE_DEBUG define_scheme_primitive("sql-stats", &SQLPersistSCM::do_stats, this, "persist-sql"); #endif } SQLPersistSCM::~SQLPersistSCM() { delete _backing; } void SQLPersistSCM::do_open(const std::string& dbname, const std::string& username, const std::string& auth) { _store = new ODBCAtomStorage(dbname, username, auth); if (!_store) throw RuntimeException(TRACE_INFO, "sql-open: Error: Unable to open the database"); if (!_store->connected()) { delete _store; _store = NULL; throw RuntimeException(TRACE_INFO, "sql-open: Error: Unable to connect to the database"); } _backing->set_store(_store); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-open"); _backing->registerWith(as); } void SQLPersistSCM::do_close(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-close: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-close"); _backing->unregisterWith(as); _backing->set_store(NULL); delete _store; _store = NULL; } void SQLPersistSCM::do_load(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-load: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-load"); // XXX TODO: this should probably be done in a separate thread. _store->loadAtomSpace(as); } void SQLPersistSCM::do_store(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-store: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-store"); // XXX TODO This should really be started in a new thread ... _store->storeAtomSpace(as); } #ifdef STORAGE_DEBUG void SQLPersistSCM::do_stats(void) { if (_store == NULL) printf("sql-stats: Database not open\n"); if (NULL == _as) printf("sql-stats: AtomSpace not set\n"); size_t extra = 0; HandleSeq all; AtomSpace* as = SchemeSmob::ss_get_env_as("sql-stats"); as->get_all_atoms(all); for (const Handle& h: all) { UUID uuid = _store->_tlbuf.getUUID(h); if (TLB::INVALID_UUID != uuid) { extra++; #if 0 // Too much to print. printf("TLB holds extra atoms %lu UUID=%lu %s\n", extra, uuid, h->toString().c_str()); #endif } } printf("sql-stats: Atomspace holds %lu atoms\n", all.size()); printf("sql-stats: tlbuf holds %lu atoms\n", _store->_tlbuf.size()); printf("sql-stats: tlbuf holds %lu atoms not in atomspace\n", extra); double asfrac = 100.0 * extra / ((double) all.size()); double tlfrac = 100.0 * extra / ((double) _store->_tlbuf.size()); printf("Extra is %f percent of atomsapce and %f of tlb \n", asfrac, tlfrac); } } #endif void opencog_persist_sql_init(void) { static SQLPersistSCM patty(NULL); } #endif // HAVE_GUILE <commit_msg>oops.<commit_after>/* * opencog/persist/sql/SQLPersistSCM.cc * * Copyright (c) 2008 by OpenCog Foundation * Copyright (c) 2008, 2009, 2013, 2015 Linas Vepstas <linasvepstas@gmail.com> * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_GUILE #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/BackingStore.h> #include <opencog/guile/SchemePrimitive.h> #include <opencog/persist/sql/SQLBackingStore.h> #include "ODBCAtomStorage.h" #include "SQLPersistSCM.h" using namespace opencog; // ================================================================= SQLPersistSCM::SQLPersistSCM(AtomSpace *as) { _as = as; _store = NULL; _backing = new SQLBackingStore(); // XXX FIXME Huge hack alert. // As of 2013, no one uses this thing, except for NLP processing. // Since I'm too lazy to find an elegant solution right now, I'm // just going to hack this in. Fix this someday. // // Anyway, what the below does is to ignore these certain types, // when they are to be fetched from the backing store. This can // speed up document processing, since we know that word instances // and documents and sentences will not be stored in the database. // Thus, we don't even try to fetch these. #define NLP_HACK 0 #if NLP_HACK _backing->_ignored_types.insert(VARIABLE_NODE); _backing->_ignored_types.insert(TYPE_NODE); _backing->_ignored_types.insert(TYPED_VARIABLE_LINK); _backing->_ignored_types.insert(BIND_LINK); _backing->_ignored_types.insert(DOCUMENT_NODE); _backing->_ignored_types.insert(SENTENCE_NODE); _backing->_ignored_types.insert(PARSE_NODE); _backing->_ignored_types.insert(PARSE_LINK); _backing->_ignored_types.insert(WORD_INSTANCE_NODE); _backing->_ignored_types.insert(WORD_INSTANCE_LINK); #endif // NLP_HACK static bool is_init = false; if (is_init) return; is_init = true; scm_with_guile(init_in_guile, this); } void* SQLPersistSCM::init_in_guile(void* self) { scm_c_define_module("opencog persist-sql", init_in_module, self); scm_c_use_module("opencog persist-sql"); return NULL; } void SQLPersistSCM::init_in_module(void* data) { SQLPersistSCM* self = (SQLPersistSCM*) data; self->init(); } void SQLPersistSCM::init(void) { define_scheme_primitive("sql-open", &SQLPersistSCM::do_open, this, "persist-sql"); define_scheme_primitive("sql-close", &SQLPersistSCM::do_close, this, "persist-sql"); define_scheme_primitive("sql-load", &SQLPersistSCM::do_load, this, "persist-sql"); define_scheme_primitive("sql-store", &SQLPersistSCM::do_store, this, "persist-sql"); #ifdef STORAGE_DEBUG define_scheme_primitive("sql-stats", &SQLPersistSCM::do_stats, this, "persist-sql"); #endif } SQLPersistSCM::~SQLPersistSCM() { delete _backing; } void SQLPersistSCM::do_open(const std::string& dbname, const std::string& username, const std::string& auth) { _store = new ODBCAtomStorage(dbname, username, auth); if (!_store) throw RuntimeException(TRACE_INFO, "sql-open: Error: Unable to open the database"); if (!_store->connected()) { delete _store; _store = NULL; throw RuntimeException(TRACE_INFO, "sql-open: Error: Unable to connect to the database"); } _backing->set_store(_store); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-open"); _backing->registerWith(as); } void SQLPersistSCM::do_close(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-close: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-close"); _backing->unregisterWith(as); _backing->set_store(NULL); delete _store; _store = NULL; } void SQLPersistSCM::do_load(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-load: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-load"); // XXX TODO: this should probably be done in a separate thread. _store->loadAtomSpace(as); } void SQLPersistSCM::do_store(void) { if (_store == NULL) throw RuntimeException(TRACE_INFO, "sql-store: Error: Database not open"); AtomSpace *as = _as; if (NULL == as) as = SchemeSmob::ss_get_env_as("sql-store"); // XXX TODO This should really be started in a new thread ... _store->storeAtomSpace(as); } #ifdef STORAGE_DEBUG void SQLPersistSCM::do_stats(void) { if (_store == NULL) printf("sql-stats: Database not open\n"); if (NULL == _as) printf("sql-stats: AtomSpace not set\n"); size_t extra = 0; HandleSeq all; AtomSpace* as = SchemeSmob::ss_get_env_as("sql-stats"); as->get_all_atoms(all); for (const Handle& h: all) { UUID uuid = _store->_tlbuf.getUUID(h); if (TLB::INVALID_UUID != uuid) { extra++; #if 0 // Too much to print. printf("TLB holds extra atoms %lu UUID=%lu %s\n", extra, uuid, h->toString().c_str()); #endif } } printf("sql-stats: Atomspace holds %lu atoms\n", all.size()); printf("sql-stats: tlbuf holds %lu atoms\n", _store->_tlbuf.size()); printf("sql-stats: tlbuf holds %lu atoms not in atomspace\n", extra); double asfrac = 100.0 * extra / ((double) all.size()); double tlfrac = 100.0 * extra / ((double) _store->_tlbuf.size()); printf("Extra is %f percent of atomsapce and %f of tlb \n", asfrac, tlfrac); } #endif void opencog_persist_sql_init(void) { static SQLPersistSCM patty(NULL); } #endif // HAVE_GUILE <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2020 Morwenn * * 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 <algorithm> #include <functional> #include <iterator> #include <vector> #include <catch2/catch.hpp> #include <cpp-sort/sorters/spin_sorter.h> #include <cpp-sort/utility/functional.h> #include "../algorithm.h" #include "../distributions.h" namespace { struct wrapper { int value; }; struct proj1: cppsort::utility::projection_base { int operator()(int value) const { return -value; } }; } TEST_CASE( "Pipe a projection_base and function pointer", "[utility][projection_base]" ) { std::vector<wrapper> vec(80); helpers::iota(std::begin(vec), std::end(vec), 0, &wrapper::value); std::mt19937_64 engine(Catch::rngSeed()); std::shuffle(std::begin(vec), std::end(vec), engine); proj1 projection; // Basic check cppsort::spin_sort(vec, &wrapper::value | projection); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}, &wrapper::value) ); // Check that the result is also a projection_base cppsort::spin_sort(vec, &wrapper::value | projection | std::negate<>{}); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::less<>{}, &wrapper::value) ); } TEST_CASE( "Pipe a projection_base several times", "[utility][projection_base]" ) { std::vector<int> vec; auto distribution = dist::shuffled{}; distribution(std::back_inserter(vec), 80, -38); auto vec2 = vec; proj1 projection; cppsort::spin_sort(vec, projection | projection); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); cppsort::spin_sort(vec2, projection | projection | projection); CHECK( std::is_sorted(std::begin(vec2), std::end(vec2), std::greater<>{}) ); } TEST_CASE( "Pipe a projection with as_projection", "[utility][projection_base]" ) { std::vector<wrapper> vec(80); helpers::iota(std::begin(vec), std::end(vec), 0, &wrapper::value); std::mt19937_64 engine(Catch::rngSeed()); std::shuffle(std::begin(vec), std::end(vec), engine); auto projection1 = cppsort::utility::as_projection(&wrapper::value); auto projection2 = proj1(); // Basic check cppsort::spin_sort(vec, projection1 | projection2); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}, &wrapper::value) ); } <commit_msg>Add tests for chainable non-const projections<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2020 Morwenn * * 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 <algorithm> #include <functional> #include <iterator> #include <vector> #include <catch2/catch.hpp> #include <cpp-sort/sorters/spin_sorter.h> #include <cpp-sort/utility/functional.h> #include "../algorithm.h" #include "../distributions.h" namespace { struct wrapper { int value; }; struct proj1: cppsort::utility::projection_base { int operator()(int value) const { return -value; } }; struct proj2: cppsort::utility::projection_base { int operator()(int value) { return -value; } }; } TEST_CASE( "Pipe a projection_base and function pointer", "[utility][projection_base]" ) { std::vector<wrapper> vec(80); helpers::iota(std::begin(vec), std::end(vec), 0, &wrapper::value); std::mt19937_64 engine(Catch::rngSeed()); std::shuffle(std::begin(vec), std::end(vec), engine); proj1 projection1; proj2 projection2; SECTION( "const projection" ) { cppsort::spin_sort(vec, &wrapper::value | projection1); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}, &wrapper::value) ); } SECTION( "chained const projection" ) { cppsort::spin_sort(vec, &wrapper::value | projection1 | std::negate<>{}); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::less<>{}, &wrapper::value) ); } SECTION( "non-const projection" ) { cppsort::spin_sort(vec, &wrapper::value | projection2); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}, &wrapper::value) ); } SECTION( "chained non-const projection" ) { cppsort::spin_sort(vec, &wrapper::value | projection2 | std::negate<>{}); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::less<>{}, &wrapper::value) ); } } TEST_CASE( "Pipe a projection_base several times", "[utility][projection_base]" ) { std::vector<int> vec; auto distribution = dist::shuffled{}; distribution(std::back_inserter(vec), 80, -38); auto vec2 = vec; proj1 projection1; proj2 projection2; cppsort::spin_sort(vec, projection1 | projection2); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); cppsort::spin_sort(vec2, projection2 | projection1 | projection2); CHECK( std::is_sorted(std::begin(vec2), std::end(vec2), std::greater<>{}) ); } TEST_CASE( "Pipe a projection with as_projection", "[utility][projection_base]" ) { std::vector<wrapper> vec(80); helpers::iota(std::begin(vec), std::end(vec), 0, &wrapper::value); std::mt19937_64 engine(Catch::rngSeed()); std::shuffle(std::begin(vec), std::end(vec), engine); auto projection1 = cppsort::utility::as_projection(&wrapper::value); auto projection2 = proj1(); // Basic check cppsort::spin_sort(vec, projection1 | projection2); CHECK( helpers::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}, &wrapper::value) ); } <|endoftext|>
<commit_before>#include "common/common.h" #include "common/input_output.h" #include "common/parser.h" #include "common/generation.h" ChVector<> lpos(0, 0, 0); ChQuaternion<> quat(1, 0, 0, 0); //all dimensions are in millimeters, milligrams real container_width = 10; //width of area with particles real container_length = 50; //length of area that roller will go over 1194mm maximum real container_thickness = 1; //thickness of container walls real container_height = 5; //height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; //amount that roller goes over the container area real roller_length = 3; //length of the roller real roller_radius = 76.2 / 2.0; //radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .2; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.446; real particle_layer_thickness = particle_radius * 4; real particle_friction = .1; real gravity = -9810; //acceleration due to gravity real timestep = .00002; //step size real time_to_run = 1; //length of simulation real current_time = 0; int num_steps = time_to_run / timestep; int max_iteration = 15; int tolerance = 0; string data_folder = "data/sls"; ChSharedBodyPtr ROLLER; real ang = 0; template<class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); } int main(int argc, char* argv[]) { bool visualize = false; int threads = 0; if (argc > 1) { threads = atoi(argv[1]); omp_set_num_threads(threads); visualize = atoi(argv[2]); //visualize //distribution_type //min_radius //max_radius //mass //friction //cohesion //layer_thickness //roller_velocity //roller_omega //roller_friction //roller_cohesion } //cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl; //string solver_string = "ACCELERATED_PROJECTED_GRADIENT_DESCENT"; //========================================================================================================= ChSystemGPU * system_gpu = new ChSystemGPU; system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU); //========================================================================================================= system_gpu->SetMaxiter(max_iteration); system_gpu->SetIterLCPmaxItersSpeed(max_iteration); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration); system_gpu->SetTol(0); system_gpu->SetTolSpeeds(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(3000); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(100, 40, 500)); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50); system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedPtr<ChMaterialSurface> material_plate; material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_plate->SetFriction(floor_friction); InitObject(PLATE, 1, ChVector<>(0, 0, 0), quat, material_plate, true, true, -1000, -20000); ChSharedPtr<ChMaterialSurface> material; material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material->SetFriction(container_friction); InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20); InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20); InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); AddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat); AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(F, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(B, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); FinalizeObject(PLATE, (ChSystemGPU *) system_gpu); FinalizeObject(L, (ChSystemGPU *) system_gpu); FinalizeObject(R, (ChSystemGPU *) system_gpu); FinalizeObject(F, (ChSystemGPU *) system_gpu); FinalizeObject(B, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu); ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ChSharedPtr<ChMaterialSurface> material_roller; material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_roller->SetFriction(roller_friction); InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius), roller_quat, material_roller, true, false, -20, -20); AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat); FinalizeObject(ROLLER, (ChSystemGPU *) system_gpu); //68 int3 num_per_dir = I3(68 * 2, 6, 540 * 2); //num_per_dir = I3(5, 6, 10); num_per_dir = I3(110, 8,880); ParticleGenerator layer_gen(system_gpu); layer_gen.SetDensity(particle_density); layer_gen.SetRadius(R3(particle_radius)); layer_gen.SetNormalDistribution(particle_radius, particle_std_dev); layer_gen.material->SetFriction(particle_friction); layer_gen.addPerturbedVolume(R3(0, 1.35, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0)); //========================================================================================================= //////Rendering specific stuff: if (visualize) { ChOpenGLManager * window_manager = new ChOpenGLManager(); ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers"); openGLView.render_camera->camera_pos = Vector(-50, 0, -50); openGLView.render_camera->look_at = Vector(0, 0, 0); openGLView.SetCustomCallback(RunTimeStep); openGLView.StartSpinning(window_manager); window_manager->CallGlutMainLoop(); } //========================================================================================================= stringstream ss_m; ss_m << data_folder << "/" << "timing.txt"; string timing_file_name = ss_m.str(); ofstream ofile(timing_file_name.c_str()); ofile.close(); int file = 0; for (int i = 0; i < num_steps; i++) { cout << "step " << i; cout << " Residual: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual(); cout << " ITER: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations(); cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time=" << system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time=" << system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << "\n"; //TimingFile(system_gpu, timing_file_name, current_time); system_gpu->DoStepDynamics(timestep); RunTimeStep(system_gpu, i); int save_every = 1.0 / timestep / 6000.0; //save data every n steps if (i % save_every == 0) { stringstream ss; cout << "Frame: " << file << endl; ss << data_folder << "/" << file << ".txt"; DumpObjects(system_gpu, ss.str(), ",", false); //output.ExportData(ss.str()); file++; } current_time += timestep; } stringstream ss; //ss << data_folder << "/" << particle_friction << "_" << plate_friction << "_" << create_particle_plate << ".txt"; //DumpAllObjectsWithGeometry(system_gpu, ss.str()); return 0; } <commit_msg>extra particles layers needed to be moved up<commit_after>#include "common/common.h" #include "common/input_output.h" #include "common/parser.h" #include "common/generation.h" ChVector<> lpos(0, 0, 0); ChQuaternion<> quat(1, 0, 0, 0); //all dimensions are in millimeters, milligrams real container_width = 10; //width of area with particles real container_length = 50; //length of area that roller will go over 1194mm maximum real container_thickness = 1; //thickness of container walls real container_height = 5; //height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; //amount that roller goes over the container area real roller_length = 3; //length of the roller real roller_radius = 76.2 / 2.0; //radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .2; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.446; real particle_layer_thickness = particle_radius * 4; real particle_friction = .1; real gravity = -9810; //acceleration due to gravity real timestep = .00002; //step size real time_to_run = 1; //length of simulation real current_time = 0; int num_steps = time_to_run / timestep; int max_iteration = 15; int tolerance = 0; string data_folder = "data/sls"; ChSharedBodyPtr ROLLER; real ang = 0; template<class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); } int main(int argc, char* argv[]) { bool visualize = false; int threads = 0; if (argc > 1) { threads = atoi(argv[1]); omp_set_num_threads(threads); visualize = atoi(argv[2]); //visualize //distribution_type //min_radius //max_radius //mass //friction //cohesion //layer_thickness //roller_velocity //roller_omega //roller_friction //roller_cohesion } //cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl; //string solver_string = "ACCELERATED_PROJECTED_GRADIENT_DESCENT"; //========================================================================================================= ChSystemGPU * system_gpu = new ChSystemGPU; system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU); //========================================================================================================= system_gpu->SetMaxiter(max_iteration); system_gpu->SetIterLCPmaxItersSpeed(max_iteration); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration); system_gpu->SetTol(0); system_gpu->SetTolSpeeds(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(3000); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(100, 40, 500)); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50); system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedPtr<ChMaterialSurface> material_plate; material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_plate->SetFriction(floor_friction); InitObject(PLATE, 1, ChVector<>(0, 0, 0), quat, material_plate, true, true, -1000, -20000); ChSharedPtr<ChMaterialSurface> material; material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material->SetFriction(container_friction); InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20); InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20); InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); AddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat); AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(F, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(B, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); FinalizeObject(PLATE, (ChSystemGPU *) system_gpu); FinalizeObject(L, (ChSystemGPU *) system_gpu); FinalizeObject(R, (ChSystemGPU *) system_gpu); FinalizeObject(F, (ChSystemGPU *) system_gpu); FinalizeObject(B, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu); ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ChSharedPtr<ChMaterialSurface> material_roller; material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_roller->SetFriction(roller_friction); InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius), roller_quat, material_roller, true, false, -20, -20); AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat); FinalizeObject(ROLLER, (ChSystemGPU *) system_gpu); //68 int3 num_per_dir = I3(68 * 2, 6, 540 * 2); //num_per_dir = I3(5, 6, 10); num_per_dir = I3(110, 8,880); ParticleGenerator layer_gen(system_gpu); layer_gen.SetDensity(particle_density); layer_gen.SetRadius(R3(particle_radius)); layer_gen.SetNormalDistribution(particle_radius, particle_std_dev); layer_gen.material->SetFriction(particle_friction); layer_gen.addPerturbedVolume(R3(0, 1.45, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0)); //========================================================================================================= //////Rendering specific stuff: if (visualize) { ChOpenGLManager * window_manager = new ChOpenGLManager(); ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers"); openGLView.render_camera->camera_pos = Vector(-50, 0, -50); openGLView.render_camera->look_at = Vector(0, 0, 0); openGLView.SetCustomCallback(RunTimeStep); openGLView.StartSpinning(window_manager); window_manager->CallGlutMainLoop(); } //========================================================================================================= stringstream ss_m; ss_m << data_folder << "/" << "timing.txt"; string timing_file_name = ss_m.str(); ofstream ofile(timing_file_name.c_str()); ofile.close(); int file = 0; for (int i = 0; i < num_steps; i++) { cout << "step " << i; cout << " Residual: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual(); cout << " ITER: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations(); cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time=" << system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time=" << system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << "\n"; //TimingFile(system_gpu, timing_file_name, current_time); system_gpu->DoStepDynamics(timestep); RunTimeStep(system_gpu, i); int save_every = 1.0 / timestep / 6000.0; //save data every n steps if (i % save_every == 0) { stringstream ss; cout << "Frame: " << file << endl; ss << data_folder << "/" << file << ".txt"; DumpObjects(system_gpu, ss.str(), ",", false); //output.ExportData(ss.str()); file++; } current_time += timestep; } stringstream ss; //ss << data_folder << "/" << particle_friction << "_" << plate_friction << "_" << create_particle_plate << ".txt"; //DumpAllObjectsWithGeometry(system_gpu, ss.str()); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <vector> #include <cmath> #include <string> #include "common/input_output.h" using std::cout; using std::endl; // all dimensions are in millimeters, milligrams real container_width = 5; // width of area with particles real container_length = 25; // length of area that roller will go over 1194mm maximum real container_thickness = .25; // thickness of container walls real container_height = 2; // height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; // amount that roller goes over the container area real roller_length = 2.5 - .25; // length of the roller real roller_radius = 76.2 / 2.0; // radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .1; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.93; real particle_layer_thickness = particle_radius * 16; real particle_friction = .52; real rolling_friction = .1; real spinning_friction = .1; real gravity = -9810; // acceleration due to gravity // step size which will not allow interpenetration more than 1/6 of smallest radius real timestep = Abs(((particle_radius - particle_std_dev) / 3.0) / roller_velocity); // real timestep = .00005; // step size real time_end = 1; // length of simulation real current_time = 0; int out_fps = 6000; int out_steps = std::ceil((1.0 / timestep) / out_fps); int num_steps = time_end / timestep; int max_iteration = 15; int tolerance = 1e-8; std::string data_output_path = "data_sls"; std::shared_ptr<ChBody> ROLLER; real ang = 0; template <class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); cout << "step " << frame << " " << ROLLER->GetPos().z << "\n"; } int main(int argc, char* argv[]) { real roller_start = container_length + roller_radius / 3.0; time_end = (roller_start) / Abs(roller_velocity); printf("Time to run: %f %f\n", roller_start, time_end); num_steps = time_end / timestep; ChSystemParallelDVI* system = new ChSystemParallelDVI; system->Set_G_acc(ChVector<>(0, gravity, 0)); system->SetIntegrationType(ChSystem::INT_ANITESCU); system->GetSettings()->min_threads = 8; system->GetSettings()->solver.tolerance = tolerance; system->GetSettings()->solver.solver_mode = SPINNING; system->GetSettings()->solver.max_iteration_normal = max_iteration; system->GetSettings()->solver.max_iteration_sliding = max_iteration; system->GetSettings()->solver.max_iteration_spinning = max_iteration; system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220 system->GetSettings()->solver.compute_N = false; system->GetSettings()->solver.alpha = 0; system->GetSettings()->solver.cache_step_length = true; system->GetSettings()->solver.use_full_inertia_tensor = false; system->GetSettings()->solver.contact_recovery_speed = 180; system->GetSettings()->solver.bilateral_clamp_speed = 1e8; system->GetSettings()->solver.skip_residual = 5; system->ChangeSolverType(BB); system->SetLoggingLevel(LOG_INFO); system->SetLoggingLevel(LOG_TRACE); system->GetSettings()->collision.collision_envelope = particle_radius * .05; system->GetSettings()->collision.bins_per_axis = int3(40, 300, 400); system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR; system->GetSettings()->collision.use_two_level = false; system->GetSettings()->collision.fixed_bins = true; auto material_plate = std::make_shared<ChMaterialSurface>(); material_plate->SetFriction(0); std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length), Vector(0, container_height * 2, 0)); FinalizeObject(PLATE, (ChSystemParallel*)system); auto material_bottom = std::make_shared<ChMaterialSurface>(); material_bottom->SetFriction(floor_friction); std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length)); FinalizeObject(BOTTOM, (ChSystemParallel*)system); ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); auto material_roller = std::make_shared<ChMaterialSurface>(); material_roller->SetFriction(roller_friction); utils::InitializeObject(ROLLER, 100000, material_roller, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start), roller_quat, true, false, 6, 6); utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2); FinalizeObject(ROLLER, (ChSystemParallel*)system); auto material_granular = std::make_shared<ChMaterialSurface>(); material_granular->SetFriction(particle_friction); material_granular->SetRollingFriction(rolling_friction); material_granular->SetSpinningFriction(spinning_friction); utils::Generator* gen = new utils::Generator(system); std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1); m1->setDefaultSize(particle_radius); m1->setDefaultDensity(particle_density); m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev, particle_radius + particle_std_dev); m1->setDefaultMaterialDVI(material_granular); gen->createObjectsBox(utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0, 0), ChVector<>(container_width * .9, particle_layer_thickness, container_length * .9)); #if 0 opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "Bucky", system); gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1); gl_window.Pause(); int frame = 0; while (frame < num_steps) { if (gl_window.Active()) { if (gl_window.DoStepDynamics(timestep)) { // TimingOutput(system); RunTimeStep(system, frame); frame++; } gl_window.Render(); } else { exit(0); } } #else double time = 0, exec_time = 0; int sim_frame = 0, out_frame = 0, next_out_frame = 0; while (time < time_end) { system->DoStepDynamics(timestep); if (sim_frame == next_out_frame) { std::cout << "write: " << out_frame << std::endl; DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat", true); out_frame++; next_out_frame += out_steps; } RunTimeStep(system, sim_frame); // Update counters. time += timestep; sim_frame++; exec_time += system->GetTimerStep(); } cout << "==================================" << endl; cout << "Simulation time: " << exec_time << endl; #endif } <commit_msg>Particles were initially interpenetrating walls<commit_after>#include <stdio.h> #include <vector> #include <cmath> #include <string> #include "common/input_output.h" using std::cout; using std::endl; // all dimensions are in millimeters, milligrams real container_width = 5; // width of area with particles real container_length = 25; // length of area that roller will go over 1194mm maximum real container_thickness = .25; // thickness of container walls real container_height = 2; // height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; // amount that roller goes over the container area real roller_length = 2.5 - .25; // length of the roller real roller_radius = 76.2 / 2.0; // radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .1; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.93; real particle_layer_thickness = particle_radius * 16; real particle_friction = .52; real rolling_friction = .1; real spinning_friction = .1; real gravity = -9810; // acceleration due to gravity // step size which will not allow interpenetration more than 1/6 of smallest radius real timestep = Abs(((particle_radius - particle_std_dev) / 3.0) / roller_velocity); // real timestep = .00005; // step size real time_end = 1; // length of simulation real current_time = 0; int out_fps = 6000; int out_steps = std::ceil((1.0 / timestep) / out_fps); int num_steps = time_end / timestep; int max_iteration = 15; int tolerance = 1e-8; std::string data_output_path = "data_sls"; std::shared_ptr<ChBody> ROLLER; real ang = 0; template <class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); cout << "step " << frame << " " << ROLLER->GetPos().z << "\n"; } int main(int argc, char* argv[]) { real roller_start = container_length + roller_radius / 3.0; time_end = (roller_start) / Abs(roller_velocity); printf("Time to run: %f %f\n", roller_start, time_end); num_steps = time_end / timestep; ChSystemParallelDVI* system = new ChSystemParallelDVI; system->Set_G_acc(ChVector<>(0, gravity, 0)); system->SetIntegrationType(ChSystem::INT_ANITESCU); system->GetSettings()->min_threads = 8; system->GetSettings()->solver.tolerance = tolerance; system->GetSettings()->solver.solver_mode = SPINNING; system->GetSettings()->solver.max_iteration_normal = max_iteration; system->GetSettings()->solver.max_iteration_sliding = max_iteration; system->GetSettings()->solver.max_iteration_spinning = max_iteration; system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220 system->GetSettings()->solver.compute_N = false; system->GetSettings()->solver.alpha = 0; system->GetSettings()->solver.cache_step_length = true; system->GetSettings()->solver.use_full_inertia_tensor = false; system->GetSettings()->solver.contact_recovery_speed = 180; system->GetSettings()->solver.bilateral_clamp_speed = 1e8; system->GetSettings()->solver.skip_residual = 5; system->ChangeSolverType(BB); system->SetLoggingLevel(LOG_INFO); system->SetLoggingLevel(LOG_TRACE); system->GetSettings()->collision.collision_envelope = particle_radius * .05; system->GetSettings()->collision.bins_per_axis = int3(40, 300, 400); system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR; system->GetSettings()->collision.use_two_level = false; system->GetSettings()->collision.fixed_bins = true; auto material_plate = std::make_shared<ChMaterialSurface>(); material_plate->SetFriction(0); std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness)); utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length), Vector(0, container_height * 2, 0)); FinalizeObject(PLATE, (ChSystemParallel*)system); auto material_bottom = std::make_shared<ChMaterialSurface>(); material_bottom->SetFriction(floor_friction); std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel); utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6); utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length)); FinalizeObject(BOTTOM, (ChSystemParallel*)system); ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1)); auto material_roller = std::make_shared<ChMaterialSurface>(); material_roller->SetFriction(roller_friction); utils::InitializeObject(ROLLER, 100000, material_roller, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start), roller_quat, true, false, 6, 6); utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2); FinalizeObject(ROLLER, (ChSystemParallel*)system); auto material_granular = std::make_shared<ChMaterialSurface>(); material_granular->SetFriction(particle_friction); material_granular->SetRollingFriction(rolling_friction); material_granular->SetSpinningFriction(spinning_friction); utils::Generator* gen = new utils::Generator(system); std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1); m1->setDefaultSize(particle_radius); m1->setDefaultDensity(particle_density); m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev, particle_radius + particle_std_dev); m1->setDefaultMaterialDVI(material_granular); gen->createObjectsBox( utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0, 0), ChVector<>(container_width * .9 - (particle_radius + particle_std_dev) * 2, particle_layer_thickness, container_length * .9 - (particle_radius + particle_std_dev) * 2)); #if 0 opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "Bucky", system); gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1); gl_window.Pause(); int frame = 0; while (frame < num_steps) { if (gl_window.Active()) { if (gl_window.DoStepDynamics(timestep)) { // TimingOutput(system); RunTimeStep(system, frame); frame++; } gl_window.Render(); } else { exit(0); } } #else double time = 0, exec_time = 0; int sim_frame = 0, out_frame = 0, next_out_frame = 0; while (time < time_end) { system->DoStepDynamics(timestep); if (sim_frame == next_out_frame) { std::cout << "write: " << out_frame << std::endl; DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat", true); out_frame++; next_out_frame += out_steps; } RunTimeStep(system, sim_frame); // Update counters. time += timestep; sim_frame++; exec_time += system->GetTimerStep(); } cout << "==================================" << endl; cout << "Simulation time: " << exec_time << endl; #endif } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: externallock.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-01-11 14:05:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ #define _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ #ifndef TOOLKIT_DLLAPI_H #include <toolkit/dllapi.h> #endif #ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX #include <comphelper/accessiblecontexthelper.hxx> #endif // ----------------------------------------------------------------------------- // class VCLExternalSolarLock // ----------------------------------------------------------------------------- class TOOLKIT_DLLPUBLIC VCLExternalSolarLock : public ::comphelper::IMutex { public: virtual void acquire(); virtual void release(); }; #endif // _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.84); FILE MERGED 2005/09/05 16:57:48 rt 1.2.84.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: externallock.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:54:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ #define _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ #ifndef TOOLKIT_DLLAPI_H #include <toolkit/dllapi.h> #endif #ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX #include <comphelper/accessiblecontexthelper.hxx> #endif // ----------------------------------------------------------------------------- // class VCLExternalSolarLock // ----------------------------------------------------------------------------- class TOOLKIT_DLLPUBLIC VCLExternalSolarLock : public ::comphelper::IMutex { public: virtual void acquire(); virtual void release(); }; #endif // _TOOLKIT_HELPER_EXTERNALLOCK_HXX_ <|endoftext|>
<commit_before>#ifndef SDR_H_ #define SDR_H_ #include <vector> #include <array> #include <bitset> #include <iostream> #include <utility> #include <algorithm> #include <iostream> #include <cmath> #include <unordered_map> #include <unordered_set> #ifdef USE_SHERWOOD #include "sherwood_map.hpp" #endif namespace sdr { typedef std::size_t position_t; typedef std::size_t width_t; #ifdef USE_SHERWOOD template<typename K, typename V, typename H = std::hash<K>, typename E = std::equal_to<K>,typename A = std::allocator<std::pair<K, V> > > using thin_sherwood_map = sherwood_map<K, V, H, E, A>; template<typename K, typename V> using hashtable_t = thin_sherwood_map<K, V>; #else template<typename K, typename V> using hashtable_t = std::unordered_map<K, V>; #endif template <width_t Width> std::vector<position_t> field_to_list(const std::bitset<Width> & data) { std::vector<position_t> positions; for(std::size_t i=0; i<Width; ++i) { if(data[i]) { positions.push_back(i); } } return positions; } template <width_t Width> struct node { // store the positions of all set bits from 0 -> width std::unordered_set<position_t> positions; node(const std::vector<position_t> & data) : positions(data.begin(), data.end()) {} void fill(const std::vector<position_t> & data) { std::copy(data.begin(), data.end(), std::inserter(positions, positions.begin())); } void clear() { positions.clear(); } void print() const { const std::size_t sroot = std::sqrt(Width); for(std::size_t y=0; y < sroot; ++y) { for(std::size_t x=0; x < sroot; ++x) { std::cout << (positions.count((y * sroot) + x) ? '1' : '0'); } std::cout << std::endl; } } }; template <width_t Width> struct bank { // all inputs we have ever received, we store here compressed into storage std::vector<node<Width>> storage; // this holds our sets of vectors for easy comparison of different objects in storage std::array<std::unordered_set<position_t>, Width> bitmap; bank() : storage(), bitmap() {} void print(const position_t pos) const { storage[pos].print(); } position_t insert(const std::vector<position_t> & data) { storage.push_back(node<Width>(data)); const position_t last_pos = storage.size() - 1; for(position_t pos : data) { bitmap[pos].insert(last_pos); } return last_pos; } void update(const position_t pos, const std::vector<position_t> & data) { node<Width> & node = storage[pos]; for(position_t i : node.positions) { bitmap[i].erase(pos); } node.clear(); node.fill(data); for(position_t p : node.positions) { bitmap[p].insert(pos); } } // find amount of matching bits between two vectors std::size_t similarity(const position_t a, const position_t b) const { std::size_t result = 0; for(position_t pos : storage[a].positions) { result += bitmap[pos].count(b); } return result; } // find similarity of one object compared to the OR'd result of a list of objects std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const { std::bitset<Width> punions; for(const position_t ppos : positions) { for(const position_t spos : storage[ppos].positions) { punions.set(spos); } } std::size_t result = 0; for(const position_t cmp : storage[pos].positions) { result += punions[cmp]; } return result; } // find most similar to object at pos // first refers to position // second refers to matching number of bits std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const { hashtable_t<position_t, std::size_t> matching_m; for(const position_t spos : storage[pos].positions) { for(const position_t bpos : bitmap[spos]) { ++matching_m[bpos]; } } // we dont care about ourselves matching_m.erase(pos); std::vector<std::pair<position_t, std::size_t>> matching_v(matching_m.begin(), matching_m.end()); std::cout << "matching_v.size() => " << matching_v.size() << std::endl; const auto partial_end = matching_v.begin() + ((amount >= matching_v.size()) ? matching_v.size() : amount); std::partial_sort(matching_v.begin(), partial_end, matching_v.end(), []( const std::pair<position_t, std::size_t> a, const std::pair<position_t, std::size_t> b ) { return (a.second) > (b.second); }); return std::vector<std::pair<position_t, std::size_t>>(matching_v.begin(), partial_end); } // return all items matching all in data std::vector<position_t> matching(const std::vector<position_t> & data) const { std::unordered_set<position_t> matching; for(const std::size_t item : data) { for(const std::size_t pos : bitmap[item]) { for(const std::size_t m : data) { if(bitmap[m].count(pos) == 0) { goto skip; } } matching.insert(pos); skip:; } } return std::vector<position_t>(matching.begin(), matching.end()); } // has to match amount in data std::vector<position_t> matching(const std::vector<position_t> & data, const std::size_t amount) const { std::unordered_set<position_t> matching; for(const std::size_t item : data) { for(const std::size_t pos : bitmap[item]) { std::size_t amount_matching = 0; for(const std::size_t m : data) { amount_matching += bitmap[m].count(pos); } if(amount_matching >= amount) { matching.insert(pos); } } } return std::vector<position_t>(matching.begin(), matching.end()); } }; } //namespace sdr #endif <commit_msg>add weighted versions<commit_after>#ifndef SDR_H_ #define SDR_H_ #include <vector> #include <array> #include <bitset> #include <iostream> #include <utility> #include <algorithm> #include <iostream> #include <cmath> #include <unordered_map> #include <unordered_set> #ifdef USE_SHERWOOD #include "sherwood_map.hpp" #endif namespace sdr { typedef std::size_t position_t; typedef std::size_t width_t; #ifdef USE_SHERWOOD template<typename K, typename V, typename H = std::hash<K>, typename E = std::equal_to<K>,typename A = std::allocator<std::pair<K, V> > > using thin_sherwood_map = sherwood_map<K, V, H, E, A>; template<typename K, typename V> using hashtable_t = thin_sherwood_map<K, V>; #else template<typename K, typename V> using hashtable_t = std::unordered_map<K, V>; #endif template <width_t Width> std::vector<position_t> field_to_list(const std::bitset<Width> & data) { std::vector<position_t> positions; for(std::size_t i=0; i<Width; ++i) { if(data[i]) { positions.push_back(i); } } return positions; } template <width_t Width> struct node { // store the positions of all set bits from 0 -> width std::unordered_set<position_t> positions; node(const std::vector<position_t> & data) : positions(data.begin(), data.end()) {} void fill(const std::vector<position_t> & data) { std::copy(data.begin(), data.end(), std::inserter(positions, positions.begin())); } void clear() { positions.clear(); } void print() const { const std::size_t sroot = std::sqrt(Width); for(std::size_t y=0; y < sroot; ++y) { for(std::size_t x=0; x < sroot; ++x) { std::cout << (positions.count((y * sroot) + x) ? '1' : '0'); } std::cout << std::endl; } } }; template <width_t Width> struct bank { // all inputs we have ever received, we store here compressed into storage std::vector<node<Width>> storage; // this holds our sets of vectors for easy comparison of different objects in storage std::array<std::unordered_set<position_t>, Width> bitmap; bank() : storage(), bitmap() {} void print(const position_t pos) const { storage[pos].print(); } position_t insert(const std::vector<position_t> & data) { storage.push_back(node<Width>(data)); const position_t last_pos = storage.size() - 1; for(position_t pos : data) { bitmap[pos].insert(last_pos); } return last_pos; } void update(const position_t pos, const std::vector<position_t> & data) { node<Width> & node = storage[pos]; for(position_t i : node.positions) { bitmap[i].erase(pos); } node.clear(); node.fill(data); for(position_t p : node.positions) { bitmap[p].insert(pos); } } // find amount of matching bits between two vectors std::size_t similarity(const position_t a, const position_t b) const { std::size_t result = 0; for(position_t pos : storage[a].positions) { result += bitmap[pos].count(b); } return result; } // find amount of matching bits between two vectors double weighted_similarity(const position_t a, const position_t b, const std::array<double, Width> & weights) const { double result = 0; for(position_t pos : storage[a].positions) { result += bitmap[pos].count(b) * weights[pos]; } return result; } // find similarity of one object compared to the OR'd result of a list of objects std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const { std::bitset<Width> punions; for(const position_t ppos : positions) { for(const position_t spos : storage[ppos].positions) { punions.set(spos); } } std::size_t result = 0; for(const position_t cmp : storage[pos].positions) { result += punions[cmp]; } return result; } // find similarity of one object compared to the OR'd result of a list of objects double weighted_union_similarity(const position_t pos, const std::vector<position_t> & positions, const std::array<double, Width> & weights) const { std::bitset<Width> punions; for(const position_t ppos : positions) { for(const position_t spos : storage[ppos].positions) { punions.set(spos); } } double result = 0; for(const position_t cmp : storage[pos].positions) { result += punions[cmp] * weights[cmp]; } return result; } // find most similar to object at pos // first refers to position // second refers to matching number of bits std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const { hashtable_t<position_t, std::size_t> matching_m; for(const position_t spos : storage[pos].positions) { for(const position_t bpos : bitmap[spos]) { ++matching_m[bpos]; } } // we dont care about ourselves matching_m.erase(pos); std::vector<std::pair<position_t, std::size_t>> matching_v(matching_m.begin(), matching_m.end()); std::cout << "matching_v.size() => " << matching_v.size() << std::endl; const auto partial_end = matching_v.begin() + ((amount >= matching_v.size()) ? matching_v.size() : amount); std::partial_sort(matching_v.begin(), partial_end, matching_v.end(), []( const std::pair<position_t, std::size_t> a, const std::pair<position_t, std::size_t> b ) { return (a.second) > (b.second); }); return std::vector<std::pair<position_t, std::size_t>>(matching_v.begin(), partial_end); } // return all items matching all in data std::vector<position_t> matching(const std::vector<position_t> & data) const { std::unordered_set<position_t> matching; for(const std::size_t item : data) { for(const std::size_t pos : bitmap[item]) { for(const std::size_t m : data) { if(bitmap[m].count(pos) == 0) { goto skip; } } matching.insert(pos); skip:; } } return std::vector<position_t>(matching.begin(), matching.end()); } // has to match amount in data std::vector<position_t> matching(const std::vector<position_t> & data, const std::size_t amount) const { std::unordered_set<position_t> matching; for(const std::size_t item : data) { for(const std::size_t pos : bitmap[item]) { std::size_t amount_matching = 0; for(const std::size_t m : data) { amount_matching += bitmap[m].count(pos); } if(amount_matching >= amount) { matching.insert(pos); } } } return std::vector<position_t>(matching.begin(), matching.end()); } // has to match amount in data std::vector<position_t> weighted_matching(const std::vector<position_t> & data, const double amount, const std::array<double, Width> & weights) const { std::unordered_set<position_t> matching; for(const std::size_t item : data) { for(const std::size_t pos : bitmap[item]) { double amount_matching = 0; for(const std::size_t m : data) { amount_matching += bitmap[m].count(pos) * weights[m]; } if(amount_matching >= amount) { matching.insert(pos); } } } return std::vector<position_t>(matching.begin(), matching.end()); } }; } //namespace sdr #endif <|endoftext|>
<commit_before>/** @file @brief Test implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include <osvr/Util/ProjectionMatrix.h> #include <osvr/Util/ProjectionMatrixFromFOV.h> #include <osvr/Util/Angles.h> #include <osvr/Util/EigenExtras.h> // Library/third-party includes #include "gtest/gtest.h" // Standard includes // - none using osvr::util::degrees; using osvr::util::computeSymmetricFOVRect; typedef std::vector<double> BoundsList; namespace opts = osvr::util::projection_options; #if 0 template <typename OptionType, bool = opts::IsColumnVector<OptionType::value>::value> struct TransformVector { template<typename Mat, typename Vec> static Vec apply(Mat const& m, Vec const& v) }; #endif template <typename OptionType> class ParameterizedProjectionTest : public ::testing::Test { public: static const opts::OptionType Options = OptionType::value; #if 0 using Vec3 = typename std::conditional<opts::IsColumnVector<Options>::value, osvr::util::ColVector3d, osvr::util::RowVector3d>::type; using Vec4 = typename std::conditional<opts::IsColumnVector<Options>::value, osvr::util::ColVector4d, osvr::util::RowVector4d>::type; #endif using Vec3 = Eigen::Vector3d; using Vec4 = Eigen::Vector4d; static double getMinZ() { return opts::IsZOutputUnsigned<Options>::value ? 0 : -1; } ParameterizedProjectionTest() : xBounds({-1, 1}), yBounds({-1, 1}), zBounds({getMinZ(), 1}) { std::cout << "\n Left handed input: " << std::boolalpha << osvr::util::projection_options::IsLeftHandedInput<Options>::value << "\n"; std::cout << "Unsigned Z output: " << std::boolalpha << osvr::util::projection_options::IsZOutputUnsigned<Options>::value << "\n"; } void setParams(double zNear, double zFar) { near = zNear; far = zFar; std::cout << "Near: " << near << "\tFar: " << far << "\n"; } osvr::util::Rectd computeSymmetricRect() const { return computeSymmetricFOVRect(50. * degrees, 40. * degrees, near); } inline void tryProjection(osvr::util::Rectd const &rect) { std::cout << rect << std::endl; double handednessCorrection = osvr::util::projection_options::IsLeftHandedInput<Options>::value ? 1. : -1.; auto projection = osvr::util::parameterizedCreateProjectionMatrix<Options>(rect, near, far); std::cout << "Projection matrix:\n"; std::cout << projection << std::endl; std::cout << "Frustum corners:\n"; Eigen::Matrix4d inv = projection.inverse(); for (auto z : zBounds) { for (auto y : yBounds) { for (auto x : xBounds) { Vec4 bound(x, y, z, 1); auto result = osvr::util::extractPoint((inv * bound).eval()); std::cout << bound.transpose() << "\t<-\t" << result.transpose() << "\n"; if (z == getMinZ()) { // near plane ASSERT_DOUBLE_EQ(near * handednessCorrection, result.z()); } else { // far plane ASSERT_DOUBLE_EQ(far * handednessCorrection, result.z()); } // F(osvr::util::extractPoint(bound), result); } } } } double near = 0.1; double far = 1000.; private: BoundsList xBounds; BoundsList yBounds; BoundsList zBounds; }; template <opts::OptionType options = 0> using Options = std::integral_constant<opts::OptionType, options>; typedef ::testing::Types< Options<>, Options<opts::ZOutputUnsigned>, Options<opts::LeftHandedInput>, Options<opts::LeftHandedInput | opts::ZOutputUnsigned>> OptionCombinations; TYPED_TEST_CASE(ParameterizedProjectionTest, OptionCombinations); TYPED_TEST(ParameterizedProjectionTest, BasicSmoketest) { this->setParams(0.1, 1000); auto rect = this->computeSymmetricRect(); this->tryProjection(rect); //[&](Eigen::Vector3d const &bound, Eigen::Vector3d const &result) {}); } <commit_msg>Clean up projection tests and add one to compare to the non-parameterized version.<commit_after>/** @file @brief Test implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include <osvr/Util/ProjectionMatrix.h> #include <osvr/Util/ProjectionMatrixFromFOV.h> #include <osvr/Util/Angles.h> #include <osvr/Util/EigenExtras.h> // Library/third-party includes #include "gtest/gtest.h" // Standard includes // - none using osvr::util::degrees; using osvr::util::computeSymmetricFOVRect; typedef std::vector<double> BoundsList; namespace opts = osvr::util::projection_options; template <typename OptionType> class ParameterizedProjectionTest : public ::testing::Test { public: static const opts::OptionType Options = OptionType::value; using Vec3 = Eigen::Vector3d; using Vec4 = Eigen::Vector4d; static double getMinZ() { return opts::IsZOutputUnsigned<Options>::value ? 0 : -1; } ParameterizedProjectionTest() : xBounds({-1, 1}), yBounds({-1, 1}), zBounds({getMinZ(), 1}) { std::cout << "\n Left handed input: " << std::boolalpha << osvr::util::projection_options::IsLeftHandedInput<Options>::value << "\n"; std::cout << "Unsigned Z output: " << std::boolalpha << osvr::util::projection_options::IsZOutputUnsigned<Options>::value << "\n"; } void setParams(double zNear, double zFar) { near = zNear; far = zFar; std::cout << "Near: " << near << "\tFar: " << far << "\n"; } osvr::util::Rectd computeSymmetricRect() const { return computeSymmetricFOVRect(50. * degrees, 40. * degrees, near); } inline void tryProjection(osvr::util::Rectd const &rect) { std::cout << rect << std::endl; double handednessCorrection = osvr::util::projection_options::IsLeftHandedInput<Options>::value ? 1. : -1.; auto projection = osvr::util::parameterizedCreateProjectionMatrix<Options>(rect, near, far); std::cout << "Projection matrix:\n"; std::cout << projection << std::endl; std::cout << "Frustum corners:\n"; Eigen::Matrix4d inv = projection.inverse(); for (auto z : zBounds) { for (auto y : yBounds) { for (auto x : xBounds) { Vec4 bound(x, y, z, 1); auto result = osvr::util::extractPoint((inv * bound).eval()); std::cout << bound.transpose() << "\t<-\t" << result.transpose() << "\n"; if (z == getMinZ()) { // near plane ASSERT_DOUBLE_EQ(near * handednessCorrection, result.z()); } else { // far plane ASSERT_DOUBLE_EQ(far * handednessCorrection, result.z()); } // F(osvr::util::extractPoint(bound), result); } } } } double near = 0.1; double far = 1000.; private: BoundsList xBounds; BoundsList yBounds; BoundsList zBounds; }; template <opts::OptionType options = 0> using Options = std::integral_constant<opts::OptionType, options>; typedef ::testing::Types< Options<>, Options<opts::ZOutputUnsigned>, Options<opts::LeftHandedInput>, Options<opts::LeftHandedInput | opts::ZOutputUnsigned>> OptionCombinations; TYPED_TEST_CASE(ParameterizedProjectionTest, OptionCombinations); TYPED_TEST(ParameterizedProjectionTest, BasicSmoketest) { this->setParams(0.1, 1000); auto rect = this->computeSymmetricRect(); this->tryProjection(rect); } TEST(ParameterizedProjectionTest, MatchesUnparameterized) { using namespace osvr::util; namespace opts = osvr::util::projection_options; double near = 0.1; double far = 100; auto rect = computeSymmetricFOVRect(50. * degrees, 40. * degrees, near); auto paramMat = parameterizedCreateProjectionMatrix<opts::RightHandedInput | opts::ZOutputSigned>( rect, near, far); auto unparamMat = createProjectionMatrix(rect, near, far); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { ASSERT_EQ(paramMat(i, j), unparamMat(i, j)); } } } <|endoftext|>
<commit_before>#include "common/common.h" #include "common/input_output.h" #include "common/parser.h" #include "common/generation.h" ChVector<> lpos(0, 0, 0); ChQuaternion<> quat(1, 0, 0, 0); //all dimensions are in millimeters, milligrams real container_width = 10; //width of area with particles real container_length = 50; //length of area that roller will go over 1194mm maximum real container_thickness = 1; //thickness of container walls real container_height = 5; //height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; //amount that roller goes over the container area real roller_length = 3; //length of the roller real roller_radius = 76.2 / 2.0; //radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .2; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.446; real particle_layer_thickness = particle_radius * 6; real particle_friction = .1; real gravity = -9810; //acceleration due to gravity real timestep = .00002; //step size real time_to_run = 1; //length of simulation real current_time = 0; int num_steps = time_to_run / timestep; int max_iteration = 15; int tolerance = 0; string data_folder = "data/sls"; ChSharedBodyPtr ROLLER; real ang = 0; template<class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); } int main(int argc, char* argv[]) { bool visualize = false; int threads = 0; if (argc > 1) { threads = atoi(argv[1]); omp_set_num_threads(threads); visualize = atoi(argv[2]); //visualize //distribution_type //min_radius //max_radius //mass //friction //cohesion //layer_thickness //roller_velocity //roller_omega //roller_friction //roller_cohesion } //cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl; //string solver_string = "ACCELERATED_PROJECTED_GRADIENT_DESCENT"; //========================================================================================================= ChSystemGPU * system_gpu = new ChSystemGPU; system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU); //========================================================================================================= system_gpu->SetMaxiter(max_iteration); system_gpu->SetIterLCPmaxItersSpeed(max_iteration); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration); system_gpu->SetTol(0); system_gpu->SetTolSpeeds(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(100, 40, 500)); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50); system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedPtr<ChMaterialSurface> material_plate; material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_plate->SetFriction(floor_friction); InitObject(PLATE, 1, ChVector<>(0, 0, 0), quat, material_plate, true, true, -1000, -20000); ChSharedPtr<ChMaterialSurface> material; material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material->SetFriction(container_friction); InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20); InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20); InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); AddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat); AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(F, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(B, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); FinalizeObject(PLATE, (ChSystemGPU *) system_gpu); FinalizeObject(L, (ChSystemGPU *) system_gpu); FinalizeObject(R, (ChSystemGPU *) system_gpu); FinalizeObject(F, (ChSystemGPU *) system_gpu); FinalizeObject(B, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu); ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ChSharedPtr<ChMaterialSurface> material_roller; material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_roller->SetFriction(roller_friction); InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius/6.0), roller_quat, material_roller, true, false, -20, -20); AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat); FinalizeObject(ROLLER, (ChSystemGPU *) system_gpu); //68 int3 num_per_dir = I3(68 * 2, 6, 540 * 2); //num_per_dir = I3(5, 6, 10); num_per_dir = I3(110, 8,880); ParticleGenerator layer_gen(system_gpu); layer_gen.SetDensity(particle_density); layer_gen.SetRadius(R3(particle_radius)); layer_gen.SetNormalDistribution(particle_radius, particle_std_dev); layer_gen.material->SetFriction(particle_friction); layer_gen.addPerturbedVolume(R3(0, 1.45, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0)); //========================================================================================================= //////Rendering specific stuff: if (visualize) { ChOpenGLManager * window_manager = new ChOpenGLManager(); ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers"); openGLView.render_camera->camera_pos = Vector(-50, 0, -50); openGLView.render_camera->look_at = Vector(0, 0, 0); openGLView.SetCustomCallback(RunTimeStep); openGLView.StartSpinning(window_manager); window_manager->CallGlutMainLoop(); } //========================================================================================================= stringstream ss_m; ss_m << data_folder << "/" << "timing.txt"; string timing_file_name = ss_m.str(); ofstream ofile(timing_file_name.c_str()); ofile.close(); int file = 0; for (int i = 0; i < num_steps; i++) { cout << "step " << i; cout << " Residual: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual(); cout << " ITER: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations(); cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time=" << system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time=" << system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << "\n"; //TimingFile(system_gpu, timing_file_name, current_time); system_gpu->DoStepDynamics(timestep); RunTimeStep(system_gpu, i); int save_every = 1.0 / timestep / 6000.0; //save data every n steps if (i % save_every == 0) { stringstream ss; cout << "Frame: " << file << endl; ss << data_folder << "/" << file << ".txt"; DumpAllObjectsWithGeometryPovray(system_gpu, ss.str()); //output.ExportData(ss.str()); file++; } current_time += timestep; } stringstream ss; //ss << data_folder << "/" << particle_friction << "_" << plate_friction << "_" << create_particle_plate << ".txt"; //DumpAllObjectsWithGeometry(system_gpu, ss.str()); return 0; } <commit_msg>reduce time step<commit_after>#include "common/common.h" #include "common/input_output.h" #include "common/parser.h" #include "common/generation.h" ChVector<> lpos(0, 0, 0); ChQuaternion<> quat(1, 0, 0, 0); //all dimensions are in millimeters, milligrams real container_width = 10; //width of area with particles real container_length = 50; //length of area that roller will go over 1194mm maximum real container_thickness = 1; //thickness of container walls real container_height = 5; //height of the outer walls real container_friction = 0; real floor_friction = .2; real spacer_width = 1; real spacer_height = 1; real roller_overlap = 1; //amount that roller goes over the container area real roller_length = 3; //length of the roller real roller_radius = 76.2 / 2.0; //radius of roller real roller_omega = 0; real roller_velocity = -127; real roller_mass = 1; real roller_friction = .2; real roller_cohesion = 0; real particle_radius = .058 / 2.0; real particle_std_dev = .015 / 2.0; real particle_mass = .05; real particle_density = 0.446; real particle_layer_thickness = particle_radius * 6; real particle_friction = .1; real gravity = -9810; //acceleration due to gravity real timestep = .00001; //step size real time_to_run = 1; //length of simulation real current_time = 0; int num_steps = time_to_run / timestep; int max_iteration = 15; int tolerance = 0; string data_folder = "data/sls"; ChSharedBodyPtr ROLLER; real ang = 0; template<class T> void RunTimeStep(T* mSys, const int frame) { ChVector<> roller_pos = ROLLER->GetPos(); ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep)); ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity)); roller_omega = roller_velocity / roller_radius; ang += roller_omega * timestep; if (ang >= 2 * CH_C_PI) { ang = 0; } Quaternion q1; q1.Q_from_AngY(ang); Quaternion q2; q1 = Q_from_AngX(-ang); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ROLLER->SetRot(q1 % roller_quat); ROLLER->SetWvel_loc(Vector(0, roller_omega, 0)); } int main(int argc, char* argv[]) { bool visualize = false; int threads = 0; if (argc > 1) { threads = atoi(argv[1]); omp_set_num_threads(threads); visualize = atoi(argv[2]); //visualize //distribution_type //min_radius //max_radius //mass //friction //cohesion //layer_thickness //roller_velocity //roller_omega //roller_friction //roller_cohesion } //cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl; //string solver_string = "ACCELERATED_PROJECTED_GRADIENT_DESCENT"; //========================================================================================================= ChSystemGPU * system_gpu = new ChSystemGPU; system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU); //========================================================================================================= system_gpu->SetMaxiter(max_iteration); system_gpu->SetIterLCPmaxItersSpeed(max_iteration); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration); system_gpu->SetTol(0); system_gpu->SetTolSpeeds(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300); ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(100, 40, 500)); ((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50); system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); //========================================================================================================= ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChSharedPtr<ChMaterialSurface> material_plate; material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_plate->SetFriction(floor_friction); InitObject(PLATE, 1, ChVector<>(0, 0, 0), quat, material_plate, true, true, -1000, -20000); ChSharedPtr<ChMaterialSurface> material; material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material->SetFriction(container_friction); InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20); InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20); InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20); InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20); AddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat); AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_length), lpos, quat); AddCollisionGeometry(F, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(B, BOX, Vector(container_width, container_height, container_thickness), lpos, quat); AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat); FinalizeObject(PLATE, (ChSystemGPU *) system_gpu); FinalizeObject(L, (ChSystemGPU *) system_gpu); FinalizeObject(R, (ChSystemGPU *) system_gpu); FinalizeObject(F, (ChSystemGPU *) system_gpu); FinalizeObject(B, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu); FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu); ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU)); ChQuaternion<> roller_quat; roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1)); ChSharedPtr<ChMaterialSurface> material_roller; material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material_roller->SetFriction(roller_friction); InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius/6.0), roller_quat, material_roller, true, false, -20, -20); AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat); FinalizeObject(ROLLER, (ChSystemGPU *) system_gpu); //68 int3 num_per_dir = I3(68 * 2, 6, 540 * 2); //num_per_dir = I3(5, 6, 10); num_per_dir = I3(110, 8,880); ParticleGenerator layer_gen(system_gpu); layer_gen.SetDensity(particle_density); layer_gen.SetRadius(R3(particle_radius)); layer_gen.SetNormalDistribution(particle_radius, particle_std_dev); layer_gen.material->SetFriction(particle_friction); layer_gen.addPerturbedVolume(R3(0, 1.45, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0)); //========================================================================================================= //////Rendering specific stuff: if (visualize) { ChOpenGLManager * window_manager = new ChOpenGLManager(); ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers"); openGLView.render_camera->camera_pos = Vector(-50, 0, -50); openGLView.render_camera->look_at = Vector(0, 0, 0); openGLView.SetCustomCallback(RunTimeStep); openGLView.StartSpinning(window_manager); window_manager->CallGlutMainLoop(); } //========================================================================================================= stringstream ss_m; ss_m << data_folder << "/" << "timing.txt"; string timing_file_name = ss_m.str(); ofstream ofile(timing_file_name.c_str()); ofile.close(); int file = 0; for (int i = 0; i < num_steps; i++) { cout << "step " << i; cout << " Residual: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual(); cout << " ITER: " << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations(); cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time=" << system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time=" << system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << "\n"; //TimingFile(system_gpu, timing_file_name, current_time); system_gpu->DoStepDynamics(timestep); RunTimeStep(system_gpu, i); int save_every = 1.0 / timestep / 6000.0; //save data every n steps if (i % save_every == 0) { stringstream ss; cout << "Frame: " << file << endl; ss << data_folder << "/" << file << ".txt"; DumpAllObjectsWithGeometryPovray(system_gpu, ss.str()); //output.ExportData(ss.str()); file++; } current_time += timestep; } stringstream ss; //ss << data_folder << "/" << particle_friction << "_" << plate_friction << "_" << create_particle_plate << ".txt"; //DumpAllObjectsWithGeometry(system_gpu, ss.str()); return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2016 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains Template Metaprogramming (TMP) utilities */ #ifndef CPP_UTILS_TMP_HPP #define CPP_UTILS_TMP_HPP #include <tuple> #include <utility> #include "assert.hpp" #include "tmp/tmp.hpp" #include "tmp/sfinae.hpp" #include "tmp/variadic.hpp" namespace cpp { namespace tmp_detail { /*! * \brief Helper Traits to test if all the types from I to N in * T are homogeneous */ template <std::size_t I, std::size_t S, typename F, typename... T> struct is_homogeneous_helper { /*! * \brief Sub helper for recursive instantiations */ template <std::size_t I1, std::size_t S1, typename Enable = void> struct helper_int : and_helper<std::is_same<F, nth_type_t<I1, T...>>::value, is_homogeneous_helper<I1 + 1, S1, F, T...>::value> {}; /*! * \copydoc helper_int */ template <std::size_t I1, std::size_t S1> struct helper_int<I1, S1, std::enable_if_t<I1 == S1>> : std::is_same<F, nth_type_t<I1, T...>> {}; static constexpr const auto value = helper_int<I, S>::value; ///< Indicates if the sequence of types is homogeneous }; } //end of namespace tmp_detail /*! * \brief Implementation of helper for for_each_tuple_t */ template <int I, typename Tuple, typename Functor> struct for_each_tuple_t_impl { /*! * \brief Apply the functof for each elements in the tuple, from I */ static void for_each(Functor&& func) { std::forward<Functor>(func).template operator()<typename std::tuple_element<I, Tuple>::type>(); for_each_tuple_t_impl<I - 1, Tuple, Functor>::for_each(std::forward<Functor>(func)); } }; /*! * \copydoc for_each_tuple_t_impl */ template <typename Tuple, typename Functor> struct for_each_tuple_t_impl<0, Tuple, Functor> { /*! * \brief Apply the functof for each elements in the tuple, from I */ static void for_each(Functor&& func) { std::forward<Functor>(func).template operator()<typename std::tuple_element<0, Tuple>::type>(); } }; /*! * \copydoc for_each_tuple_t_impl */ template <typename Tuple, typename Functor> struct for_each_tuple_t_impl<-1, Tuple, Functor> { /*! * \brief End of the the recursion */ static void for_each(Functor&& /*func*/) { //Nothing to be done } }; /*! * \brief Call the given functor for each type in the tuple * \tparam Tuple The tuple type * \param func The functor to call */ template <typename Tuple, typename Functor> void for_each_tuple_t(Functor&& func) { for_each_tuple_t_impl<static_cast<int>(std::tuple_size<Tuple>::value) - 1, Tuple, Functor>::for_each(std::forward<Functor>(func)); } /*! * \brief Traits to test if a type is a specialization of a template * \tparam TT The template type * \tparam T The type to test */ template <template <typename...> class TT, typename T> struct is_specialization_of : std::false_type {}; /*! * \copydoc is_specialization_of */ template <template <typename...> class TT, typename... Args> struct is_specialization_of<TT, TT<Args...>> : std::true_type {}; /*! * \brief Traits to test if all the given types are convertible to V * \tparam V The target type * \tparam F The first type to test * \tparam S The types to test */ template <typename V, typename F, typename... S> struct all_convertible_to : bool_constant_c<and_c<all_convertible_to<V, F>, all_convertible_to<V, S...>>> {}; /*! * \copydoc all_convertible_to */ template <typename V, typename F> struct all_convertible_to<V, F> : bool_constant_c<std::is_convertible<F, V>> {}; /*! * \brief Test is a list of types homogeneous * \tparam F The first type * \tparam T The types */ template <typename F, typename... T> struct is_homogeneous : bool_constant_c<tmp_detail::is_homogeneous_helper<0, sizeof...(T)-1, F, T...>> {}; /*! * \copydoc all_convertible_to */ template <typename F> struct is_homogeneous<F> : std::true_type {}; /* * \brief Test if a list of types is sub-homogeneous * * A sub-homogeneous list of types is a list where the N-1 first types are the * same and the last one is different */ template <typename... T> struct is_sub_homogeneous; /*! * \copydoc is_sub_homogeneous */ template <> struct is_sub_homogeneous<> : std::false_type {}; /*! * \copydoc is_sub_homogeneous */ template <typename T> struct is_sub_homogeneous<T> : std::false_type {}; /*! * \copydoc is_sub_homogeneous */ template <typename T1, typename T2> struct is_sub_homogeneous<T1, T2> : bool_constant_c<not_c<std::is_same<T1, T2>>> {}; /*! * \copydoc is_sub_homogeneous */ template <typename T1, typename T2, typename T3, typename... T> struct is_sub_homogeneous<T1, T2, T3, T...> : bool_constant_c< and_c< std::is_same<T1, T2>, is_sub_homogeneous<T2, T3, T...>>> {}; /*! * \brief Apply the given function to each element of the variadic * packs whose position is present in the sequence * \param f The functor * \param i The index sequence * \param args The arguments */ template <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) == 0)> = detail::dummy> void for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) { f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...))); cpp_unused(i); } /*! * \brief Apply the given function to each element of the variadic * packs whose position is present in the sequence * \param f The functor * \param i The index sequence * \param args The arguments */ template <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) > 0)> = detail::dummy> void for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) { f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...))); for_each_in_subset(f, std::index_sequence<I...>(), std::forward<T>(args)...); cpp_unused(i); } /*! * \brief Apply the given function to each element of the variadic pack * \param f The functor * \param args The arguments */ template <typename F, typename... T> void for_each_in(F&& f, T&&... args) { for_each_in_subset(f, std::make_index_sequence<sizeof...(T)>(), std::forward<T>(args)...); } /*! * \brief Test if the variadic list of types containg the given type * \tparam T1 The type to search * \tparam T The list of types */ template <typename T1, typename... T> struct variadic_contains; /*! * \copydoc variadic_contains */ template <typename T1, typename T2, typename... T> struct variadic_contains<T1, T2, T...> : bool_constant_c<or_c<std::is_same<T1, T2>, variadic_contains<T1, T...>>> {}; /*! * \copydoc variadic_contains */ template <typename T1> struct variadic_contains<T1> : std::false_type {}; /*! * \brief A compile-time type list. */ template <typename... T> struct type_list { /*! * \brief Indicates if the list contains the given type * \tparam V The type to search in the list * \return true if the type is in the list, false otherwise. */ template <typename V> static constexpr bool contains() { return variadic_contains<V, T...>::value; } }; } //end of namespace cpp #endif //CPP_UTILS_TMP_HPP <commit_msg>Add value traits support<commit_after>//======================================================================= // Copyright (c) 2013-2016 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains Template Metaprogramming (TMP) utilities */ #ifndef CPP_UTILS_TMP_HPP #define CPP_UTILS_TMP_HPP #include <tuple> #include <utility> #include "assert.hpp" #include "tmp/tmp.hpp" #include "tmp/sfinae.hpp" #include "tmp/variadic.hpp" namespace cpp { namespace tmp_detail { /*! * \brief Helper Traits to test if all the types from I to N in * T are homogeneous */ template <std::size_t I, std::size_t S, typename F, typename... T> struct is_homogeneous_helper { /*! * \brief Sub helper for recursive instantiations */ template <std::size_t I1, std::size_t S1, typename Enable = void> struct helper_int : and_helper<std::is_same<F, nth_type_t<I1, T...>>::value, is_homogeneous_helper<I1 + 1, S1, F, T...>::value> {}; /*! * \copydoc helper_int */ template <std::size_t I1, std::size_t S1> struct helper_int<I1, S1, std::enable_if_t<I1 == S1>> : std::is_same<F, nth_type_t<I1, T...>> {}; static constexpr const auto value = helper_int<I, S>::value; ///< Indicates if the sequence of types is homogeneous }; } //end of namespace tmp_detail /*! * \brief Implementation of helper for for_each_tuple_t */ template <int I, typename Tuple, typename Functor> struct for_each_tuple_t_impl { /*! * \brief Apply the functof for each elements in the tuple, from I */ static void for_each(Functor&& func) { std::forward<Functor>(func).template operator()<typename std::tuple_element<I, Tuple>::type>(); for_each_tuple_t_impl<I - 1, Tuple, Functor>::for_each(std::forward<Functor>(func)); } }; /*! * \copydoc for_each_tuple_t_impl */ template <typename Tuple, typename Functor> struct for_each_tuple_t_impl<0, Tuple, Functor> { /*! * \brief Apply the functof for each elements in the tuple, from I */ static void for_each(Functor&& func) { std::forward<Functor>(func).template operator()<typename std::tuple_element<0, Tuple>::type>(); } }; /*! * \copydoc for_each_tuple_t_impl */ template <typename Tuple, typename Functor> struct for_each_tuple_t_impl<-1, Tuple, Functor> { /*! * \brief End of the the recursion */ static void for_each(Functor&& /*func*/) { //Nothing to be done } }; /*! * \brief Call the given functor for each type in the tuple * \tparam Tuple The tuple type * \param func The functor to call */ template <typename Tuple, typename Functor> void for_each_tuple_t(Functor&& func) { for_each_tuple_t_impl<static_cast<int>(std::tuple_size<Tuple>::value) - 1, Tuple, Functor>::for_each(std::forward<Functor>(func)); } /*! * \brief Traits to test if a type is a specialization of a template * \tparam TT The template type * \tparam T The type to test */ template <template <typename...> class TT, typename T> struct is_specialization_of : std::false_type {}; /*! * \copydoc is_specialization_of */ template <template <typename...> class TT, typename... Args> struct is_specialization_of<TT, TT<Args...>> : std::true_type {}; /*! * \brief Traits to test if all the given types are convertible to V * \tparam V The target type * \tparam F The first type to test * \tparam S The types to test */ template <typename V, typename F, typename... S> struct all_convertible_to : bool_constant_c<and_c<all_convertible_to<V, F>, all_convertible_to<V, S...>>> {}; /*! * \copydoc all_convertible_to */ template <typename V, typename F> struct all_convertible_to<V, F> : bool_constant_c<std::is_convertible<F, V>> {}; /*! * \brief Test is a list of types homogeneous * \tparam F The first type * \tparam T The types */ template <typename F, typename... T> struct is_homogeneous : bool_constant_c<tmp_detail::is_homogeneous_helper<0, sizeof...(T)-1, F, T...>> {}; /*! * \copydoc all_convertible_to */ template <typename F> struct is_homogeneous<F> : std::true_type {}; /* * \brief Test if a list of types is sub-homogeneous * * A sub-homogeneous list of types is a list where the N-1 first types are the * same and the last one is different */ template <typename... T> struct is_sub_homogeneous; /*! * \copydoc is_sub_homogeneous */ template <> struct is_sub_homogeneous<> : std::false_type {}; /*! * \copydoc is_sub_homogeneous */ template <typename T> struct is_sub_homogeneous<T> : std::false_type {}; /*! * \copydoc is_sub_homogeneous */ template <typename T1, typename T2> struct is_sub_homogeneous<T1, T2> : bool_constant_c<not_c<std::is_same<T1, T2>>> {}; /*! * \copydoc is_sub_homogeneous */ template <typename T1, typename T2, typename T3, typename... T> struct is_sub_homogeneous<T1, T2, T3, T...> : bool_constant_c< and_c< std::is_same<T1, T2>, is_sub_homogeneous<T2, T3, T...>>> {}; /*! * \brief Apply the given function to each element of the variadic * packs whose position is present in the sequence * \param f The functor * \param i The index sequence * \param args The arguments */ template <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) == 0)> = detail::dummy> void for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) { f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...))); cpp_unused(i); } /*! * \brief Apply the given function to each element of the variadic * packs whose position is present in the sequence * \param f The functor * \param i The index sequence * \param args The arguments */ template <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) > 0)> = detail::dummy> void for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) { f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...))); for_each_in_subset(f, std::index_sequence<I...>(), std::forward<T>(args)...); cpp_unused(i); } /*! * \brief Apply the given function to each element of the variadic pack * \param f The functor * \param args The arguments */ template <typename F, typename... T> void for_each_in(F&& f, T&&... args) { for_each_in_subset(f, std::make_index_sequence<sizeof...(T)>(), std::forward<T>(args)...); } /*! * \brief Test if the variadic list of types containg the given type * \tparam T1 The type to search * \tparam T The list of types */ template <typename T1, typename... T> struct variadic_contains; /*! * \copydoc variadic_contains */ template <typename T1, typename T2, typename... T> struct variadic_contains<T1, T2, T...> : bool_constant_c<or_c<std::is_same<T1, T2>, variadic_contains<T1, T...>>> {}; /*! * \copydoc variadic_contains */ template <typename T1> struct variadic_contains<T1> : std::false_type {}; /*! * \brief A compile-time type list. */ template <typename... T> struct type_list { /*! * \brief Indicates if the list contains the given type * \tparam V The type to search in the list * \return true if the type is in the list, false otherwise. */ template <typename V> static constexpr bool contains() { return variadic_contains<V, T...>::value; } }; // If the compiler supports it, declare value traits to complement all // the existing traits #if __cpp_variable_templates >= 201304 /*! * \brief Value Traits to test if a type is a specialization of a template * * \tparam TT The template type * \tparam T The type to test */ template <template <typename...> class TT, typename T> constexpr bool is_specialization_of_v = is_specialization_of<TT, T>::value; /*! * \brief Value traits to test if all the given types are convertible to V * * \tparam V The target type * \tparam F The first type to test * \tparam S The types to test */ template <typename V, typename F, typename... S> constexpr bool all_convertible_to_v = all_convertible_to<V, F, S...>::value; /*! * \brief Value traits to test if is a list of types homogeneous * \tparam F The first type * \tparam T The types */ template <typename F, typename... T> constexpr bool is_homogeneous_v = is_homogeneous<F, T...>::value; /* * \brief Value traits to test if a list of types is sub-homogeneous * * A sub-homogeneous list of types is a list where the N-1 first types are the * same and the last one is different */ template <typename... T> constexpr bool is_sub_homogeneous_v = is_sub_homogeneous<T...>; /*! * \brief Value traits to test if the variadic list of types containg the given type * \tparam T1 The type to search * \tparam T The list of types */ template <typename T1, typename... T> constexpr bool variadic_contains_v = variadic_contains<T1, T...>::value; #endif } //end of namespace cpp #endif //CPP_UTILS_TMP_HPP <|endoftext|>
<commit_before>//===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BenchmarkResult.h" #include "BenchmarkRunner.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/bit.h" #include "llvm/ADT/StringRef.h" #include "llvm/ObjectYAML/YAML.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" static constexpr const char kIntegerPrefix[] = "i_0x"; static constexpr const char kDoublePrefix[] = "f_"; static constexpr const char kInvalidOperand[] = "INVALID"; namespace llvm { namespace { // A mutable struct holding an LLVMState that can be passed through the // serialization process to encode/decode registers and instructions. struct YamlContext { YamlContext(const exegesis::LLVMState &State) : State(&State), ErrorStream(LastError) {} void serializeMCInst(const llvm::MCInst &MCInst, llvm::raw_ostream &OS) { OS << getInstrName(MCInst.getOpcode()); for (const auto &Op : MCInst) { OS << ' '; serializeMCOperand(Op, OS); } } void deserializeMCInst(llvm::StringRef String, llvm::MCInst &Value) { llvm::SmallVector<llvm::StringRef, 8> Pieces; String.split(Pieces, " ", /* MaxSplit */ -1, /* KeepEmpty */ false); if (Pieces.empty()) { ErrorStream << "Unknown Instruction: '" << String << "'"; return; } bool ProcessOpcode = true; for (llvm::StringRef Piece : Pieces) { if (ProcessOpcode) Value.setOpcode(getInstrOpcode(Piece)); else Value.addOperand(deserializeMCOperand(Piece)); ProcessOpcode = false; } } std::string &getLastError() { return ErrorStream.str(); } llvm::raw_string_ostream &getErrorStream() { return ErrorStream; } llvm::StringRef getRegName(unsigned RegNo) { const llvm::StringRef RegName = State->getRegInfo().getName(RegNo); if (RegName.empty()) ErrorStream << "No register with enum value" << RegNo; return RegName; } unsigned getRegNo(llvm::StringRef RegName) { const llvm::MCRegisterInfo &RegInfo = State->getRegInfo(); for (unsigned E = RegInfo.getNumRegs(), I = 0; I < E; ++I) if (RegInfo.getName(I) == RegName) return I; ErrorStream << "No register with name " << RegName; return 0; } private: void serializeIntegerOperand(llvm::raw_ostream &OS, int64_t Value) { OS << kIntegerPrefix; OS.write_hex(llvm::bit_cast<uint64_t>(Value)); } bool tryDeserializeIntegerOperand(llvm::StringRef String, int64_t &Value) { if (!String.consume_front(kIntegerPrefix)) return false; return !String.consumeInteger(16, Value); } void serializeFPOperand(llvm::raw_ostream &OS, double Value) { OS << kDoublePrefix << llvm::format("%la", Value); } bool tryDeserializeFPOperand(llvm::StringRef String, double &Value) { if (!String.consume_front(kDoublePrefix)) return false; char *EndPointer = nullptr; Value = strtod(String.begin(), &EndPointer); return EndPointer == String.end(); } void serializeMCOperand(const llvm::MCOperand &MCOperand, llvm::raw_ostream &OS) { if (MCOperand.isReg()) { OS << getRegName(MCOperand.getReg()); } else if (MCOperand.isImm()) { serializeIntegerOperand(OS, MCOperand.getImm()); } else if (MCOperand.isFPImm()) { serializeFPOperand(OS, MCOperand.getFPImm()); } else { OS << kInvalidOperand; } } llvm::MCOperand deserializeMCOperand(llvm::StringRef String) { assert(!String.empty()); int64_t IntValue = 0; double DoubleValue = 0; if (tryDeserializeIntegerOperand(String, IntValue)) return llvm::MCOperand::createImm(IntValue); if (tryDeserializeFPOperand(String, DoubleValue)) return llvm::MCOperand::createFPImm(DoubleValue); if (unsigned RegNo = getRegNo(String)) return llvm::MCOperand::createReg(RegNo); if (String != kInvalidOperand) ErrorStream << "Unknown Operand: '" << String << "'"; return {}; } llvm::StringRef getInstrName(unsigned InstrNo) { const llvm::StringRef InstrName = State->getInstrInfo().getName(InstrNo); if (InstrName.empty()) ErrorStream << "No opcode with enum value" << InstrNo; return InstrName; } unsigned getInstrOpcode(llvm::StringRef InstrName) { const llvm::MCInstrInfo &InstrInfo = State->getInstrInfo(); for (unsigned E = InstrInfo.getNumOpcodes(), I = 0; I < E; ++I) if (InstrInfo.getName(I) == InstrName) return I; ErrorStream << "No opcode with name " << InstrName; return 0; } const llvm::exegesis::LLVMState *State; std::string LastError; llvm::raw_string_ostream ErrorStream; }; } // namespace // Defining YAML traits for IO. namespace yaml { static YamlContext &getTypedContext(void *Ctx) { return *reinterpret_cast<YamlContext *>(Ctx); } // std::vector<llvm::MCInst> will be rendered as a list. template <> struct SequenceElementTraits<llvm::MCInst> { static const bool flow = false; }; template <> struct ScalarTraits<llvm::MCInst> { static void output(const llvm::MCInst &Value, void *Ctx, llvm::raw_ostream &Out) { getTypedContext(Ctx).serializeMCInst(Value, Out); } static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) { YamlContext &Context = getTypedContext(Ctx); Context.deserializeMCInst(Scalar, Value); return Context.getLastError(); } // By default strings are quoted only when necessary. // We force the use of single quotes for uniformity. static QuotingType mustQuote(StringRef) { return QuotingType::Single; } static const bool flow = true; }; // std::vector<exegesis::Measure> will be rendered as a list. template <> struct SequenceElementTraits<exegesis::BenchmarkMeasure> { static const bool flow = false; }; // exegesis::Measure is rendererd as a flow instead of a list. // e.g. { "key": "the key", "value": 0123 } template <> struct MappingTraits<exegesis::BenchmarkMeasure> { static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) { Io.mapRequired("key", Obj.Key); if (!Io.outputting()) { // For backward compatibility, interpret debug_string as a key. Io.mapOptional("debug_string", Obj.Key); } Io.mapRequired("value", Obj.PerInstructionValue); Io.mapOptional("per_snippet_value", Obj.PerSnippetValue); } static const bool flow = true; }; template <> struct ScalarEnumerationTraits<exegesis::InstructionBenchmark::ModeE> { static void enumeration(IO &Io, exegesis::InstructionBenchmark::ModeE &Value) { Io.enumCase(Value, "", exegesis::InstructionBenchmark::Unknown); Io.enumCase(Value, "latency", exegesis::InstructionBenchmark::Latency); Io.enumCase(Value, "uops", exegesis::InstructionBenchmark::Uops); } }; // std::vector<exegesis::RegisterValue> will be rendered as a list. template <> struct SequenceElementTraits<exegesis::RegisterValue> { static const bool flow = false; }; template <> struct ScalarTraits<exegesis::RegisterValue> { static constexpr const unsigned kRadix = 16; static constexpr const bool kSigned = false; static void output(const exegesis::RegisterValue &RV, void *Ctx, llvm::raw_ostream &Out) { YamlContext &Context = getTypedContext(Ctx); Out << Context.getRegName(RV.Register) << "=0x" << RV.Value.toString(kRadix, kSigned); } static StringRef input(StringRef String, void *Ctx, exegesis::RegisterValue &RV) { llvm::SmallVector<llvm::StringRef, 2> Pieces; String.split(Pieces, "=0x", /* MaxSplit */ -1, /* KeepEmpty */ false); YamlContext &Context = getTypedContext(Ctx); if (Pieces.size() == 2) { RV.Register = Context.getRegNo(Pieces[0]); const unsigned BitsNeeded = llvm::APInt::getBitsNeeded(Pieces[1], kRadix); RV.Value = llvm::APInt(BitsNeeded, Pieces[1], kRadix); } else { Context.getErrorStream() << "Unknown initial register value: '" << String << "'"; } return Context.getLastError(); } static QuotingType mustQuote(StringRef) { return QuotingType::Single; } static const bool flow = true; }; template <> struct MappingContextTraits<exegesis::InstructionBenchmarkKey, YamlContext> { static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj, YamlContext &Context) { Io.setContext(&Context); Io.mapRequired("instructions", Obj.Instructions); Io.mapOptional("config", Obj.Config); Io.mapRequired("register_initial_values", Obj.RegisterInitialValues); } }; template <> struct MappingContextTraits<exegesis::InstructionBenchmark, YamlContext> { struct NormalizedBinary { NormalizedBinary(IO &io) {} NormalizedBinary(IO &, std::vector<uint8_t> &Data) : Binary(Data) {} std::vector<uint8_t> denormalize(IO &) { std::vector<uint8_t> Data; std::string Str; raw_string_ostream OSS(Str); Binary.writeAsBinary(OSS); OSS.flush(); Data.assign(Str.begin(), Str.end()); return Data; } BinaryRef Binary; }; static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj, YamlContext &Context) { Io.mapRequired("mode", Obj.Mode); Io.mapRequired("key", Obj.Key, Context); Io.mapRequired("cpu_name", Obj.CpuName); Io.mapRequired("llvm_triple", Obj.LLVMTriple); Io.mapRequired("num_repetitions", Obj.NumRepetitions); Io.mapRequired("measurements", Obj.Measurements); Io.mapRequired("error", Obj.Error); Io.mapOptional("info", Obj.Info); // AssembledSnippet MappingNormalization<NormalizedBinary, std::vector<uint8_t>> BinaryString( Io, Obj.AssembledSnippet); Io.mapOptional("assembled_snippet", BinaryString->Binary); } }; } // namespace yaml namespace exegesis { llvm::Expected<InstructionBenchmark> InstructionBenchmark::readYaml(const LLVMState &State, llvm::StringRef Filename) { if (auto ExpectedMemoryBuffer = llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) { llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); InstructionBenchmark Benchmark; if (Yin.setCurrentDocument()) llvm::yaml::yamlize(Yin, Benchmark, /*unused*/ true, Context); if (!Context.getLastError().empty()) return llvm::make_error<BenchmarkFailure>(Context.getLastError()); return Benchmark; } else { return ExpectedMemoryBuffer.takeError(); } } llvm::Expected<std::vector<InstructionBenchmark>> InstructionBenchmark::readYamls(const LLVMState &State, llvm::StringRef Filename) { if (auto ExpectedMemoryBuffer = llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) { llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); std::vector<InstructionBenchmark> Benchmarks; while (Yin.setCurrentDocument()) { Benchmarks.emplace_back(); yamlize(Yin, Benchmarks.back(), /*unused*/ true, Context); if (Yin.error()) return llvm::errorCodeToError(Yin.error()); if (!Context.getLastError().empty()) return llvm::make_error<BenchmarkFailure>(Context.getLastError()); Yin.nextDocument(); } return Benchmarks; } else { return ExpectedMemoryBuffer.takeError(); } } void InstructionBenchmark::writeYamlTo(const LLVMState &State, llvm::raw_ostream &OS) { llvm::yaml::Output Yout(OS); YamlContext Context(State); Yout.beginDocuments(); llvm::yaml::yamlize(Yout, *this, /*unused*/ true, Context); Yout.endDocuments(); } void InstructionBenchmark::readYamlFrom(const LLVMState &State, llvm::StringRef InputContent) { llvm::yaml::Input Yin(InputContent); YamlContext Context(State); if (Yin.setCurrentDocument()) llvm::yaml::yamlize(Yin, *this, /*unused*/ true, Context); } llvm::Error InstructionBenchmark::writeYaml(const LLVMState &State, const llvm::StringRef Filename) { if (Filename == "-") { writeYamlTo(State, llvm::outs()); } else { int ResultFD = 0; if (auto E = llvm::errorCodeToError( openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways, llvm::sys::fs::F_Text))) { return E; } llvm::raw_fd_ostream Ostr(ResultFD, true /*shouldClose*/); writeYamlTo(State, Ostr); } return llvm::Error::success(); } void PerInstructionStats::push(const BenchmarkMeasure &BM) { if (Key.empty()) Key = BM.Key; assert(Key == BM.Key); ++NumValues; SumValues += BM.PerInstructionValue; MaxValue = std::max(MaxValue, BM.PerInstructionValue); MinValue = std::min(MinValue, BM.PerInstructionValue); } } // namespace exegesis } // namespace llvm <commit_msg>[llvm-exegesis] Increasing wrapping limit.<commit_after>//===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BenchmarkResult.h" #include "BenchmarkRunner.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/bit.h" #include "llvm/ADT/StringRef.h" #include "llvm/ObjectYAML/YAML.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" static constexpr const char kIntegerPrefix[] = "i_0x"; static constexpr const char kDoublePrefix[] = "f_"; static constexpr const char kInvalidOperand[] = "INVALID"; namespace llvm { namespace { // A mutable struct holding an LLVMState that can be passed through the // serialization process to encode/decode registers and instructions. struct YamlContext { YamlContext(const exegesis::LLVMState &State) : State(&State), ErrorStream(LastError) {} void serializeMCInst(const llvm::MCInst &MCInst, llvm::raw_ostream &OS) { OS << getInstrName(MCInst.getOpcode()); for (const auto &Op : MCInst) { OS << ' '; serializeMCOperand(Op, OS); } } void deserializeMCInst(llvm::StringRef String, llvm::MCInst &Value) { llvm::SmallVector<llvm::StringRef, 8> Pieces; String.split(Pieces, " ", /* MaxSplit */ -1, /* KeepEmpty */ false); if (Pieces.empty()) { ErrorStream << "Unknown Instruction: '" << String << "'"; return; } bool ProcessOpcode = true; for (llvm::StringRef Piece : Pieces) { if (ProcessOpcode) Value.setOpcode(getInstrOpcode(Piece)); else Value.addOperand(deserializeMCOperand(Piece)); ProcessOpcode = false; } } std::string &getLastError() { return ErrorStream.str(); } llvm::raw_string_ostream &getErrorStream() { return ErrorStream; } llvm::StringRef getRegName(unsigned RegNo) { const llvm::StringRef RegName = State->getRegInfo().getName(RegNo); if (RegName.empty()) ErrorStream << "No register with enum value" << RegNo; return RegName; } unsigned getRegNo(llvm::StringRef RegName) { const llvm::MCRegisterInfo &RegInfo = State->getRegInfo(); for (unsigned E = RegInfo.getNumRegs(), I = 0; I < E; ++I) if (RegInfo.getName(I) == RegName) return I; ErrorStream << "No register with name " << RegName; return 0; } private: void serializeIntegerOperand(llvm::raw_ostream &OS, int64_t Value) { OS << kIntegerPrefix; OS.write_hex(llvm::bit_cast<uint64_t>(Value)); } bool tryDeserializeIntegerOperand(llvm::StringRef String, int64_t &Value) { if (!String.consume_front(kIntegerPrefix)) return false; return !String.consumeInteger(16, Value); } void serializeFPOperand(llvm::raw_ostream &OS, double Value) { OS << kDoublePrefix << llvm::format("%la", Value); } bool tryDeserializeFPOperand(llvm::StringRef String, double &Value) { if (!String.consume_front(kDoublePrefix)) return false; char *EndPointer = nullptr; Value = strtod(String.begin(), &EndPointer); return EndPointer == String.end(); } void serializeMCOperand(const llvm::MCOperand &MCOperand, llvm::raw_ostream &OS) { if (MCOperand.isReg()) { OS << getRegName(MCOperand.getReg()); } else if (MCOperand.isImm()) { serializeIntegerOperand(OS, MCOperand.getImm()); } else if (MCOperand.isFPImm()) { serializeFPOperand(OS, MCOperand.getFPImm()); } else { OS << kInvalidOperand; } } llvm::MCOperand deserializeMCOperand(llvm::StringRef String) { assert(!String.empty()); int64_t IntValue = 0; double DoubleValue = 0; if (tryDeserializeIntegerOperand(String, IntValue)) return llvm::MCOperand::createImm(IntValue); if (tryDeserializeFPOperand(String, DoubleValue)) return llvm::MCOperand::createFPImm(DoubleValue); if (unsigned RegNo = getRegNo(String)) return llvm::MCOperand::createReg(RegNo); if (String != kInvalidOperand) ErrorStream << "Unknown Operand: '" << String << "'"; return {}; } llvm::StringRef getInstrName(unsigned InstrNo) { const llvm::StringRef InstrName = State->getInstrInfo().getName(InstrNo); if (InstrName.empty()) ErrorStream << "No opcode with enum value" << InstrNo; return InstrName; } unsigned getInstrOpcode(llvm::StringRef InstrName) { const llvm::MCInstrInfo &InstrInfo = State->getInstrInfo(); for (unsigned E = InstrInfo.getNumOpcodes(), I = 0; I < E; ++I) if (InstrInfo.getName(I) == InstrName) return I; ErrorStream << "No opcode with name " << InstrName; return 0; } const llvm::exegesis::LLVMState *State; std::string LastError; llvm::raw_string_ostream ErrorStream; }; } // namespace // Defining YAML traits for IO. namespace yaml { static YamlContext &getTypedContext(void *Ctx) { return *reinterpret_cast<YamlContext *>(Ctx); } // std::vector<llvm::MCInst> will be rendered as a list. template <> struct SequenceElementTraits<llvm::MCInst> { static const bool flow = false; }; template <> struct ScalarTraits<llvm::MCInst> { static void output(const llvm::MCInst &Value, void *Ctx, llvm::raw_ostream &Out) { getTypedContext(Ctx).serializeMCInst(Value, Out); } static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) { YamlContext &Context = getTypedContext(Ctx); Context.deserializeMCInst(Scalar, Value); return Context.getLastError(); } // By default strings are quoted only when necessary. // We force the use of single quotes for uniformity. static QuotingType mustQuote(StringRef) { return QuotingType::Single; } static const bool flow = true; }; // std::vector<exegesis::Measure> will be rendered as a list. template <> struct SequenceElementTraits<exegesis::BenchmarkMeasure> { static const bool flow = false; }; // exegesis::Measure is rendererd as a flow instead of a list. // e.g. { "key": "the key", "value": 0123 } template <> struct MappingTraits<exegesis::BenchmarkMeasure> { static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) { Io.mapRequired("key", Obj.Key); if (!Io.outputting()) { // For backward compatibility, interpret debug_string as a key. Io.mapOptional("debug_string", Obj.Key); } Io.mapRequired("value", Obj.PerInstructionValue); Io.mapOptional("per_snippet_value", Obj.PerSnippetValue); } static const bool flow = true; }; template <> struct ScalarEnumerationTraits<exegesis::InstructionBenchmark::ModeE> { static void enumeration(IO &Io, exegesis::InstructionBenchmark::ModeE &Value) { Io.enumCase(Value, "", exegesis::InstructionBenchmark::Unknown); Io.enumCase(Value, "latency", exegesis::InstructionBenchmark::Latency); Io.enumCase(Value, "uops", exegesis::InstructionBenchmark::Uops); } }; // std::vector<exegesis::RegisterValue> will be rendered as a list. template <> struct SequenceElementTraits<exegesis::RegisterValue> { static const bool flow = false; }; template <> struct ScalarTraits<exegesis::RegisterValue> { static constexpr const unsigned kRadix = 16; static constexpr const bool kSigned = false; static void output(const exegesis::RegisterValue &RV, void *Ctx, llvm::raw_ostream &Out) { YamlContext &Context = getTypedContext(Ctx); Out << Context.getRegName(RV.Register) << "=0x" << RV.Value.toString(kRadix, kSigned); } static StringRef input(StringRef String, void *Ctx, exegesis::RegisterValue &RV) { llvm::SmallVector<llvm::StringRef, 2> Pieces; String.split(Pieces, "=0x", /* MaxSplit */ -1, /* KeepEmpty */ false); YamlContext &Context = getTypedContext(Ctx); if (Pieces.size() == 2) { RV.Register = Context.getRegNo(Pieces[0]); const unsigned BitsNeeded = llvm::APInt::getBitsNeeded(Pieces[1], kRadix); RV.Value = llvm::APInt(BitsNeeded, Pieces[1], kRadix); } else { Context.getErrorStream() << "Unknown initial register value: '" << String << "'"; } return Context.getLastError(); } static QuotingType mustQuote(StringRef) { return QuotingType::Single; } static const bool flow = true; }; template <> struct MappingContextTraits<exegesis::InstructionBenchmarkKey, YamlContext> { static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj, YamlContext &Context) { Io.setContext(&Context); Io.mapRequired("instructions", Obj.Instructions); Io.mapOptional("config", Obj.Config); Io.mapRequired("register_initial_values", Obj.RegisterInitialValues); } }; template <> struct MappingContextTraits<exegesis::InstructionBenchmark, YamlContext> { struct NormalizedBinary { NormalizedBinary(IO &io) {} NormalizedBinary(IO &, std::vector<uint8_t> &Data) : Binary(Data) {} std::vector<uint8_t> denormalize(IO &) { std::vector<uint8_t> Data; std::string Str; raw_string_ostream OSS(Str); Binary.writeAsBinary(OSS); OSS.flush(); Data.assign(Str.begin(), Str.end()); return Data; } BinaryRef Binary; }; static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj, YamlContext &Context) { Io.mapRequired("mode", Obj.Mode); Io.mapRequired("key", Obj.Key, Context); Io.mapRequired("cpu_name", Obj.CpuName); Io.mapRequired("llvm_triple", Obj.LLVMTriple); Io.mapRequired("num_repetitions", Obj.NumRepetitions); Io.mapRequired("measurements", Obj.Measurements); Io.mapRequired("error", Obj.Error); Io.mapOptional("info", Obj.Info); // AssembledSnippet MappingNormalization<NormalizedBinary, std::vector<uint8_t>> BinaryString( Io, Obj.AssembledSnippet); Io.mapOptional("assembled_snippet", BinaryString->Binary); } }; } // namespace yaml namespace exegesis { llvm::Expected<InstructionBenchmark> InstructionBenchmark::readYaml(const LLVMState &State, llvm::StringRef Filename) { if (auto ExpectedMemoryBuffer = llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) { llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); InstructionBenchmark Benchmark; if (Yin.setCurrentDocument()) llvm::yaml::yamlize(Yin, Benchmark, /*unused*/ true, Context); if (!Context.getLastError().empty()) return llvm::make_error<BenchmarkFailure>(Context.getLastError()); return Benchmark; } else { return ExpectedMemoryBuffer.takeError(); } } llvm::Expected<std::vector<InstructionBenchmark>> InstructionBenchmark::readYamls(const LLVMState &State, llvm::StringRef Filename) { if (auto ExpectedMemoryBuffer = llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) { llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get()); YamlContext Context(State); std::vector<InstructionBenchmark> Benchmarks; while (Yin.setCurrentDocument()) { Benchmarks.emplace_back(); yamlize(Yin, Benchmarks.back(), /*unused*/ true, Context); if (Yin.error()) return llvm::errorCodeToError(Yin.error()); if (!Context.getLastError().empty()) return llvm::make_error<BenchmarkFailure>(Context.getLastError()); Yin.nextDocument(); } return Benchmarks; } else { return ExpectedMemoryBuffer.takeError(); } } void InstructionBenchmark::writeYamlTo(const LLVMState &State, llvm::raw_ostream &OS) { llvm::yaml::Output Yout(OS, nullptr /*Ctx*/, 200 /*WrapColumn*/); YamlContext Context(State); Yout.beginDocuments(); llvm::yaml::yamlize(Yout, *this, /*unused*/ true, Context); Yout.endDocuments(); } void InstructionBenchmark::readYamlFrom(const LLVMState &State, llvm::StringRef InputContent) { llvm::yaml::Input Yin(InputContent); YamlContext Context(State); if (Yin.setCurrentDocument()) llvm::yaml::yamlize(Yin, *this, /*unused*/ true, Context); } llvm::Error InstructionBenchmark::writeYaml(const LLVMState &State, const llvm::StringRef Filename) { if (Filename == "-") { writeYamlTo(State, llvm::outs()); } else { int ResultFD = 0; if (auto E = llvm::errorCodeToError( openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways, llvm::sys::fs::F_Text))) { return E; } llvm::raw_fd_ostream Ostr(ResultFD, true /*shouldClose*/); writeYamlTo(State, Ostr); } return llvm::Error::success(); } void PerInstructionStats::push(const BenchmarkMeasure &BM) { if (Key.empty()) Key = BM.Key; assert(Key == BM.Key); ++NumValues; SumValues += BM.PerInstructionValue; MaxValue = std::max(MaxValue, BM.PerInstructionValue); MinValue = std::min(MinValue, BM.PerInstructionValue); } } // namespace exegesis } // namespace llvm <|endoftext|>
<commit_before><commit_msg>[DF] Add test for ROOT-9558<commit_after><|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <pthread.h> //#include "carbon_user.h" #include <time.h> #include <sys/timeb.h> #define MAX 100000000 #define INT_MAX 100000000 // #define DEBUG 1 #define BILLION 1E9 int _W[8][8] = { {0, 2, 1, 17, MAX, MAX, MAX, MAX}, {2, 0, MAX, MAX, 2, 6, MAX, MAX}, {1, MAX, 0, MAX, MAX, MAX, MAX, 8}, {17, MAX, MAX, 0, MAX, 2, 1, 9}, {MAX, 2, MAX, MAX, 0, 4, MAX, MAX}, {MAX, 6, MAX, 2, 4, 0, 5, MAX}, {MAX, MAX, MAX, 1, MAX, 5, 0, 3}, {MAX, MAX, 8, 9, MAX, MAX, 3, 0} }; int min = INT_MAX; int min_index = 0; pthread_mutex_t lock; pthread_mutex_t locks[4194304]; int u = 0; void init_weights(int N, int DEG, int** W, int** W_index) { int range = DEG + (N - DEG)/16; // Initialize to -1 for(int i = 0; i < N; i++) for(int j = 0; j < DEG; j++) W_index[i][j]= -1; // Populate Index Array for(int i = 0; i < N; i++) { int last = 0; int min = 0; int max = DEG; for(int j = 0; j < DEG; j++) { if(W_index[i][j] == -1) { int neighbor = i+j; //W_index[i][j] = i+j;//rand()%(DEG); if(neighbor > last) { W_index[i][j] = neighbor; last = W_index[i][j]; } else { if(last < (N-1)) { W_index[i][j] = (last + 1); last = W_index[i][j]; } } } else { last = W_index[i][j]; } if(W_index[i][j]>=N) { W_index[i][j] = N-1; } } } // Populate Cost Array for(int i = 0; i < N; i++) { for(int j = 0; j < DEG; j++) { double v = drand48(); /*if(v > 0.8 || W_index[i][j] == -1) { W[i][j] = MAX; W_index[i][j] = -1; } else*/ if(W_index[i][j] == i) W[i][j] = 0; else W[i][j] = (int) (v*100) + 1; //printf(" %d ",W_index[i][j]); } //printf("\n"); } } int initialize_single_source(int* D, int* Q, int source, int N); void relax(int u, int i, volatile int* D, int** W, int** W_index, int N); int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u); typedef struct { int* local_min; int* global_min; int* Q; int* D; //int** W; int** W_index; int* d_count; int tid; int P; int N; int DEG; pthread_barrier_t* barrier_total; pthread_barrier_t* barrier; } thread_arg_t; int local_min_buffer[1024]; int Total_tid[1024] = {0}; int global_min_buffer; int terminate = 0; int range=1; int old_range =1; int difference=0; int pid=0; int start = 64; int P_global = 256; int change = 0; int *test; int *test1; long long Total = 0; thread_arg_t thread_arg[1024]; pthread_t thread_handle[1024]; void* do_work(void* args) { volatile thread_arg_t* arg = (thread_arg_t*) args; volatile int* count = arg->d_count; volatile int* global_min = arg->global_min; volatile int* local_min = arg->local_min; int tid = arg->tid; int P = arg->P; volatile int* Q = arg->Q; int* D = arg->D; //int** W = arg->W; int** W_index = arg->W_index; const int N = arg->N; const int DEG = arg->DEG; int local_count = N; int i, j, po; int uu = 0; P = start; int a = 0; int start = 0; //tid * DEG / (arg->P); int stop = 0; //(tid+1) * DEG / (arg->P); start = tid * (N) / (P); stop = (tid+1) * (N) / (P); pthread_barrier_wait(arg->barrier_total); for(uu=start;uu<stop;uu++) { if(test1[uu]==1) { for(int i = 0; i < DEG; i++) { int neighbor = W_index[uu][i]; if(neighbor>=N) continue; pthread_mutex_lock(&locks[neighbor]); if(uu>=N) terminate=1; D[W_index[uu][i]]++; Q[W_index[uu][i]] = 0; pthread_mutex_unlock(&locks[neighbor]); } } } pthread_barrier_wait(arg->barrier_total); for(uu=start;uu<stop;uu++) { if(test1[uu]==1){ unsigned int ret = -1; /*while (D[uu] != 0) { D[uu] >>= 1; ret++; }*/ ret = D[uu]/3; D[uu]=ret; if(D[uu]>=1) { //pthread_mutex_lock(&lock); Total_tid[tid] = Total_tid[tid]+D[uu]; //pthread_mutex_unlock(&lock); } } } pthread_barrier_wait(arg->barrier_total); if(tid==0) { for(int i=0;i<P;i++) { Total = Total + Total_tid[i]; } } pthread_barrier_wait(arg->barrier_total); return NULL; } int main(int argc, char** argv) { //int mul = W_index[0][0]; // Start the simulator //CarbonStartSim(argc, argv); char filename[100]; printf("Please Enter The Name Of The File You Would Like To Fetch\n"); scanf("%s", filename); FILE *file0 = fopen(filename,"r"); int lines_to_check=0; char c; int number0; int number1; int starting_node = 0; int previous_node = 0; int check = 0; int inter = -1; int N = 2097152; //can be read from file if needed, this is a default upper limit int DEG = 12; //also can be reda from file if needed, upper limit here again const int P1 = atoi(argv[1]); int P = P1; P_global = P1; start = P1; //change = change1; old_range = change; range = change; if (DEG > N) { fprintf(stderr, "Degree of graph cannot be grater than number of Vertices\n"); exit(EXIT_FAILURE); } int* D; int* Q; posix_memalign((void**) &D, 64, N * sizeof(int)); posix_memalign((void**) &Q, 64, N * sizeof(int)); posix_memalign((void**) &test, 64, N * sizeof(int)); posix_memalign((void**) &test1, 64, N * sizeof(int)); int d_count = N; pthread_barrier_t barrier_total; pthread_barrier_t barrier; //int** W = (int**) malloc(N*sizeof(int*)); int** W_index = (int**) malloc(N*sizeof(int*)); for(int i = 0; i < N; i++) { //W[i] = (int *)malloc(sizeof(int)*N); //int ret = posix_memalign((void**) &W[i], 64, DEG*sizeof(int)); int re1 = posix_memalign((void**) &W_index[i], 64, DEG*sizeof(int)); if (re1!=0) { fprintf(stderr, "Could not allocate memory\n"); exit(EXIT_FAILURE); } } printf("\nRead"); for(int i=0;i<N;i++) { for(int j=0;j<DEG;j++) { //W[i][j] = 1000000000; W_index[i][j] = INT_MAX; } test[i]=0; test1[i]=0; } for(c=getc(file0); c!=EOF; c=getc(file0)) { if(c=='\n') lines_to_check++; if(lines_to_check>3) { fscanf(file0, "%d %d", &number0,&number1); //printf("\n%d %d",number0,number1); inter = test[number0]; //W[number0][inter] = drand48(); W_index[number0][inter] = number1; //previous_node = number0; test[number0]++; test1[number0]=1; test1[number1]=1; } } printf("\nFile Read"); //init_weights(N, DEG, W, W_index); /*for(int i = 0;i<100;i++) { for(int j = 0;j<4;j++) { printf(" %d ",W_index[i][j]); } printf("\n"); }*/ pthread_barrier_init(&barrier_total, NULL, P); pthread_barrier_init(&barrier, NULL, P); pthread_mutex_init(&lock, NULL); for(int i=0; i<2097152; i++) pthread_mutex_init(&locks[i], NULL); initialize_single_source(D, Q, 0, N); for(int j = 0; j < P; j++) { thread_arg[j].local_min = local_min_buffer; thread_arg[j].global_min = &global_min_buffer; thread_arg[j].Q = Q; thread_arg[j].D = D; //thread_arg[j].W = W; thread_arg[j].W_index = W_index; thread_arg[j].d_count = &d_count; thread_arg[j].tid = j; thread_arg[j].P = P; thread_arg[j].N = N; thread_arg[j].DEG = DEG; thread_arg[j].barrier_total = &barrier_total; thread_arg[j].barrier = &barrier; } int mul = 2; // Enable performance and energy models //CarbonEnableModels(); struct timespec requestStart, requestEnd; clock_gettime(CLOCK_REALTIME, &requestStart); for(int j = 1; j < P; j++) { pthread_create(thread_handle+j, NULL, do_work, (void*)&thread_arg[j]); } do_work((void*) &thread_arg[0]); printf("Threads Returned!"); for(int j = 1; j < P; j++) { //mul = mul*2; pthread_join(thread_handle[j],NULL); } printf("Threads Joined!"); clock_gettime(CLOCK_REALTIME, &requestEnd); double accum = ( requestEnd.tv_sec - requestStart.tv_sec ) + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / BILLION; printf( "%lf\n", accum ); // Enable performance and energy models //CarbonDisableModels(); //printf("\ndistance:%d \n",D[N-1]); printf("%d",Total); //for(int i = 0; i < N; i++) { // printf(" %d ", D[i]); //} //printf("\n"); printf("\n TOTAL=%d",Total); // Stop the simulator //CarbonStopSim(); return 0; } int initialize_single_source(int* D, int* Q, int source, int N) { for(int i = 0; i < N+1; i++) { D[i] = 0; Q[i] = 1; } //D[source] = 0; return 0; } int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u) { int min = INT_MAX; int min_index = N; for(int i = start; i < stop; i++) { if(W_index[u][i]==-1 || W[u][i]==INT_MAX) continue; if(D[i] < min && Q[i]) { min = D[i]; min_index = W_index[u][i]; } } return min_index; } void relax(int u, int i, volatile int* D, int** W, int** W_index, int N) { if((D[W_index[u][i]] > (D[u] + W[u][i]) && (W_index[u][i]!=-1 && W_index[u][i]<N && W[u][i]!=INT_MAX))) D[W_index[u][i]] = D[u] + W[u][i]; } <commit_msg>updated tri<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: localedatawrapper.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: er $ $Date: 2001-07-09 17:49:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #define _UNOTOOLS_LOCALEDATAWRAPPER_HXX #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> // enum MeasurementSystem, enum DateFormat #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_ #include <com/sun/star/i18n/XLocaleData.hpp> #endif #ifndef _COM_SUN_STAR_I18N_LOCALEITEM_HPP_ #include <com/sun/star/i18n/LocaleItem.hpp> #endif #ifndef _COM_SUN_STAR_I18N_RESERVEDWORDS_HPP_ #include <com/sun/star/i18n/reservedWords.hpp> #endif #ifndef INCLUDED_UNOTOOLS_READWRITEMUTEXGUARD_HXX #include <unotools/readwritemutexguard.hxx> #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } }}} class Date; class Time; class CalendarWrapper; class LocaleDataWrapper { static ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > xInstalledLocales; static ::com::sun::star::uno::Sequence< sal_uInt16 > xInstalledLanguageTypes; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData > xLD; ::com::sun::star::lang::Locale aLocale; ::com::sun::star::i18n::LocaleDataItem aLocaleDataItem; ::com::sun::star::uno::Sequence< ::rtl::OUString > aReservedWordSeq; // cached items String aLocaleItem[::com::sun::star::i18n::LocaleItem::COUNT]; String aReservedWord[::com::sun::star::i18n::reservedWords::COUNT]; String aCurrSymbol; String aCurrBankSymbol; int nDateFormat; int nLongDateFormat; USHORT nCurrPositiveFormat; USHORT nCurrNegativeFormat; USHORT nCurrDigits; BOOL bLocaleDataItemValid; BOOL bReservedWordValid; mutable ::utl::ReadWriteMutex aMutex; // dummies, to be implemented or provided by XML locale data sal_Unicode cCurrZeroChar; // not implemented, prevent usage LocaleDataWrapper( const LocaleDataWrapper& ); LocaleDataWrapper& operator=( const LocaleDataWrapper& ); // whenever Locale changes void invalidateData(); void getOneLocaleItemImpl( sal_Int16 nItem ); const String& getOneLocaleItem( sal_Int16 nItem ) const; void getOneReservedWordImpl( sal_Int16 nWord ); const String& getOneReservedWord( sal_Int16 nWord ) const; void getCurrSymbolsImpl(); void getCurrFormatsImpl(); void scanCurrFormatImpl( const String& rCode, xub_StrLen nStart, xub_StrLen& nSign, xub_StrLen& nPar, xub_StrLen& nNum, xub_StrLen& nBlank, xub_StrLen& nSym ); void getDateFormatsImpl(); DateFormat scanDateFormatImpl( const String& rCode ); sal_Unicode* ImplAddFormatNum( sal_Unicode* pBuf, long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const; public: LocaleDataWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF, const ::com::sun::star::lang::Locale& rLocale ); ~LocaleDataWrapper(); /// set a new Locale to request void setLocale( const ::com::sun::star::lang::Locale& rLocale ); /// get current requested Locale const ::com::sun::star::lang::Locale& getLocale() const; /// get current loaded Locale, which might differ from the requested Locale ::com::sun::star::lang::Locale getLoadedLocale() const; // Wrapper implementations of class LocaleData ::com::sun::star::i18n::LanguageCountryInfo getLanguageCountryInfo() const; ::com::sun::star::i18n::LocaleDataItem getLocaleItem() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Calendar > getAllCalendars() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Currency > getAllCurrencies() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::FormatElement > getAllFormats() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Implementation > getCollatorImplementations() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getTransliterations() const; ::com::sun::star::i18n::ForbiddenCharacters getForbiddenCharacters() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getReservedWord() const; ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > getAllInstalledLocaleNames() const; /// same as the wrapper implementation but static static ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > getInstalledLocaleNames(); /** Get LanguageTypes for all installed locales which are unambiguous convertible back and forth between locale ISO strings and MS-LCID LanguageType. Upon the first time the function is called in a non-PRODUCT version debug messages are shown for locales not matching, excluding already known problems. (e.g. used in number formatter dialog init) */ static ::com::sun::star::uno::Sequence< sal_uInt16 > getInstalledLanguageTypes(); /// maps the LocaleData string to the International enum MeasurementSystem mapMeasurementStringToEnum( const String& rMS ) const; // Functionality of class International methods, LocaleItem inline const String& getDateSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DATE_SEPARATOR ); } inline const String& getNumThousandSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::THOUSAND_SEPARATOR ); } inline const String& getNumDecimalSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DECIMAL_SEPARATOR ); } inline const String& getTimeSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_SEPARATOR ); } inline const String& getTime100SecSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_100SEC_SEPARATOR ); } inline const String& getListSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LIST_SEPARATOR ); } inline const String& getQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_START ); } inline const String& getQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_END ); } inline const String& getDoubleQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_START ); } inline const String& getDoubleQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_END ); } inline const String& getMeasurementSystem() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ); } inline MeasurementSystem getMeasurementSystemEnum() const { return mapMeasurementStringToEnum( getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ) ); } inline const String& getTimeAM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_AM ); } inline const String& getTimePM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_PM ); } inline const String& getLongDateDayOfWeekSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_OF_WEEK_SEPARATOR ); } inline const String& getLongDateDaySep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_SEPARATOR ); } inline const String& getLongDateMonthSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_MONTH_SEPARATOR ); } inline const String& getLongDateYearSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_YEAR_SEPARATOR ); } // currency const String& getCurrSymbol() const; const String& getCurrBankSymbol() const; USHORT getCurrPositiveFormat() const; USHORT getCurrNegativeFormat() const; USHORT getCurrDigits() const; // simple date and time formatting DateFormat getDateFormat() const; DateFormat getLongDateFormat() const; /// only numerical values of Gregorian calendar String getDate( const Date& rDate ) const; String getTime( const Time& rTime, BOOL bSec = TRUE, BOOL b100Sec = FALSE ) const; String getDuration( const Time& rTime, BOOL bSec = TRUE, BOOL b100Sec = FALSE ) const; /** The CalendarWrapper already <b>MUST</b> have loaded a calendar. @param nDisplayDayOfWeek 0 := abbreviated name 1 := full name @param bDayOfMonthWithLeadingZero <FALSE/> := without leading zero <TRUE/> := with leading zero if <10 @param nDisplayMonth 0 := abbreviated name 1 := full name @param bTwoDigitYear <FALSE/> := full year <TRUE/> := year % 100 */ String getLongDate( const Date& rDate, CalendarWrapper& rCal, sal_Int16 nDisplayDayOfWeek = 1, sal_Bool bDayOfMonthWithLeadingZero = sal_False, sal_Int16 nDisplayMonth = 1, sal_Bool bTwoDigitYear = sal_False ) const; #if SUPD >= 638 /** Simple number formatting @param nNumber value * 10**nDecimals @param bTrailingZeros </TRUE> := always display trailing zeros in decimal places, even if integer value. </FALSE> := trailing zeros are only displayed if the value is not an integer value. */ String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE, BOOL bTrailingZeros = TRUE ) const; #else String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE ) const; String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const; #endif /// "Secure" currency formatted string. String getCurr( long nNumber, USHORT nDecimals, const String& rCurrencySymbol, BOOL bUseThousandSep = TRUE ) const; /** Default currency formatted string, use with care as default currency may change in any locale, for example, DEM -> EUR */ String getCurr( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE ) const { return getCurr( nNumber, nDecimals, getCurrSymbol(), bUseThousandSep ); } // dummy returns, to be implemented inline sal_Unicode getCurrZeroChar() const { return cCurrZeroChar; } inline BOOL isNumLeadingZero() const { return TRUE; } // reserved words inline const String& getTrueWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::TRUE_WORD ); } inline const String& getFalseWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::FALSE_WORD ); } /// return a quarter string matching nQuarter (0..3) => "1st quarter" .. "4th quarter" inline const String& getQuarterWord( sal_Int16 nQuarter ) const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::QUARTER1_WORD + nQuarter ); } inline const String& getAboveWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::ABOVE_WORD ); } inline const String& getBelowWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::BELOW_WORD ); } #ifndef PRODUCT ByteString& AppendLocaleInfo( ByteString& rDebugMsg ) const; #endif }; #endif // _UNOTOOLS_LOCALEDATAWRAPPER_HXX <commit_msg>#94368# get rid of class International<commit_after>/************************************************************************* * * $RCSfile: localedatawrapper.hxx,v $ * * $Revision: 1.19 $ * * last change: $Author: er $ $Date: 2001-11-23 19:31:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #define _UNOTOOLS_LOCALEDATAWRAPPER_HXX #ifndef _TOOLS_INTN_HXX #include <tools/intn.hxx> // enum MeasurementSystem, enum DateFormat #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_ #include <com/sun/star/i18n/XLocaleData.hpp> #endif #ifndef _COM_SUN_STAR_I18N_LOCALEITEM_HPP_ #include <com/sun/star/i18n/LocaleItem.hpp> #endif #ifndef _COM_SUN_STAR_I18N_RESERVEDWORDS_HPP_ #include <com/sun/star/i18n/reservedWords.hpp> #endif #ifndef INCLUDED_UNOTOOLS_READWRITEMUTEXGUARD_HXX #include <unotools/readwritemutexguard.hxx> #endif namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } }}} class Date; class Time; class CalendarWrapper; class LocaleDataWrapper { static ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > xInstalledLocales; static ::com::sun::star::uno::Sequence< sal_uInt16 > xInstalledLanguageTypes; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData > xLD; ::com::sun::star::lang::Locale aLocale; ::com::sun::star::i18n::LocaleDataItem aLocaleDataItem; ::com::sun::star::uno::Sequence< ::rtl::OUString > aReservedWordSeq; // cached items String aLocaleItem[::com::sun::star::i18n::LocaleItem::COUNT]; String aReservedWord[::com::sun::star::i18n::reservedWords::COUNT]; String aCurrSymbol; String aCurrBankSymbol; int nDateFormat; int nLongDateFormat; USHORT nCurrPositiveFormat; USHORT nCurrNegativeFormat; USHORT nCurrDigits; BOOL bLocaleDataItemValid; BOOL bReservedWordValid; mutable ::utl::ReadWriteMutex aMutex; // dummies, to be implemented or provided by XML locale data sal_Unicode cCurrZeroChar; // not implemented, prevent usage LocaleDataWrapper( const LocaleDataWrapper& ); LocaleDataWrapper& operator=( const LocaleDataWrapper& ); // whenever Locale changes void invalidateData(); void getOneLocaleItemImpl( sal_Int16 nItem ); const String& getOneLocaleItem( sal_Int16 nItem ) const; void getOneReservedWordImpl( sal_Int16 nWord ); const String& getOneReservedWord( sal_Int16 nWord ) const; void getCurrSymbolsImpl(); void getCurrFormatsImpl(); void scanCurrFormatImpl( const String& rCode, xub_StrLen nStart, xub_StrLen& nSign, xub_StrLen& nPar, xub_StrLen& nNum, xub_StrLen& nBlank, xub_StrLen& nSym ); void getDateFormatsImpl(); DateFormat scanDateFormatImpl( const String& rCode ); sal_Unicode* ImplAddFormatNum( sal_Unicode* pBuf, long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const; public: LocaleDataWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF, const ::com::sun::star::lang::Locale& rLocale ); ~LocaleDataWrapper(); /// set a new Locale to request void setLocale( const ::com::sun::star::lang::Locale& rLocale ); /// get current requested Locale const ::com::sun::star::lang::Locale& getLocale() const; /// get current loaded Locale, which might differ from the requested Locale ::com::sun::star::lang::Locale getLoadedLocale() const; // Wrapper implementations of class LocaleData ::com::sun::star::i18n::LanguageCountryInfo getLanguageCountryInfo() const; ::com::sun::star::i18n::LocaleDataItem getLocaleItem() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Calendar > getAllCalendars() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Currency > getAllCurrencies() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::FormatElement > getAllFormats() const; ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::Implementation > getCollatorImplementations() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getTransliterations() const; ::com::sun::star::i18n::ForbiddenCharacters getForbiddenCharacters() const; ::com::sun::star::uno::Sequence< ::rtl::OUString > getReservedWord() const; ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > getAllInstalledLocaleNames() const; /// same as the wrapper implementation but static static ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > getInstalledLocaleNames(); /** Get LanguageTypes for all installed locales which are unambiguous convertible back and forth between locale ISO strings and MS-LCID LanguageType. Upon the first time the function is called in a non-PRODUCT version debug messages are shown for locales not matching, excluding already known problems. (e.g. used in number formatter dialog init) */ static ::com::sun::star::uno::Sequence< sal_uInt16 > getInstalledLanguageTypes(); /// maps the LocaleData string to the International enum MeasurementSystem mapMeasurementStringToEnum( const String& rMS ) const; // Functionality of class International methods, LocaleItem inline const String& getDateSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DATE_SEPARATOR ); } inline const String& getNumThousandSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::THOUSAND_SEPARATOR ); } inline const String& getNumDecimalSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DECIMAL_SEPARATOR ); } inline const String& getTimeSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_SEPARATOR ); } inline const String& getTime100SecSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_100SEC_SEPARATOR ); } inline const String& getListSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LIST_SEPARATOR ); } inline const String& getQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_START ); } inline const String& getQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::SINGLE_QUOTATION_END ); } inline const String& getDoubleQuotationMarkStart() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_START ); } inline const String& getDoubleQuotationMarkEnd() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::DOUBLE_QUOTATION_END ); } inline const String& getMeasurementSystem() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ); } inline MeasurementSystem getMeasurementSystemEnum() const { return mapMeasurementStringToEnum( getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::MEASUREMENT_SYSTEM ) ); } inline const String& getTimeAM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_AM ); } inline const String& getTimePM() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::TIME_PM ); } inline const String& getLongDateDayOfWeekSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_OF_WEEK_SEPARATOR ); } inline const String& getLongDateDaySep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_DAY_SEPARATOR ); } inline const String& getLongDateMonthSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_MONTH_SEPARATOR ); } inline const String& getLongDateYearSep() const { return getOneLocaleItem( ::com::sun::star::i18n::LocaleItem::LONG_DATE_YEAR_SEPARATOR ); } // currency const String& getCurrSymbol() const; const String& getCurrBankSymbol() const; USHORT getCurrPositiveFormat() const; USHORT getCurrNegativeFormat() const; USHORT getCurrDigits() const; // simple date and time formatting DateFormat getDateFormat() const; DateFormat getLongDateFormat() const; /// only numerical values of Gregorian calendar String getDate( const Date& rDate ) const; String getTime( const Time& rTime, BOOL bSec = TRUE, BOOL b100Sec = FALSE ) const; String getDuration( const Time& rTime, BOOL bSec = TRUE, BOOL b100Sec = FALSE ) const; /** The CalendarWrapper already <b>MUST</b> have loaded a calendar. @param nDisplayDayOfWeek 0 := abbreviated name 1 := full name @param bDayOfMonthWithLeadingZero <FALSE/> := without leading zero <TRUE/> := with leading zero if <10 @param nDisplayMonth 0 := abbreviated name 1 := full name @param bTwoDigitYear <FALSE/> := full year <TRUE/> := year % 100 */ String getLongDate( const Date& rDate, CalendarWrapper& rCal, sal_Int16 nDisplayDayOfWeek = 1, sal_Bool bDayOfMonthWithLeadingZero = sal_False, sal_Int16 nDisplayMonth = 1, sal_Bool bTwoDigitYear = sal_False ) const; #if SUPD >= 638 /** Simple number formatting @param nNumber value * 10**nDecimals @param bTrailingZeros </TRUE> := always display trailing zeros in decimal places, even if integer value. </FALSE> := trailing zeros are only displayed if the value is not an integer value. */ String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE, BOOL bTrailingZeros = TRUE ) const; #else String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE ) const; String getNum( long nNumber, USHORT nDecimals, BOOL bUseThousandSep, BOOL bTrailingZeros ) const; #endif /// "Secure" currency formatted string. String getCurr( long nNumber, USHORT nDecimals, const String& rCurrencySymbol, BOOL bUseThousandSep = TRUE ) const; /** Default currency formatted string, use with care as default currency may change in any locale, for example, DEM -> EUR */ String getCurr( long nNumber, USHORT nDecimals, BOOL bUseThousandSep = TRUE ) const { return getCurr( nNumber, nDecimals, getCurrSymbol(), bUseThousandSep ); } // dummy returns, to be implemented inline sal_Unicode getCurrZeroChar() const { return cCurrZeroChar; } inline BOOL isNumLeadingZero() const { return TRUE; } /// standard decimal places inline USHORT getNumDigits() const { return 2; } inline BOOL isNumTrailingZeros() const { return TRUE; } // reserved words inline const String& getTrueWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::TRUE_WORD ); } inline const String& getFalseWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::FALSE_WORD ); } /// return a quarter string matching nQuarter (0..3) => "1st quarter" .. "4th quarter" inline const String& getQuarterWord( sal_Int16 nQuarter ) const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::QUARTER1_WORD + nQuarter ); } inline const String& getAboveWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::ABOVE_WORD ); } inline const String& getBelowWord() const { return getOneReservedWord( ::com::sun::star::i18n::reservedWords::BELOW_WORD ); } #ifndef PRODUCT ByteString& AppendLocaleInfo( ByteString& rDebugMsg ) const; #endif }; #endif // _UNOTOOLS_LOCALEDATAWRAPPER_HXX <|endoftext|>
<commit_before>#include "translator.hpp" #include "decl.hpp" #include "type.hpp" #include "context.hpp" #include "expr.hpp" #include "action.hpp" #include "dumper.hpp" #include <string> // for testing only #include <iostream> #include <sstream> namespace pip { translator::translator(context& cxt) : cxt(cxt) { } /// program ::= (pip <decl-seq>) decl* translator::trans_program(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; match_list(list, "pip", &decls); return new program_decl(std::move(decls)); } sexpr::throw_unexpected_term(e); } /// decl-seq ::= (<decl*>) decl_seq translator::trans_decls(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; // for (const sexpr::expr* elem : list->exprs) { decl* d = trans_decl(list); decls.push_back(d); // } return decls; } sexpr::throw_unexpected_term(e); } /// decl ::= table-decl | meter-decl decl* translator::trans_decl(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "table") return trans_table(list); sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0])); } sexpr::throw_unexpected_term(e); } /// table-decl ::= (table id <match-kind> <match-seq>) /// /// rule-kind ::= exact | prefix | wildcard | range /// /// FIXME: We actually need parse the key extraction program. This /// would be a sequence of actions that bits from the current offset /// into a "key register". decl* translator::trans_table(const sexpr::list_expr* e) { symbol* id; symbol* kind; action_seq actions; rule_seq rules; match_list(e, "table", &id, &kind, &actions, &rules); // TODO: Actually parse the kind of match. For now, we can simply // assume that all tables are exact. Hint: use the match_list framework // to return a match kind. return new table_decl(id, rk_exact, std::move(actions), std::move(rules)); } /// rule_seq ::= (<rule*>) rule_seq translator::trans_rules(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { match_list(list, "rules"); rule_seq rules; // Match each element in turn. for(const sexpr::expr* el : list->exprs) { // We are only interested in the entire sublists contained within list, // not its individual expressions. if(const sexpr::list_expr* r = as<sexpr::list_expr>(el)) { rule* r1 = trans_rule(r); rules.push_back(r1); } } return rules; } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; expr* key; action_seq actions; match_list(list, &key, &actions); return new rule(rk_exact, key, std::move(actions)); } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::list_expr* e) { expr_seq exprs; expr* key; action_seq actions; match_list(e, "rule", &key, &actions); return new rule(rk_exact, key, std::move(actions)); } action_seq translator::trans_actions(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { match_list(list, "actions"); action_seq actions; for(const sexpr::expr* el : list->exprs) { // We are only interested in the entire sublists contained within list, // not its individual expressions. if(const sexpr::list_expr* a = as<sexpr::list_expr>(el)) { action* a1 = trans_action(a); actions.push_back(a1); } // action* a = trans_action(list); // actions.push_back(a); } return actions; } sexpr::throw_unexpected_term(e); } // TODO: parse extra information (i.e. expr to output for output_action). action* translator::trans_action(const sexpr::list_expr* e) { symbol* action_name; expr_seq exprs; int i; match_list(e, &action_name); if(*action_name == "advance") return cxt.make_action(ak_advance); if(*action_name == "copy") return cxt.make_action(ak_copy); if(*action_name == "set") return cxt.make_action(ak_set); if(*action_name == "write") { action* a; match_list(e, "write", &a); return cxt.make_action(ak_write, nullptr, nullptr, a); } if(*action_name == "clear") return cxt.make_action(ak_clear); if( *action_name == "drop" ) return cxt.make_action(ak_drop); if( *action_name == "match" ) return cxt.make_action(ak_match); if( *action_name == "goto" ) { expr* dst; match_list(e, "goto", &dst); return cxt.make_action(ak_goto, dst); } if( *action_name == "output" ) { expr* dst; match_list(e, "output", &dst); return cxt.make_action(ak_output, dst); } sexpr::throw_unexpected_term(e); } expr* translator::trans_expr(const sexpr::expr* e) { // Match bare integer literals. // TODO: match int width // if (const sexpr::int_expr* num = as<sexpr::int_expr>(e)) // return trans_int_expr(num, 32); // Match bare keyword literals. // if (const sexpr::id_expr* id = as<sexpr::id_expr>(e)) { // if (*id->id == "miss") // return trans_miss_expr(id); // } // Match phrases. // // FIXME: Use a lookup table + switch. if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "int") return trans_int_expr(list); if (*sym == "wildcard") return trans_wild_expr(list); if (*sym == "range") return trans_range_expr(list); if (*sym == "port") return trans_port_expr(list); if (*sym == "offset") return trans_offset_expr(list); if (*sym == "miss") return trans_miss_expr(); } } expr_seq translator::trans_exprs(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; for (const sexpr::expr* elem : list->exprs) { expr* e = trans_expr(elem); exprs.push_back(e); } return exprs; } sexpr::throw_unexpected_term(e); } expr* translator::trans_range_expr(const sexpr::list_expr* e) { expr* lo; expr* hi; match_list(e, "range", &lo, &hi); auto lo_expr = as<int_expr>(lo); auto hi_expr = as<int_expr>(hi); auto lo_val = lo_expr->val; auto hi_val = hi_expr->val; auto lo_ty = static_cast<int_type*>(lo_expr->ty); auto hi_ty = static_cast<int_type*>(hi_expr->ty); if(lo_ty->width == hi_ty->width) return cxt.make_range_expr(new range_type( new int_type(lo_ty->width)), lo_val, hi_val); //TODO: proper diagnostic std::stringstream ss; ss << "Width of range arguments not equal: " << lo_ty->width << ", and " << hi_ty->width << "\n"; throw std::runtime_error(ss.str().c_str()); } expr* translator::trans_wild_expr(const sexpr::list_expr* e) { } expr* translator::trans_miss_expr() { return cxt.make_miss_expr(nullptr); } expr* translator::trans_ref_expr(const sexpr::id_expr* e) { } expr* translator::trans_field_expr(const sexpr::id_expr* e) { } expr* translator::trans_port_expr(const sexpr::list_expr* e) { int port; match_list(e, "port", &port); // TODO: define a type for this kind of expression return cxt.make_port_expr(nullptr, port); } expr* translator::trans_offset_expr(const sexpr::list_expr* e) { symbol* space; expr* offset; expr* size; match_list(e, "offset", &space, &offset, &size); // TODO: determine typing of offset expressions return new offset_expr(nullptr, space, offset, size); } // When given an integer width specifier, such as i32, // return the integer after the i. In this case, 32. static int deduce_int_type_width(const symbol* ty) { std::string spec = *ty; if(spec.front() == 'i') { spec.erase(0, 1); std::size_t it; auto width = std::stoi(spec.c_str(), &it); if(spec.size() == it) return width; } std::stringstream ss; ss << "Invalid integer width specifier: " << *ty << ". Specifier should be of form i[integer].\n"; throw std::runtime_error(ss.str().c_str()); } expr* translator::trans_int_expr(const sexpr::list_expr* e) { symbol* width_specifier; int value; match_list(e, "int", &width_specifier, &value); int w = deduce_int_type_width(width_specifier); return cxt.make_int_expr( new int_type(w), value ); } // -------------------------------------------------------------------------- // // Matching void translator::match(const sexpr::list_expr* list, int n, decl_seq* decls) { *decls = trans_decls(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, rule_seq* rules) { *rules = trans_rules(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs) { *exprs = trans_exprs(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr** out) { *out = trans_expr(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action_seq* actions) { *actions = trans_actions(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action** a) { *a = trans_action(list); } } // namespace pip <commit_msg>update formatting<commit_after>#include "translator.hpp" #include "decl.hpp" #include "type.hpp" #include "context.hpp" #include "expr.hpp" #include "action.hpp" #include "dumper.hpp" #include <string> // for testing only #include <iostream> #include <sstream> namespace pip { translator::translator(context& cxt) : cxt(cxt) { } /// program ::= (pip <decl-seq>) decl* translator::trans_program(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; match_list(list, "pip", &decls); return new program_decl(std::move(decls)); } sexpr::throw_unexpected_term(e); } /// decl-seq ::= (<decl*>) decl_seq translator::trans_decls(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; // for (const sexpr::expr* elem : list->exprs) { decl* d = trans_decl(list); decls.push_back(d); // } return decls; } sexpr::throw_unexpected_term(e); } /// decl ::= table-decl | meter-decl decl* translator::trans_decl(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "table") return trans_table(list); sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0])); } sexpr::throw_unexpected_term(e); } /// table-decl ::= (table id <match-kind> <match-seq>) /// /// rule-kind ::= exact | prefix | wildcard | range /// /// FIXME: We actually need parse the key extraction program. This /// would be a sequence of actions that bits from the current offset /// into a "key register". decl* translator::trans_table(const sexpr::list_expr* e) { symbol* id; symbol* kind; action_seq actions; rule_seq rules; match_list(e, "table", &id, &kind, &actions, &rules); // TODO: Actually parse the kind of match. For now, we can simply // assume that all tables are exact. Hint: use the match_list framework // to return a match kind. return new table_decl(id, rk_exact, std::move(actions), std::move(rules)); } /// rule_seq ::= (<rule*>) rule_seq translator::trans_rules(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { match_list(list, "rules"); rule_seq rules; // Match each element in turn. for(const sexpr::expr* el : list->exprs) { // We are only interested in the entire sublists contained within list, // not its individual expressions. if(const sexpr::list_expr* r = as<sexpr::list_expr>(el)) { rule* r1 = trans_rule(r); rules.push_back(r1); } } return rules; } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; expr* key; action_seq actions; match_list(list, &key, &actions); return new rule(rk_exact, key, std::move(actions)); } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::list_expr* e) { expr_seq exprs; expr* key; action_seq actions; match_list(e, "rule", &key, &actions); return new rule(rk_exact, key, std::move(actions)); } action_seq translator::trans_actions(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { match_list(list, "actions"); action_seq actions; for(const sexpr::expr* el : list->exprs) { // We are only interested in the entire sublists contained within list, // not its individual expressions. if(const sexpr::list_expr* a = as<sexpr::list_expr>(el)) { action* a1 = trans_action(a); actions.push_back(a1); } // action* a = trans_action(list); // actions.push_back(a); } return actions; } sexpr::throw_unexpected_term(e); } // TODO: parse extra information (i.e. expr to output for output_action). action* translator::trans_action(const sexpr::list_expr* e) { symbol* action_name; expr_seq exprs; int i; match_list(e, &action_name); if(*action_name == "advance") return cxt.make_action(ak_advance); if(*action_name == "copy") return cxt.make_action(ak_copy); if(*action_name == "set") return cxt.make_action(ak_set); if(*action_name == "write") { action* a; match_list(e, "write", &a); return cxt.make_action(ak_write, nullptr, nullptr, a); } if(*action_name == "clear") return cxt.make_action(ak_clear); if( *action_name == "drop" ) return cxt.make_action(ak_drop); if( *action_name == "match" ) return cxt.make_action(ak_match); if( *action_name == "goto" ) { expr* dst; match_list(e, "goto", &dst); return cxt.make_action(ak_goto, dst); } if( *action_name == "output" ) { expr* dst; match_list(e, "output", &dst); return cxt.make_action(ak_output, dst); } sexpr::throw_unexpected_term(e); } expr* translator::trans_expr(const sexpr::expr* e) { // Match bare integer literals. // TODO: match int width // if (const sexpr::int_expr* num = as<sexpr::int_expr>(e)) // return trans_int_expr(num, 32); // Match bare keyword literals. // if (const sexpr::id_expr* id = as<sexpr::id_expr>(e)) { // if (*id->id == "miss") // return trans_miss_expr(id); // } // Match phrases. // // FIXME: Use a lookup table + switch. if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "int") return trans_int_expr(list); if (*sym == "wildcard") return trans_wild_expr(list); if (*sym == "range") return trans_range_expr(list); if (*sym == "port") return trans_port_expr(list); if (*sym == "offset") return trans_offset_expr(list); if (*sym == "miss") return trans_miss_expr(); } } expr_seq translator::trans_exprs(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; for (const sexpr::expr* elem : list->exprs) { expr* e = trans_expr(elem); exprs.push_back(e); } return exprs; } sexpr::throw_unexpected_term(e); } expr* translator::trans_range_expr(const sexpr::list_expr* e) { expr* lo; expr* hi; match_list(e, "range", &lo, &hi); auto lo_expr = as<int_expr>(lo); auto hi_expr = as<int_expr>(hi); auto lo_val = lo_expr->val; auto hi_val = hi_expr->val; auto lo_ty = static_cast<int_type*>(lo_expr->ty); auto hi_ty = static_cast<int_type*>(hi_expr->ty); if(lo_ty->width == hi_ty->width) return cxt.make_range_expr(new range_type( new int_type(lo_ty->width)), lo_val, hi_val); //TODO: proper diagnostic std::stringstream ss; ss << "Width of range arguments not equal: " << lo_ty->width << ", and " << hi_ty->width << "\n"; throw std::runtime_error(ss.str().c_str()); } expr* translator::trans_wild_expr(const sexpr::list_expr* e) { } expr* translator::trans_miss_expr() { return cxt.make_miss_expr(nullptr); } expr* translator::trans_ref_expr(const sexpr::id_expr* e) { } expr* translator::trans_field_expr(const sexpr::id_expr* e) { } expr* translator::trans_port_expr(const sexpr::list_expr* e) { int port; match_list(e, "port", &port); // TODO: define a type for this kind of expression return cxt.make_port_expr(nullptr, port); } expr* translator::trans_offset_expr(const sexpr::list_expr* e) { symbol* space; expr* offset; expr* size; match_list(e, "offset", &space, &offset, &size); // TODO: determine typing of offset expressions return new offset_expr(nullptr, space, offset, size); } // When given an integer width specifier, such as i32, // return the integer after the i. In this case, 32. static int deduce_int_type_width(const symbol* ty) { std::string spec = *ty; if(spec.front() == 'i') { spec.erase(0, 1); std::size_t it; auto width = std::stoi(spec.c_str(), &it); if(spec.size() == it) return width; } std::stringstream ss; ss << "Invalid integer width specifier: " << *ty << ". Specifier should be of form i[integer].\n"; throw std::runtime_error(ss.str().c_str()); } expr* translator::trans_int_expr(const sexpr::list_expr* e) { symbol* width_specifier; int value; match_list(e, "int", &width_specifier, &value); int w = deduce_int_type_width(width_specifier); return cxt.make_int_expr( new int_type(w), value ); } // -------------------------------------------------------------------------- //// Matching void translator::match(const sexpr::list_expr* list, int n, decl_seq* decls) { *decls = trans_decls(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, rule_seq* rules) { *rules = trans_rules(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs) { *exprs = trans_exprs(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr** out) { *out = trans_expr(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action_seq* actions) { *actions = trans_actions(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action** a) { *a = trans_action(list); } } // namespace pip <|endoftext|>
<commit_before>/* This file is part of tgl-library This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Copyright Vitaly Valtman 2014-2015 Copyright Topology LP 2016 */ #include "tgl.h" #include "crypto/rsa_pem.h" #include "crypto/sha.h" #include "tools.h" #include "mtproto-client.h" #include "structures.h" #include "tgl_download_manager.h" #include "tgl-timer.h" #include "tgl-queries.h" #include "tools.h" #include "types/tgl_online_status_observer.h" #include "types/tgl_update_callback.h" #include "types/tgl_rsa_key.h" #include "types/tgl_secret_chat.h" #include "queries.h" #include <assert.h> #include <stdlib.h> std::unique_ptr<tgl_state> tgl_state::s_instance; tgl_state::tgl_state() : locks(0) , ev_login(NULL) , m_is_started(false) , m_online_status(tgl_online_status::not_online) , m_app_id(0) , m_error_code(0) , m_temp_key_expire_time(0) , m_pts(0) , m_qts(0) , m_date(0) , m_seq(0) , m_test_mode(0) , m_our_id() , m_enable_pfs(false) , m_ipv6_enabled(false) , m_bn_ctx(TGLC_bn_ctx_new()) , m_online_status_observers() { } tgl_state *tgl_state::instance() { if (!s_instance) { s_instance.reset(new tgl_state); } return s_instance.get(); } void tgl_state::reset() { s_instance.reset(); } void tgl_state::set_auth_key(int num, const char *buf) { assert(num > 0 && num <= MAX_DC_ID); assert(m_dcs[num]); if (buf) { memcpy(m_dcs[num]->auth_key, buf, 256); } static unsigned char sha1_buffer[20]; TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer); memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8); m_dcs[num]->flags |= TGLDCF_AUTHORIZED; TGL_DEBUG("set auth key for DC " << num << " to " << std::hex << m_dcs[num]->auth_key_id); m_callback->dc_update(m_dcs[num]); } void tgl_state::set_our_id(int id) { if (m_our_id.peer_id == id) { return; } m_our_id.peer_id = id; m_our_id.peer_type = tgl_peer_type::user; assert(our_id().peer_id > 0); m_callback->our_id(our_id().peer_id); } void tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port) { if (id < 0) { return; } if (static_cast<size_t>(id) >= m_dcs.size()) { m_dcs.resize(id+1, nullptr); } if (!m_dcs[id]) { m_dcs[id] = tgl_state::instance()->allocate_dc(id); if (tgl_state::instance()->pfs_enabled()) { //dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(&regen_temp_key_gw, DC)); //dc->ev->start(0); } } if (is_v6) { m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port)); } else { m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port)); } } void tgl_state::set_dc_signed(int num) { TGL_DEBUG2("set signed " << num); assert(num > 0 && num <= MAX_DC_ID); assert(m_dcs[num]); m_dcs[num]->flags |= TGLDCF_LOGGED_IN; m_callback->dc_update(m_dcs[num]); } void tgl_state::set_working_dc(int num) { if (m_working_dc && m_working_dc->id == num) { return; } TGL_DEBUG2("change working DC to " << num); assert(num > 0 && num <= MAX_DC_ID); m_working_dc = m_dcs[num]; m_callback->change_active_dc(num); } void tgl_state::set_qts(int32_t qts, bool force) { if (locks & TGL_LOCK_DIFF) { return; } if (qts <= m_qts && !force) { return; } m_qts = qts; m_callback->qts_changed(qts); } void tgl_state::set_pts(int32_t pts, bool force) { if (locks & TGL_LOCK_DIFF && !force) { return; } if (pts <= m_pts && !force) { return; } m_pts = pts; m_callback->pts_changed(pts); } void tgl_state::set_date(int64_t date, bool force) { if (locks & TGL_LOCK_DIFF && !force) { return; } if (date <= m_date && !force) { return; } m_date = date; m_callback->date_changed(date); } void tgl_state::set_seq(int32_t seq) { if (locks & TGL_LOCK_DIFF) { return; } if (seq <= m_seq) { return; } m_seq = seq; } void tgl_state::reset_server_state() { m_qts = 0; m_pts = 0; m_date = 0; m_seq = 0; } void tgl_state::add_rsa_key(const std::string& key) { m_rsa_key_list.push_back(std::unique_ptr<tgl_rsa_key>(new tgl_rsa_key(key))); } int tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version) { m_download_manager = std::make_shared<tgl_download_manager>(download_dir); m_app_id = app_id; m_app_hash = app_hash; m_app_version = app_version; assert(m_timer_factory); assert(m_connection_factory); if (!m_temp_key_expire_time) { m_temp_key_expire_time = 100000; } if (tglmp_on_start() < 0) { return -1; } if (!m_app_id) { m_app_id = TG_APP_ID; m_app_hash = TG_APP_HASH; } m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this)); m_state_lookup_timer->start(3600); return 0; } int tgl_authorized_dc(const std::shared_ptr<tgl_dc>& dc) { assert(dc); return dc->flags & TGLDCF_AUTHORIZED; } int tgl_signed_dc(const std::shared_ptr<tgl_dc>& dc) { assert(dc); return (dc->flags & TGLDCF_LOGGED_IN) != 0; } void tgl_state::set_enable_pfs(bool val) { m_enable_pfs = val; } void tgl_state::set_test_mode(bool val) { m_test_mode = val; } void tgl_state::set_enable_ipv6(bool val) { m_ipv6_enabled = val; } void tgl_state::set_error(const std::string& error, int error_code) { m_error = error; m_error_code = error_code; } int32_t tgl_state::create_secret_chat_id() { int chat_id = tgl_random<int>(); while (tgl_state::instance()->secret_chat_for_id(chat_id)) { chat_id = tgl_random<int>(); } return chat_id; } std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(int32_t id) { int chat_id; if (id) { chat_id = id; } else { chat_id = create_secret_chat_id(); } auto secret_chat = std::make_shared<tgl_secret_chat>(); secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0); m_secret_chats[chat_id] = secret_chat; return secret_chat; } std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id) { if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) { return nullptr; } auto secret_chat = std::make_shared<tgl_secret_chat>(); secret_chat->id = chat_id; m_secret_chats[chat_id.peer_id] = secret_chat; return secret_chat; } std::shared_ptr<tgl_secret_chat> tgl_state::secret_chat_for_id(int chat_id) const { auto secret_chat_it = m_secret_chats.find(chat_id); if (secret_chat_it == m_secret_chats.end()) { return nullptr; } return secret_chat_it->second; } void tgl_state::add_secret_chat(const std::shared_ptr<tgl_secret_chat>& secret_chat) { m_secret_chats[secret_chat->id.peer_id] = secret_chat; } void tgl_state::add_query(const std::shared_ptr<query>& q) { auto id = q->msg_id(); assert(id); auto inserted_iterator_pair = m_active_queries.emplace(id, q); if (inserted_iterator_pair.second) { q->dc()->increase_active_queries(); } else { inserted_iterator_pair.first->second = q; } } std::shared_ptr<query> tgl_state::get_query(int64_t id) const { assert(id); auto it = m_active_queries.find(id); if (it == m_active_queries.end()) { return nullptr; } return it->second; } void tgl_state::remove_query(const std::shared_ptr<query>& q) { auto id = q->msg_id(); assert(id); auto it = m_active_queries.find(id); if (it != m_active_queries.end()) { m_active_queries.erase(it); q->dc()->decrease_active_queries(); } } void tgl_state::remove_all_queries() { m_active_queries.clear(); } std::shared_ptr<tgl_dc> tgl_state::dc_at(int id) { if (static_cast<size_t>(id) >= m_dcs.size()) { return nullptr; } return m_dcs[id]; } std::shared_ptr<tgl_dc> tgl_state::allocate_dc(int id) { if (static_cast<size_t>(id) >= m_dcs.size()) { m_dcs.resize(id+1, nullptr); } assert(!m_dcs[id]); std::shared_ptr<tgl_dc> dc = std::make_shared<tgl_dc>(); dc->id = id; m_dcs[id] = dc; return dc; } void tgl_state::state_lookup_timeout() { tgl_do_lookup_state(); if (m_state_lookup_timer) { m_state_lookup_timer->start(3600); } } void tgl_state::logout() { tgl_do_logout(nullptr); } void tgl_state::set_online_status(tgl_online_status status) { if (status == m_online_status) { return; } m_online_status = status; for (const auto& weak_observer: m_online_status_observers) { if (auto observer = weak_observer.lock()) { observer->on_online_status_changed(status); } } } <commit_msg>Remove a log of auth key<commit_after>/* This file is part of tgl-library This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Copyright Vitaly Valtman 2014-2015 Copyright Topology LP 2016 */ #include "tgl.h" #include "crypto/rsa_pem.h" #include "crypto/sha.h" #include "tools.h" #include "mtproto-client.h" #include "structures.h" #include "tgl_download_manager.h" #include "tgl-timer.h" #include "tgl-queries.h" #include "tools.h" #include "types/tgl_online_status_observer.h" #include "types/tgl_update_callback.h" #include "types/tgl_rsa_key.h" #include "types/tgl_secret_chat.h" #include "queries.h" #include <assert.h> #include <stdlib.h> std::unique_ptr<tgl_state> tgl_state::s_instance; tgl_state::tgl_state() : locks(0) , ev_login(NULL) , m_is_started(false) , m_online_status(tgl_online_status::not_online) , m_app_id(0) , m_error_code(0) , m_temp_key_expire_time(0) , m_pts(0) , m_qts(0) , m_date(0) , m_seq(0) , m_test_mode(0) , m_our_id() , m_enable_pfs(false) , m_ipv6_enabled(false) , m_bn_ctx(TGLC_bn_ctx_new()) , m_online_status_observers() { } tgl_state *tgl_state::instance() { if (!s_instance) { s_instance.reset(new tgl_state); } return s_instance.get(); } void tgl_state::reset() { s_instance.reset(); } void tgl_state::set_auth_key(int num, const char *buf) { assert(num > 0 && num <= MAX_DC_ID); assert(m_dcs[num]); if (buf) { memcpy(m_dcs[num]->auth_key, buf, 256); } static unsigned char sha1_buffer[20]; TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer); memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8); m_dcs[num]->flags |= TGLDCF_AUTHORIZED; m_callback->dc_update(m_dcs[num]); } void tgl_state::set_our_id(int id) { if (m_our_id.peer_id == id) { return; } m_our_id.peer_id = id; m_our_id.peer_type = tgl_peer_type::user; assert(our_id().peer_id > 0); m_callback->our_id(our_id().peer_id); } void tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port) { if (id < 0) { return; } if (static_cast<size_t>(id) >= m_dcs.size()) { m_dcs.resize(id+1, nullptr); } if (!m_dcs[id]) { m_dcs[id] = tgl_state::instance()->allocate_dc(id); if (tgl_state::instance()->pfs_enabled()) { //dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(&regen_temp_key_gw, DC)); //dc->ev->start(0); } } if (is_v6) { m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port)); } else { m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port)); } } void tgl_state::set_dc_signed(int num) { TGL_DEBUG2("set signed " << num); assert(num > 0 && num <= MAX_DC_ID); assert(m_dcs[num]); m_dcs[num]->flags |= TGLDCF_LOGGED_IN; m_callback->dc_update(m_dcs[num]); } void tgl_state::set_working_dc(int num) { if (m_working_dc && m_working_dc->id == num) { return; } TGL_DEBUG2("change working DC to " << num); assert(num > 0 && num <= MAX_DC_ID); m_working_dc = m_dcs[num]; m_callback->change_active_dc(num); } void tgl_state::set_qts(int32_t qts, bool force) { if (locks & TGL_LOCK_DIFF) { return; } if (qts <= m_qts && !force) { return; } m_qts = qts; m_callback->qts_changed(qts); } void tgl_state::set_pts(int32_t pts, bool force) { if (locks & TGL_LOCK_DIFF && !force) { return; } if (pts <= m_pts && !force) { return; } m_pts = pts; m_callback->pts_changed(pts); } void tgl_state::set_date(int64_t date, bool force) { if (locks & TGL_LOCK_DIFF && !force) { return; } if (date <= m_date && !force) { return; } m_date = date; m_callback->date_changed(date); } void tgl_state::set_seq(int32_t seq) { if (locks & TGL_LOCK_DIFF) { return; } if (seq <= m_seq) { return; } m_seq = seq; } void tgl_state::reset_server_state() { m_qts = 0; m_pts = 0; m_date = 0; m_seq = 0; } void tgl_state::add_rsa_key(const std::string& key) { m_rsa_key_list.push_back(std::unique_ptr<tgl_rsa_key>(new tgl_rsa_key(key))); } int tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version) { m_download_manager = std::make_shared<tgl_download_manager>(download_dir); m_app_id = app_id; m_app_hash = app_hash; m_app_version = app_version; assert(m_timer_factory); assert(m_connection_factory); if (!m_temp_key_expire_time) { m_temp_key_expire_time = 100000; } if (tglmp_on_start() < 0) { return -1; } if (!m_app_id) { m_app_id = TG_APP_ID; m_app_hash = TG_APP_HASH; } m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this)); m_state_lookup_timer->start(3600); return 0; } int tgl_authorized_dc(const std::shared_ptr<tgl_dc>& dc) { assert(dc); return dc->flags & TGLDCF_AUTHORIZED; } int tgl_signed_dc(const std::shared_ptr<tgl_dc>& dc) { assert(dc); return (dc->flags & TGLDCF_LOGGED_IN) != 0; } void tgl_state::set_enable_pfs(bool val) { m_enable_pfs = val; } void tgl_state::set_test_mode(bool val) { m_test_mode = val; } void tgl_state::set_enable_ipv6(bool val) { m_ipv6_enabled = val; } void tgl_state::set_error(const std::string& error, int error_code) { m_error = error; m_error_code = error_code; } int32_t tgl_state::create_secret_chat_id() { int chat_id = tgl_random<int>(); while (tgl_state::instance()->secret_chat_for_id(chat_id)) { chat_id = tgl_random<int>(); } return chat_id; } std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(int32_t id) { int chat_id; if (id) { chat_id = id; } else { chat_id = create_secret_chat_id(); } auto secret_chat = std::make_shared<tgl_secret_chat>(); secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0); m_secret_chats[chat_id] = secret_chat; return secret_chat; } std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id) { if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) { return nullptr; } auto secret_chat = std::make_shared<tgl_secret_chat>(); secret_chat->id = chat_id; m_secret_chats[chat_id.peer_id] = secret_chat; return secret_chat; } std::shared_ptr<tgl_secret_chat> tgl_state::secret_chat_for_id(int chat_id) const { auto secret_chat_it = m_secret_chats.find(chat_id); if (secret_chat_it == m_secret_chats.end()) { return nullptr; } return secret_chat_it->second; } void tgl_state::add_secret_chat(const std::shared_ptr<tgl_secret_chat>& secret_chat) { m_secret_chats[secret_chat->id.peer_id] = secret_chat; } void tgl_state::add_query(const std::shared_ptr<query>& q) { auto id = q->msg_id(); assert(id); auto inserted_iterator_pair = m_active_queries.emplace(id, q); if (inserted_iterator_pair.second) { q->dc()->increase_active_queries(); } else { inserted_iterator_pair.first->second = q; } } std::shared_ptr<query> tgl_state::get_query(int64_t id) const { assert(id); auto it = m_active_queries.find(id); if (it == m_active_queries.end()) { return nullptr; } return it->second; } void tgl_state::remove_query(const std::shared_ptr<query>& q) { auto id = q->msg_id(); assert(id); auto it = m_active_queries.find(id); if (it != m_active_queries.end()) { m_active_queries.erase(it); q->dc()->decrease_active_queries(); } } void tgl_state::remove_all_queries() { m_active_queries.clear(); } std::shared_ptr<tgl_dc> tgl_state::dc_at(int id) { if (static_cast<size_t>(id) >= m_dcs.size()) { return nullptr; } return m_dcs[id]; } std::shared_ptr<tgl_dc> tgl_state::allocate_dc(int id) { if (static_cast<size_t>(id) >= m_dcs.size()) { m_dcs.resize(id+1, nullptr); } assert(!m_dcs[id]); std::shared_ptr<tgl_dc> dc = std::make_shared<tgl_dc>(); dc->id = id; m_dcs[id] = dc; return dc; } void tgl_state::state_lookup_timeout() { tgl_do_lookup_state(); if (m_state_lookup_timer) { m_state_lookup_timer->start(3600); } } void tgl_state::logout() { tgl_do_logout(nullptr); } void tgl_state::set_online_status(tgl_online_status status) { if (status == m_online_status) { return; } m_online_status = status; for (const auto& weak_observer: m_online_status_observers) { if (auto observer = weak_observer.lock()) { observer->on_online_status_changed(status); } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdint.h> #include <time.h> #include <v8.h> #include <node.h> using namespace node; using namespace v8; class Time { public : static void Init(Handle<Object> target) { HandleScope scope; // time(3) Persistent<FunctionTemplate> s_time = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Time_)); target->Set(String::NewSymbol("time"), s_time->GetFunction()); // tzset(3) Persistent<FunctionTemplate> s_tzset = Persistent<FunctionTemplate>::New(FunctionTemplate::New(tzset_)); target->Set(String::NewSymbol("tzset"), s_tzset->GetFunction()); // localtime Persistent<FunctionTemplate> s_localtime = Persistent<FunctionTemplate>::New(FunctionTemplate::New(localtime_)); target->Set(String::NewSymbol("localtime"), s_localtime->GetFunction()); } static Handle<Value> Time_(const Arguments& args) { return Integer::New(time(NULL)); } static Handle<Value> tzset_(const Arguments& args) { HandleScope scope; // Set up the timezone info from the current TZ environ variable tzset(); // Set up a return object that will hold the results of the timezone change Local<Object> obj = Object::New(); // The 'tzname' char * [] gets put into a JS Array int tznameLength = sizeof(tzname) / sizeof(int); Local<Array> tznameArray = Array::New( tznameLength ); for (int i=0; i < tznameLength; i++) { tznameArray->Set(Number::New(i), String::NewSymbol( tzname[i] )); } obj->Set(String::NewSymbol("tzname"), tznameArray); // The 'timezone' long is the "seconds West of UTC" obj->Set(String::NewSymbol("timezone"), Number::New( timezone )); // The 'daylight' int is obselete actually, but I'll include it here for // curiosity's sake. See the "Notes" section of "man tzset" obj->Set(String::NewSymbol("daylight"), Number::New( daylight )); return scope.Close(obj); } static Handle<Value> localtime_(const Arguments& args) { HandleScope scope; // Construct the 'tm' struct time_t rawtime = static_cast<time_t>(args[0]->Int32Value()); struct tm * timeinfo = localtime ( &rawtime ); // Create the return "Object" Local<Object> obj = Object::New(); obj->Set(String::NewSymbol("seconds"), Integer::New(timeinfo->tm_sec) ); obj->Set(String::NewSymbol("minutes"), Integer::New(timeinfo->tm_min) ); obj->Set(String::NewSymbol("hours"), Integer::New(timeinfo->tm_hour) ); obj->Set(String::NewSymbol("dayOfMonth"), Integer::New(timeinfo->tm_mday) ); obj->Set(String::NewSymbol("month"), Integer::New(timeinfo->tm_mon) ); obj->Set(String::NewSymbol("year"), Integer::New(timeinfo->tm_year) ); obj->Set(String::NewSymbol("dayOfWeek"), Integer::New(timeinfo->tm_wday) ); obj->Set(String::NewSymbol("dayOfYear"), Integer::New(timeinfo->tm_yday) ); obj->Set(String::NewSymbol("isDaylightSavings"), Integer::New(timeinfo->tm_isdst) ); return scope.Close(obj); } }; extern "C" { static void init (Handle<Object> target) { Time::Init(target); } NODE_MODULE(time, init); } <commit_msg>Make "isDaylightSavings" into a Boolean<commit_after>#include <stdio.h> #include <stdint.h> #include <time.h> #include <v8.h> #include <node.h> using namespace node; using namespace v8; class Time { public : static void Init(Handle<Object> target) { HandleScope scope; // time(3) Persistent<FunctionTemplate> s_time = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Time_)); target->Set(String::NewSymbol("time"), s_time->GetFunction()); // tzset(3) Persistent<FunctionTemplate> s_tzset = Persistent<FunctionTemplate>::New(FunctionTemplate::New(tzset_)); target->Set(String::NewSymbol("tzset"), s_tzset->GetFunction()); // localtime Persistent<FunctionTemplate> s_localtime = Persistent<FunctionTemplate>::New(FunctionTemplate::New(localtime_)); target->Set(String::NewSymbol("localtime"), s_localtime->GetFunction()); } static Handle<Value> Time_(const Arguments& args) { return Integer::New(time(NULL)); } static Handle<Value> tzset_(const Arguments& args) { HandleScope scope; // Set up the timezone info from the current TZ environ variable tzset(); // Set up a return object that will hold the results of the timezone change Local<Object> obj = Object::New(); // The 'tzname' char * [] gets put into a JS Array int tznameLength = sizeof(tzname) / sizeof(int); Local<Array> tznameArray = Array::New( tznameLength ); for (int i=0; i < tznameLength; i++) { tznameArray->Set(Number::New(i), String::NewSymbol( tzname[i] )); } obj->Set(String::NewSymbol("tzname"), tznameArray); // The 'timezone' long is the "seconds West of UTC" obj->Set(String::NewSymbol("timezone"), Number::New( timezone )); // The 'daylight' int is obselete actually, but I'll include it here for // curiosity's sake. See the "Notes" section of "man tzset" obj->Set(String::NewSymbol("daylight"), Number::New( daylight )); return scope.Close(obj); } static Handle<Value> localtime_(const Arguments& args) { HandleScope scope; // Construct the 'tm' struct time_t rawtime = static_cast<time_t>(args[0]->Int32Value()); struct tm * timeinfo = localtime ( &rawtime ); // Create the return "Object" Local<Object> obj = Object::New(); obj->Set(String::NewSymbol("seconds"), Integer::New(timeinfo->tm_sec) ); obj->Set(String::NewSymbol("minutes"), Integer::New(timeinfo->tm_min) ); obj->Set(String::NewSymbol("hours"), Integer::New(timeinfo->tm_hour) ); obj->Set(String::NewSymbol("dayOfMonth"), Integer::New(timeinfo->tm_mday) ); obj->Set(String::NewSymbol("month"), Integer::New(timeinfo->tm_mon) ); obj->Set(String::NewSymbol("year"), Integer::New(timeinfo->tm_year) ); obj->Set(String::NewSymbol("dayOfWeek"), Integer::New(timeinfo->tm_wday) ); obj->Set(String::NewSymbol("dayOfYear"), Integer::New(timeinfo->tm_yday) ); obj->Set(String::NewSymbol("isDaylightSavings"), Boolean::New(timeinfo->tm_isdst > 0) ); return scope.Close(obj); } }; extern "C" { static void init (Handle<Object> target) { Time::Init(target); } NODE_MODULE(time, init); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkJavaUtil.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // include stdmutex for borland #ifdef __BORLANDC__ #include <stdmutex.h> #endif #include <iostream.h> #include <stdlib.h> #include <stdio.h> #ifdef _INTEGRAL_MAX_BITS #undef _INTEGRAL_MAX_BITS #endif #define _INTEGRAL_MAX_BITS 64 #ifdef _WIN32 #include "vtkSetGet.h" #include "vtkWin32Header.h" #include "vtkObject.h" HANDLE vtkGlobalMutex = NULL; #define VTK_GET_MUTEX() WaitForSingleObject(vtkGlobalMutex,INFINITE) #define VTK_RELEASE_MUTEX() ReleaseMutex(vtkGlobalMutex) #include <mapiform.h> #else #include <thread.h> #include <synch.h> mutex_t vtkGlobalMutex; #define VTK_GET_MUTEX() mutex_lock(&vtkGlobalMutex) #define VTK_RELEASE_MUTEX() mutex_unlock(&vtkGlobalMutex) #endif #include "vtkJavaUtil.h" int vtkJavaIdCount = 1; //#define VTKJAVADEBUG class vtkHashNode { public: vtkHashNode *next; void *key; void *value; }; class vtkHashTable { public: vtkHashTable(); vtkHashNode *(nodes[64]); void AddHashEntry(void *key,void *value); void *GetHashTableValue(void *key); void DeleteHashEntry(void *key); }; vtkHashTable::vtkHashTable() { int i; for (i = 0; i < 64; i++) { this->nodes[i] = NULL; } } vtkHashTable *vtkInstanceLookup = NULL; vtkHashTable *vtkPointerLookup = NULL; vtkHashTable *vtkTypecastLookup = NULL; vtkHashTable *vtkDeleteLookup = NULL; void vtkHashTable::AddHashEntry(void *key,void *value) { vtkHashNode *pos; vtkHashNode *newpos; int loc; newpos = new vtkHashNode; newpos->key = key; newpos->value = value; newpos->next = NULL; loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; if (!pos) { this->nodes[loc] = newpos; return; } while (pos->next) { pos = pos->next; } pos->next = newpos; } void *vtkHashTable::GetHashTableValue(void *key) { vtkHashNode *pos; int loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; if (!pos) { return NULL; } while ((pos)&&(pos->key != key)) { pos = pos->next; } if (pos) { return pos->value; } return NULL; } void vtkHashTable::DeleteHashEntry(void *key) { vtkHashNode *pos; vtkHashNode *prev = NULL; int loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; while ((pos)&&(pos->key != key)) { prev = pos; pos = pos->next; } if (pos) { // we found this object if (prev) { prev->next = pos->next; } else { this->nodes[loc] = pos->next; } delete pos; } } int vtkJavaGetId(JNIEnv *env,jobject obj) { jfieldID id; int result; id = env->GetFieldID(env->GetObjectClass(obj),"vtkId","I"); result = (int)env->GetIntField(obj,id); return result; } void vtkJavaSetId(JNIEnv *env,jobject obj, int newVal) { jfieldID id; jint jNewVal = (jint)newVal; id = env->GetFieldID(env->GetObjectClass(obj),"vtkId","I"); env->SetIntField(obj,id,jNewVal); } // add an object to the hash table void vtkJavaAddObjectToHash(JNIEnv *env, jobject obj, void *ptr, void *tcFunc,int deleteMe) { if (!vtkInstanceLookup) { vtkInstanceLookup = new vtkHashTable; vtkTypecastLookup = new vtkHashTable; vtkPointerLookup = new vtkHashTable; vtkDeleteLookup = new vtkHashTable; #ifdef _WIN32 vtkGlobalMutex = CreateMutex(NULL, FALSE, NULL); #endif } VTK_GET_MUTEX(); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Adding an object to hash ptr = " << ptr); #endif // lets make sure it isn't already there if (vtkJavaGetId(env,obj)) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Attempt to add an object to the hash when one already exists!!!"); #endif VTK_RELEASE_MUTEX(); return; } // get a unique id for this object // just use vtkJavaIdCount and then increment // to handle loop around make sure the id isn't currently in use while (vtkInstanceLookup->GetHashTableValue((void *)vtkJavaIdCount)) { vtkJavaIdCount++; if (vtkJavaIdCount > 268435456) vtkJavaIdCount = 1; } vtkInstanceLookup->AddHashEntry((void *)vtkJavaIdCount,ptr); vtkTypecastLookup->AddHashEntry((void *)vtkJavaIdCount,tcFunc); vtkPointerLookup->AddHashEntry(ptr,(void *)env->NewGlobalRef(obj)); vtkDeleteLookup->AddHashEntry((void *)vtkJavaIdCount,(void *)deleteMe); vtkJavaSetId(env,obj,vtkJavaIdCount); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Added object to hash id= " << vtkJavaIdCount << " " << ptr); #endif vtkJavaIdCount++; VTK_RELEASE_MUTEX(); } // should we delete this object int vtkJavaShouldIDeleteObject(JNIEnv *env,jobject obj) { int id = vtkJavaGetId(env,obj); VTK_GET_MUTEX(); if ((int)(vtkDeleteLookup->GetHashTableValue((void *)id))) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Decided to delete id = " << id); #endif vtkJavaDeleteObjectFromHash(env, id); VTK_RELEASE_MUTEX(); return 1; } #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Decided to NOT delete id = " << id); #endif vtkJavaDeleteObjectFromHash(env, id); VTK_RELEASE_MUTEX(); return 0; } // delete an object from the hash void vtkJavaDeleteObjectFromHash(JNIEnv *env, int id) { void *ptr; void *vptr; ptr = vtkInstanceLookup->GetHashTableValue((void *)id); if (!ptr) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Attempt to delete an object that doesnt exist!!!"); #endif return; } vtkInstanceLookup->DeleteHashEntry((void *)id); vtkTypecastLookup->DeleteHashEntry((void *)id); vptr = vtkPointerLookup->GetHashTableValue(ptr); env->DeleteGlobalRef((jobject)&vptr); vtkPointerLookup->DeleteHashEntry(ptr); vtkDeleteLookup->DeleteHashEntry((void *)id); } jobject vtkJavaGetObjectFromPointer(void *ptr) { jobject obj; #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into pointer " << ptr); #endif obj = (jobject)vtkPointerLookup->GetHashTableValue((jobject *)ptr); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into pointer " << ptr << " obj = " << obj); #endif return obj; } void *vtkJavaGetPointerFromObject(JNIEnv *env, jobject obj, char *result_type) { void *ptr; void *(*command)(void *,char *); int id; id = vtkJavaGetId(env,obj); ptr = vtkInstanceLookup->GetHashTableValue((void *)id); command = (void *(*)(void *,char *))vtkTypecastLookup->GetHashTableValue((void *)id); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into id " << id << " ptr = " << ptr); #endif if (!ptr) { return NULL; } if (command(ptr,result_type)) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Got id= " << id << " ptr= " << ptr << " " << result_type); #endif return command(ptr,result_type); } else { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("vtk bad argument, type conversion failed."); #endif return NULL; } } jarray vtkJavaMakeJArrayOfDoubleFromDouble(JNIEnv *env, double *ptr, int size) { jdoubleArray ret; int i; jdouble *array; ret = env->NewDoubleArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetDoubleArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseDoubleArrayElements(ret,array,0); return ret; } jarray vtkJavaMakeJArrayOfDoubleFromFloat(JNIEnv *env, float *ptr, int size) { jdoubleArray ret; int i; jdouble *array; ret = env->NewDoubleArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetDoubleArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseDoubleArrayElements(ret,array,0); return ret; } jarray vtkJavaMakeJArrayOfIntFromInt(JNIEnv *env, int *ptr, int size) { jintArray ret; int i; jint *array; ret = env->NewIntArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetIntArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseIntArrayElements(ret,array,0); return ret; } char *vtkJavaUTFToChar(JNIEnv *env,jstring in) { char *result; const char *inBytes; int length, i; int resultLength = 1; length = env->GetStringUTFLength(in); inBytes = env->GetStringUTFChars(in,NULL); for (i = 0; i < length; i++) { if ((inBytes[i] >= 0)&&(inBytes[i] < 128 )) resultLength++; } result = new char [resultLength]; resultLength = 0; // the 0 versus 1 up above is on purpose for (i = 0; i < length; i++) { if ((inBytes[i] >= 0)&&(inBytes[i] < 128 )) { result[resultLength] = inBytes[i]; resultLength++; } } result[resultLength] = '\0'; env->ReleaseStringUTFChars(in,inBytes); return result; } jstring vtkJavaMakeJavaString(JNIEnv *env, const char *in) { jstring result; char *utf; int inLength, utfLength, i; inLength = strlen(in); utfLength = inLength + 2; utf = new char [utfLength]; for (i = 0; i < inLength; i++) { utf[i] = in[i]; } utf[inLength] = 0xC0; utf[inLength+1] = 0x80; result = env->NewStringUTF(utf); // do we need to free utf here ? Does JNI make a copy ? return result; } //**jcp this is the callback inteface stub for Java. no user parms are passed //since the callback must be a method of a class. We make the rash assumption //that the <this> pointer will anchor any required other elements for the //called functions. // void vtkJavaVoidFunc(void* f) { vtkJavaVoidFuncArg *iprm = (vtkJavaVoidFuncArg *)f; iprm->uenv->CallVoidMethod(iprm->uobj,iprm->mid); } void vtkJavaVoidFuncArgDelete(void* arg) { vtkJavaVoidFuncArg *arg2; arg2 = (vtkJavaVoidFuncArg *)arg; // free the structure arg2->uenv->DeleteGlobalRef(arg2->uobj); delete arg2; } <commit_msg>better error checking<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkJavaUtil.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // include stdmutex for borland #ifdef __BORLANDC__ #include <stdmutex.h> #endif #include <iostream.h> #include <stdlib.h> #include <stdio.h> #ifdef _INTEGRAL_MAX_BITS #undef _INTEGRAL_MAX_BITS #endif #define _INTEGRAL_MAX_BITS 64 #ifdef _WIN32 #include "vtkSetGet.h" #include "vtkWin32Header.h" #include "vtkObject.h" HANDLE vtkGlobalMutex = NULL; #define VTK_GET_MUTEX() WaitForSingleObject(vtkGlobalMutex,INFINITE) #define VTK_RELEASE_MUTEX() ReleaseMutex(vtkGlobalMutex) #include <mapiform.h> #else #include <thread.h> #include <synch.h> mutex_t vtkGlobalMutex; #define VTK_GET_MUTEX() mutex_lock(&vtkGlobalMutex) #define VTK_RELEASE_MUTEX() mutex_unlock(&vtkGlobalMutex) #endif #include "vtkJavaUtil.h" int vtkJavaIdCount = 1; //#define VTKJAVADEBUG class vtkHashNode { public: vtkHashNode *next; void *key; void *value; }; class vtkHashTable { public: vtkHashTable(); vtkHashNode *(nodes[64]); void AddHashEntry(void *key,void *value); void *GetHashTableValue(void *key); void DeleteHashEntry(void *key); }; vtkHashTable::vtkHashTable() { int i; for (i = 0; i < 64; i++) { this->nodes[i] = NULL; } } vtkHashTable *vtkInstanceLookup = NULL; vtkHashTable *vtkPointerLookup = NULL; vtkHashTable *vtkTypecastLookup = NULL; vtkHashTable *vtkDeleteLookup = NULL; void vtkHashTable::AddHashEntry(void *key,void *value) { vtkHashNode *pos; vtkHashNode *newpos; int loc; newpos = new vtkHashNode; newpos->key = key; newpos->value = value; newpos->next = NULL; loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; if (!pos) { this->nodes[loc] = newpos; return; } while (pos->next) { pos = pos->next; } pos->next = newpos; } void *vtkHashTable::GetHashTableValue(void *key) { vtkHashNode *pos; int loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; if (!pos) { return NULL; } while ((pos)&&(pos->key != key)) { pos = pos->next; } if (pos) { return pos->value; } return NULL; } void vtkHashTable::DeleteHashEntry(void *key) { vtkHashNode *pos; vtkHashNode *prev = NULL; int loc = (((unsigned long)key) & 0x03f0) / 16; pos = this->nodes[loc]; while ((pos)&&(pos->key != key)) { prev = pos; pos = pos->next; } if (pos) { // we found this object if (prev) { prev->next = pos->next; } else { this->nodes[loc] = pos->next; } delete pos; } } int vtkJavaGetId(JNIEnv *env,jobject obj) { jfieldID id; int result; id = env->GetFieldID(env->GetObjectClass(obj),"vtkId","I"); result = (int)env->GetIntField(obj,id); return result; } void vtkJavaSetId(JNIEnv *env,jobject obj, int newVal) { jfieldID id; jint jNewVal = (jint)newVal; id = env->GetFieldID(env->GetObjectClass(obj),"vtkId","I"); env->SetIntField(obj,id,jNewVal); } // add an object to the hash table void vtkJavaAddObjectToHash(JNIEnv *env, jobject obj, void *ptr, void *tcFunc,int deleteMe) { if (!vtkInstanceLookup) { vtkInstanceLookup = new vtkHashTable; vtkTypecastLookup = new vtkHashTable; vtkPointerLookup = new vtkHashTable; vtkDeleteLookup = new vtkHashTable; #ifdef _WIN32 vtkGlobalMutex = CreateMutex(NULL, FALSE, NULL); #endif } VTK_GET_MUTEX(); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Adding an object to hash ptr = " << ptr); #endif // lets make sure it isn't already there if (vtkJavaGetId(env,obj)) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Attempt to add an object to the hash when one already exists!!!"); #endif VTK_RELEASE_MUTEX(); return; } // get a unique id for this object // just use vtkJavaIdCount and then increment // to handle loop around make sure the id isn't currently in use while (vtkInstanceLookup->GetHashTableValue((void *)vtkJavaIdCount)) { vtkJavaIdCount++; if (vtkJavaIdCount > 268435456) vtkJavaIdCount = 1; } vtkInstanceLookup->AddHashEntry((void *)vtkJavaIdCount,ptr); vtkTypecastLookup->AddHashEntry((void *)vtkJavaIdCount,tcFunc); vtkPointerLookup->AddHashEntry(ptr,(void *)env->NewGlobalRef(obj)); vtkDeleteLookup->AddHashEntry((void *)vtkJavaIdCount,(void *)deleteMe); vtkJavaSetId(env,obj,vtkJavaIdCount); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Added object to hash id= " << vtkJavaIdCount << " " << ptr); #endif vtkJavaIdCount++; VTK_RELEASE_MUTEX(); } // should we delete this object int vtkJavaShouldIDeleteObject(JNIEnv *env,jobject obj) { int id = vtkJavaGetId(env,obj); VTK_GET_MUTEX(); if ((int)(vtkDeleteLookup->GetHashTableValue((void *)id))) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Decided to delete id = " << id); #endif vtkJavaDeleteObjectFromHash(env, id); VTK_RELEASE_MUTEX(); return 1; } #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Decided to NOT delete id = " << id); #endif vtkJavaDeleteObjectFromHash(env, id); VTK_RELEASE_MUTEX(); return 0; } // delete an object from the hash void vtkJavaDeleteObjectFromHash(JNIEnv *env, int id) { void *ptr; void *vptr; ptr = vtkInstanceLookup->GetHashTableValue((void *)id); if (!ptr) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Attempt to delete an object that doesnt exist!!!"); #endif return; } vtkInstanceLookup->DeleteHashEntry((void *)id); vtkTypecastLookup->DeleteHashEntry((void *)id); vptr = vtkPointerLookup->GetHashTableValue(ptr); env->DeleteGlobalRef((jobject)&vptr); vtkPointerLookup->DeleteHashEntry(ptr); vtkDeleteLookup->DeleteHashEntry((void *)id); } jobject vtkJavaGetObjectFromPointer(void *ptr) { jobject obj; #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into pointer " << ptr); #endif obj = (jobject)vtkPointerLookup->GetHashTableValue((jobject *)ptr); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into pointer " << ptr << " obj = " << obj); #endif return obj; } void *vtkJavaGetPointerFromObject(JNIEnv *env, jobject obj, char *result_type) { void *ptr; void *(*command)(void *,char *); int id; id = vtkJavaGetId(env,obj); ptr = vtkInstanceLookup->GetHashTableValue((void *)id); command = (void *(*)(void *,char *))vtkTypecastLookup->GetHashTableValue((void *)id); #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Checking into id " << id << " ptr = " << ptr); #endif if (!ptr) { return NULL; } if (command(ptr,result_type)) { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("Got id= " << id << " ptr= " << ptr << " " << result_type); #endif return command(ptr,result_type); } else { #ifdef VTKJAVADEBUG vtkGenericWarningMacro("vtk bad argument, type conversion failed."); #endif return NULL; } } jarray vtkJavaMakeJArrayOfDoubleFromDouble(JNIEnv *env, double *ptr, int size) { jdoubleArray ret; int i; jdouble *array; ret = env->NewDoubleArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetDoubleArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseDoubleArrayElements(ret,array,0); return ret; } jarray vtkJavaMakeJArrayOfDoubleFromFloat(JNIEnv *env, float *ptr, int size) { jdoubleArray ret; int i; jdouble *array; ret = env->NewDoubleArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetDoubleArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseDoubleArrayElements(ret,array,0); return ret; } jarray vtkJavaMakeJArrayOfIntFromInt(JNIEnv *env, int *ptr, int size) { jintArray ret; int i; jint *array; ret = env->NewIntArray(size); if (ret == 0) { // should throw an exception here return 0; } array = env->GetIntArrayElements(ret,NULL); // copy the data for (i = 0; i < size; i++) { array[i] = ptr[i]; } env->ReleaseIntArrayElements(ret,array,0); return ret; } char *vtkJavaUTFToChar(JNIEnv *env,jstring in) { char *result; const char *inBytes; int length, i; int resultLength = 1; length = env->GetStringUTFLength(in); inBytes = env->GetStringUTFChars(in,NULL); for (i = 0; i < length; i++) { if ((inBytes[i] >= 0)&&(inBytes[i] < 128 )) resultLength++; } result = new char [resultLength]; resultLength = 0; // the 0 versus 1 up above is on purpose for (i = 0; i < length; i++) { if ((inBytes[i] >= 0)&&(inBytes[i] < 128 )) { result[resultLength] = inBytes[i]; resultLength++; } } result[resultLength] = '\0'; env->ReleaseStringUTFChars(in,inBytes); return result; } jstring vtkJavaMakeJavaString(JNIEnv *env, const char *in) { jstring result; char *utf; int inLength, utfLength, i; inLength = strlen(in); utfLength = inLength + 2; utf = new char [utfLength]; for (i = 0; i < inLength; i++) { utf[i] = in[i]; } utf[inLength] = 0xC0; utf[inLength+1] = 0x80; result = env->NewStringUTF(utf); // do we need to free utf here ? Does JNI make a copy ? return result; } //**jcp this is the callback inteface stub for Java. no user parms are passed //since the callback must be a method of a class. We make the rash assumption //that the <this> pointer will anchor any required other elements for the //called functions. - edited by km void vtkJavaVoidFunc(void* f) { vtkJavaVoidFuncArg *iprm = (vtkJavaVoidFuncArg *)f; // make sure we have a valid method ID if (iprm->mid) { iprm->uenv->CallVoidMethod(iprm->uobj,iprm->mid); } } void vtkJavaVoidFuncArgDelete(void* arg) { vtkJavaVoidFuncArg *arg2; arg2 = (vtkJavaVoidFuncArg *)arg; // free the structure arg2->uenv->DeleteGlobalRef(arg2->uobj); delete arg2; } <|endoftext|>
<commit_before>/*------------gauss_vis.cpp----------------------------------------------------/ * * Purpose: Simple visualization script for difference scenes for computus video * 2020 * * Notes: Compilation instructions: * g++ -L/path/to/GathVL -I/path/to/GathVL -lgathvl -o gauss_vis gauss_vis.cpp `pkg-config --cflags --libs cairo libavformat libavcodec libswresample libswscale libavutil` -Wl,-rpath,/path/to/GathVL * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <memory> #include <vector> #include "include/camera.h" #include "include/scene.h" void synodic_scene(camera& cam, scene& world, double end_frame, double timestep){ vec sun_size = {world.size.y*0.09, world.size.y*0.09}; vec earth_size = {world.size.y*0.045, world.size.y*0.045}; vec moon_size = {world.size.y*0.018, world.size.y*0.018}; color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc = sun_loc + earth_offset; vec moon_loc = earth_loc + moon_offset; auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, sun_size*1.1); sun->add_animator<vec_animator>(20,25, &sun->size, sun_size*1.1, sun_size); std::shared_ptr<ellipse> earth; std::shared_ptr<ellipse> moon; earth = std::make_shared<ellipse>(earth_clr, earth_loc, vec{0,0}, 0, true); earth->add_animator<vec_animator>(10,30, &earth->size, vec{0,0}, earth_size*1.1); earth->add_animator<vec_animator>(30,35, &earth->size, earth_size*1.1, earth_size); moon = std::make_shared<ellipse>(moon_clr, moon_loc, vec{0,0}, 0, true); moon->add_animator<vec_animator>(20,40, &moon->size, vec{0,0}, moon_size*1.1); moon->add_animator<vec_animator>(40,45, &moon->size, moon_size*1.1, moon_size); std::shared_ptr<arc> earth_shadows; std::shared_ptr<arc> moon_shadows; earth_shadows = std::make_shared<arc>(earth_loc, earth_size*0.95, vec{0,2*M_PI}); moon_shadows = std::make_shared<arc>(moon_loc, moon_size*0.95, vec{0,2*M_PI}); // Creating a theta for the earth that changes with time double earth_theta = M_PI/4; double moon_theta = M_PI/4; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_half_year_frames = gregorian_year_frames*29.53*6/365.2524; // creating line connecting sun and moon and adding animator auto synodic_line_0 = std::make_shared<line>(sun_loc, sun_loc); synodic_line_0->add_animator<vec_animator>(lunar_half_year_frames + 60, lunar_half_year_frames + 90, &synodic_line_0->end, sun_loc, moon_loc); for (int i = 50; i < lunar_half_year_frames + 51; ++i){ earth_theta -= earth_freq*timestep; moon_theta -= (moon_freq + earth_freq)*timestep; vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta), earth_radius*sin(earth_theta)); earth->add_animator<vec_animator>(i-1,i, &earth->location, earth_loc, new_loc); earth_loc = new_loc; new_loc = earth_loc + vec(moon_radius*cos(moon_theta), moon_radius*sin(moon_theta)); moon->add_animator<vec_animator>(i-1,i, &moon->location, moon_loc, new_loc); if (i < lunar_half_year_frames + 50){ moon_loc = new_loc; } } // Create line connecting sun and new moon auto synodic_line_1 = std::make_shared<line>(sun_loc, sun_loc); synodic_line_1->add_animator<vec_animator>(lunar_half_year_frames + 60, lunar_half_year_frames + 90, &synodic_line_1->end, sun_loc, moon_loc); world.add_layer(); world.add_layer(); world.add_object(sun, 1); world.add_object(earth, 2); world.add_object(moon, 2); world.add_object(synodic_line_0, 2); world.add_object(synodic_line_1, 2); for (int i = 0; i < end_frame; ++i){ world.update(i); if (i == 51){ world.add_object(earth_shadows, 1); world.add_object(moon_shadows, 1); } cam.encode_frame(world); } } void orbit_scene(camera& cam, scene& world, double end_frame, double timestep){ vec sun_size = {world.size.y*0.09, world.size.y*0.09}; vec earth_size = {world.size.y*0.045, world.size.y*0.045}; vec moon_size = {world.size.y*0.018, world.size.y*0.018}; color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc[3] = {sun_loc + earth_offset, vec(0,0), vec(0,0)}; vec moon_loc[3] = {earth_loc[0] + moon_offset, vec(0,0), vec(0,0)}; // Don't Judge Me! for (int i = 1; i < 3; ++i){ earth_loc[i] = earth_loc[0]; moon_loc[i] = moon_loc[0]; } auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, sun_size*1.1); sun->add_animator<vec_animator>(20,25, &sun->size, sun_size*1.1, sun_size); std::shared_ptr<ellipse> earth; std::shared_ptr<ellipse> moon; earth = std::make_shared<ellipse>(earth_clr, earth_loc[0], vec{0,0}, 0, true); earth->add_animator<vec_animator>(10,30, &earth->size, vec{0,0}, earth_size*1.1); earth->add_animator<vec_animator>(30,35, &earth->size, earth_size*1.1, earth_size); moon = std::make_shared<ellipse>(moon_clr, moon_loc[0], vec{0,0}, 0, true); moon->add_animator<vec_animator>(20,40, &moon->size, vec{0,0}, moon_size*1.1); moon->add_animator<vec_animator>(40,45, &moon->size, moon_size*1.1, moon_size); // Creating a theta for the earth that changes with time double earth_theta[2] = {M_PI/4, 0}; double moon_theta[2] = {M_PI/4, 0}; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_year_frames = gregorian_year_frames*29.53*12/365.2524; int indices = 2; for (int i = 50; i < gregorian_year_frames + 51; ++i){ //if (i > lunar_year_frames + 32){ if (i == floor(lunar_year_frames) + 51){ indices = 1; earth_theta[1] = fmod(earth_theta[0] + earth_freq*timestep, 2*M_PI); } earth_theta[0] -= earth_freq*timestep; moon_theta[0] -= (moon_freq + earth_freq)*timestep; for (int j = 0; j < indices; ++j){ vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta[0]), earth_radius*sin(earth_theta[0])); earth->add_animator<vec_animator>(i-1,i, &earth->location, earth_loc[0], new_loc); earth_loc[j] = new_loc; new_loc = earth_loc[0] + vec(moon_radius*cos(moon_theta[0]), moon_radius*sin(moon_theta[0])); moon->add_animator<vec_animator>(i-1,i, &moon->location, moon_loc[0], new_loc); moon_loc[j] = new_loc; } } moon_theta[1] = fmod(moon_theta[0] + (moon_freq+earth_freq)*timestep, 2*M_PI); moon_theta[0] = M_PI/4 + (moon_freq+earth_freq)*timestep; // Drawing the line for the Earths auto earth_arc = std::make_shared<arc>(sun_loc, vec(earth_radius,earth_radius), vec{0,0}); earth_arc->add_animator<vec_animator>(50+gregorian_year_frames, 80+gregorian_year_frames, &earth_arc->angles, vec{earth_theta[0], earth_theta[0]}, vec{earth_theta[0], earth_theta[1]}); // Drawing the line for the Earths auto moon_arc = std::make_shared<arc>(earth_loc[0], vec(moon_radius,moon_radius), vec{0,0}); moon_arc->add_animator<vec_animator>(90+gregorian_year_frames, 120+gregorian_year_frames, &moon_arc->angles, vec{moon_theta[1], moon_theta[1]}, vec{moon_theta[1], moon_theta[0]}); std::shared_ptr<arc> earth_shadows[2]; std::shared_ptr<arc> moon_shadows[2]; for (int i = 0; i < 2; ++i){ earth_shadows[i] = std::make_shared<arc>(earth_loc[i+1], earth_size*0.95, vec{0,2*M_PI}); moon_shadows[i] = std::make_shared<arc>(moon_loc[i+1], moon_size*0.95, vec{0,2*M_PI}); } world.add_layer(); world.add_layer(); world.add_object(sun, 1); world.add_object(earth, 2); world.add_object(moon, 2); for (int i = 0; i < end_frame; ++i){ world.update(i); if (i == 51){ world.add_object(earth_shadows[1], 1); world.add_object(moon_shadows[1], 1); } if (i == floor(lunar_year_frames) + 51){ world.add_object(earth_shadows[0], 1); world.add_object(moon_shadows[0], 1); } if (i == 50+floor(gregorian_year_frames)){ world.add_object(earth_arc, 2); } if (i == 90+floor(gregorian_year_frames)){ world.add_object(moon_arc, 2); } cam.encode_frame(world); } } int main() { camera cam(vec{1280, 720}); scene world = scene({1280, 720}, {0, 0, 0, 1}); cam.add_encoder<video_encoder>("/tmp/video.mp4", cam.size, 60); orbit_scene(cam, world, 1000, 0.1); //synodic_scene(cam, world, 2000, 0.025); cam.clear_encoders(); return 0; } <commit_msg>adding black version<commit_after>/*------------gauss_vis.cpp----------------------------------------------------/ * * Purpose: Simple visualization script for difference scenes for computus video * 2020 * * Notes: Compilation instructions: * g++ -L/path/to/GathVL -I/path/to/GathVL -lgathvl -o gauss_vis gauss_vis.cpp `pkg-config --cflags --libs cairo libavformat libavcodec libswresample libswscale libavutil` -Wl,-rpath,/path/to/GathVL * *-----------------------------------------------------------------------------*/ #include <iostream> #include <cmath> #include <memory> #include <vector> #include "include/camera.h" #include "include/scene.h" void synodic_scene(camera& cam, scene& world, double end_frame, double timestep){ vec sun_size = {world.size.y*0.09, world.size.y*0.09}; vec earth_size = {world.size.y*0.045, world.size.y*0.045}; vec moon_size = {world.size.y*0.018, world.size.y*0.018}; color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; color line_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc = sun_loc + earth_offset; vec moon_loc = earth_loc + moon_offset; auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, sun_size*1.1); sun->add_animator<vec_animator>(20,25, &sun->size, sun_size*1.1, sun_size); std::shared_ptr<ellipse> earth; std::shared_ptr<ellipse> moon; earth = std::make_shared<ellipse>(earth_clr, earth_loc, vec{0,0}, 0, true); earth->add_animator<vec_animator>(10,30, &earth->size, vec{0,0}, earth_size*1.1); earth->add_animator<vec_animator>(30,35, &earth->size, earth_size*1.1, earth_size); moon = std::make_shared<ellipse>(moon_clr, moon_loc, vec{0,0}, 0, true); moon->add_animator<vec_animator>(20,40, &moon->size, vec{0,0}, moon_size*1.1); moon->add_animator<vec_animator>(40,45, &moon->size, moon_size*1.1, moon_size); std::shared_ptr<arc> earth_shadows; std::shared_ptr<arc> moon_shadows; earth_shadows = std::make_shared<arc>(earth_loc, earth_size*0.95, vec{0,2*M_PI}); moon_shadows = std::make_shared<arc>(moon_loc, moon_size*0.95, vec{0,2*M_PI}); // Creating a theta for the earth that changes with time double earth_theta = M_PI/4; double moon_theta = M_PI/4; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_half_year_frames = gregorian_year_frames*29.53*6/365.2524; // creating line connecting sun and moon and adding animator auto synodic_line_0 = std::make_shared<line>(line_clr, sun_loc, sun_loc); synodic_line_0->add_animator<vec_animator>(lunar_half_year_frames + 60, lunar_half_year_frames + 90, &synodic_line_0->end, sun_loc, moon_loc); for (int i = 50; i < lunar_half_year_frames + 51; ++i){ earth_theta -= earth_freq*timestep; moon_theta -= (moon_freq + earth_freq)*timestep; vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta), earth_radius*sin(earth_theta)); earth->add_animator<vec_animator>(i-1,i, &earth->location, earth_loc, new_loc); earth_loc = new_loc; new_loc = earth_loc + vec(moon_radius*cos(moon_theta), moon_radius*sin(moon_theta)); moon->add_animator<vec_animator>(i-1,i, &moon->location, moon_loc, new_loc); if (i < lunar_half_year_frames + 50){ moon_loc = new_loc; } } // Create line connecting sun and new moon auto synodic_line_1 = std::make_shared<line>(line_clr, sun_loc, sun_loc); synodic_line_1->add_animator<vec_animator>(lunar_half_year_frames + 60, lunar_half_year_frames + 90, &synodic_line_1->end, sun_loc, moon_loc); world.add_layer(); world.add_layer(); world.add_object(sun, 1); world.add_object(earth, 2); world.add_object(moon, 2); for (int i = 0; i < end_frame; ++i){ world.update(i); if (i == 51){ world.add_object(earth_shadows, 1); world.add_object(moon_shadows, 1); } if (i == floor(lunar_half_year_frames) + 60){ world.add_object(synodic_line_0, 2); world.add_object(synodic_line_1, 2); } cam.encode_frame(world); } } void orbit_scene(camera& cam, scene& world, double end_frame, double timestep){ vec sun_size = {world.size.y*0.09, world.size.y*0.09}; vec earth_size = {world.size.y*0.045, world.size.y*0.045}; vec moon_size = {world.size.y*0.018, world.size.y*0.018}; color sun_clr = {1, 1, 0.5, 1}; color earth_clr = {0, 1, 1, 1}; color moon_clr = {0.5, 0.5, 0.5, 1}; double earth_radius = 200; double moon_radius = 100; vec earth_offset = vec{sqrt(earth_radius*earth_radius/2), sqrt(earth_radius*earth_radius/2)}; vec moon_offset = vec{sqrt(moon_radius*moon_radius/2), sqrt(moon_radius*moon_radius/2)}; vec sun_loc = {world.size.x/2, world.size.y/2}; vec earth_loc[3] = {sun_loc + earth_offset, vec(0,0), vec(0,0)}; vec moon_loc[3] = {earth_loc[0] + moon_offset, vec(0,0), vec(0,0)}; // Don't Judge Me! for (int i = 1; i < 3; ++i){ earth_loc[i] = earth_loc[0]; moon_loc[i] = moon_loc[0]; } auto sun = std::make_shared<ellipse>(sun_clr, sun_loc, vec{0,0}, 0, true); sun->add_animator<vec_animator>(0,20, &sun->size, vec{0,0}, sun_size*1.1); sun->add_animator<vec_animator>(20,25, &sun->size, sun_size*1.1, sun_size); std::shared_ptr<ellipse> earth; std::shared_ptr<ellipse> moon; earth = std::make_shared<ellipse>(earth_clr, earth_loc[0], vec{0,0}, 0, true); earth->add_animator<vec_animator>(10,30, &earth->size, vec{0,0}, earth_size*1.1); earth->add_animator<vec_animator>(30,35, &earth->size, earth_size*1.1, earth_size); moon = std::make_shared<ellipse>(moon_clr, moon_loc[0], vec{0,0}, 0, true); moon->add_animator<vec_animator>(20,40, &moon->size, vec{0,0}, moon_size*1.1); moon->add_animator<vec_animator>(40,45, &moon->size, moon_size*1.1, moon_size); // Creating a theta for the earth that changes with time double earth_theta[2] = {M_PI/4, 0}; double moon_theta[2] = {M_PI/4, 0}; double earth_freq = 0.1; double moon_freq = earth_freq*365*12/354; double gregorian_year_frames = 2*M_PI/earth_freq/timestep; double lunar_year_frames = gregorian_year_frames*29.53*12/365.2524; int indices = 2; for (int i = 50; i < gregorian_year_frames + 51; ++i){ //if (i > lunar_year_frames + 32){ if (i == floor(lunar_year_frames) + 51){ indices = 1; earth_theta[1] = fmod(earth_theta[0] + earth_freq*timestep, 2*M_PI); } earth_theta[0] -= earth_freq*timestep; moon_theta[0] -= (moon_freq + earth_freq)*timestep; for (int j = 0; j < indices; ++j){ vec new_loc = sun_loc + vec(earth_radius*cos(earth_theta[0]), earth_radius*sin(earth_theta[0])); earth->add_animator<vec_animator>(i-1,i, &earth->location, earth_loc[0], new_loc); earth_loc[j] = new_loc; new_loc = earth_loc[0] + vec(moon_radius*cos(moon_theta[0]), moon_radius*sin(moon_theta[0])); moon->add_animator<vec_animator>(i-1,i, &moon->location, moon_loc[0], new_loc); moon_loc[j] = new_loc; } } moon_theta[1] = fmod(moon_theta[0] + (moon_freq+earth_freq)*timestep, 2*M_PI); moon_theta[0] = M_PI/4 + (moon_freq+earth_freq)*timestep; // Drawing the line for the Earths auto earth_arc = std::make_shared<arc>(sun_loc, vec(earth_radius,earth_radius), vec{0,0}); earth_arc->add_animator<vec_animator>(50+gregorian_year_frames, 80+gregorian_year_frames, &earth_arc->angles, vec{earth_theta[0], earth_theta[0]}, vec{earth_theta[0], earth_theta[1]}); // Drawing the line for the Earths auto moon_arc = std::make_shared<arc>(earth_loc[0], vec(moon_radius,moon_radius), vec{0,0}); moon_arc->add_animator<vec_animator>(90+gregorian_year_frames, 120+gregorian_year_frames, &moon_arc->angles, vec{moon_theta[1], moon_theta[1]}, vec{moon_theta[1], moon_theta[0]}); std::shared_ptr<arc> earth_shadows[2]; std::shared_ptr<arc> moon_shadows[2]; for (int i = 0; i < 2; ++i){ earth_shadows[i] = std::make_shared<arc>(earth_loc[i+1], earth_size*0.95, vec{0,2*M_PI}); moon_shadows[i] = std::make_shared<arc>(moon_loc[i+1], moon_size*0.95, vec{0,2*M_PI}); } world.add_layer(); world.add_layer(); world.add_object(sun, 1); world.add_object(earth, 2); world.add_object(moon, 2); for (int i = 0; i < end_frame; ++i){ world.update(i); if (i == 51){ world.add_object(earth_shadows[1], 1); world.add_object(moon_shadows[1], 1); } if (i == floor(lunar_year_frames) + 51){ world.add_object(earth_shadows[0], 1); world.add_object(moon_shadows[0], 1); } if (i == 50+floor(gregorian_year_frames)){ world.add_object(earth_arc, 2); } if (i == 90+floor(gregorian_year_frames)){ world.add_object(moon_arc, 2); } cam.encode_frame(world); } } int main() { camera cam(vec{1280, 720}); scene world = scene({1280, 720}, {0, 0, 0, 1}); //world.bg_clr = {1,1,1,1}; cam.add_encoder<video_encoder>("/tmp/video.mp4", cam.size, 60); //orbit_scene(cam, world, 1000, 0.1); synodic_scene(cam, world, 4000, 0.01); cam.clear_encoders(); return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <mpi.h> #include <cstring> #include <cassert> const int SHIFT = 32; const unsigned long long BASE = (unsigned long long)1 << SHIFT; int VALID = 1000000; int LEN = VALID / 8 + 2; void add(unsigned long long dest[], unsigned src[]) { for (int i = LEN - 1; i >= 0; i--) if (dest[i] >= BASE - src[i]) { assert(i && "Oh carry overflow!"); dest[i] = (long long)dest[i] + src[i] - BASE; dest[i - 1]++; } else { dest[i] += src[i]; } } void minus(unsigned long long dest[], unsigned src[]) { bool borrow = false; for (int i = LEN - 1; i >= 0; i--) if (dest[i] < src[i] + (borrow? 1: 0)) { assert(i && "Oh borrow overflow!"); dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0); borrow = true; } else { dest[i] = dest[i] - src[i] - (borrow? 1: 0); borrow = false; } } void multiply(unsigned dest[], unsigned num) { unsigned carry = 0; for (int i = LEN - 1; i >= 0; i--) { unsigned long long tmp = (unsigned long long)num * dest[i] + carry; assert((tmp & (BASE - 1)) < BASE && "multiply truncation"); dest[i] = (tmp & (BASE - 1)); carry = tmp >> SHIFT; assert((i || !carry) && "Oh multiply overflow!"); } } void divide(unsigned dest[], unsigned num) { unsigned long long s = 0; for (int i = 0; i < LEN; i++) { s <<= SHIFT; s += dest[i]; if (s >= num) { assert(s / num < BASE && "divide truncation"); dest[i] = s / num; s %= num; } else { dest[i] = 0; } } } void test_multiply_divide() { unsigned *ptr = new unsigned[LEN]; for (int i = 0; i < LEN; i++) ptr[i] = i; unsigned num = 123454321; multiply(ptr, num); divide(ptr, num); for (int i = 0; i < LEN; i++) assert(ptr[i] == (unsigned)i && "multiply or divide error."); delete[] ptr; } void test_add_minus() { unsigned long long *ptr = new unsigned long long[LEN]; unsigned *ptr2 = new unsigned[LEN]; for (int i = 0; i < LEN; i++) { ptr[i] = LEN - i; ptr2[i] = ptr[i] + 1; } ptr[0] = 1, ptr2[0] = 0; minus(ptr, ptr2); assert(ptr[0] == 0 && "ptr[0] minus error."); assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error."); for (int i = 1; i < LEN - 1; i++) assert(ptr[i] == BASE - 2 && "substraction error."); add(ptr, ptr2); assert(ptr[0] == 1 && "ptr[0] add error."); for (int i = 1; i < LEN; i++) assert(ptr[i] == (unsigned)LEN - i && "addition error."); delete[] ptr; delete[] ptr2; } inline void print(unsigned num) { for (int pos = SHIFT - 4; pos >= 0; pos -= 4) printf("%01X", (num >> pos) & 0xF); } void test_print() { unsigned tmp = 180150013; print(tmp); } inline void output(unsigned long long array[]) { printf("%llu.\n", array[0]); int digit = 0; for (int i = 1; digit < VALID; i++) for (int pos = SHIFT - 4; pos >= 0; pos -= 4) { printf("%01X", ((unsigned)array[i] >> pos) & 0xF); if (++digit % 64 == 0) printf("\n"); } printf("\n"); } void shift_right(unsigned sub[], unsigned num) { unsigned uint_bit = 8 * sizeof(unsigned); if (LEN * uint_bit <= num) { memset(sub, 0, sizeof(unsigned) * LEN); return; } if (num >= uint_bit) { memmove(sub + num / uint_bit, sub, sizeof(unsigned) * LEN - num / uint_bit * sizeof(unsigned)); memset(sub, 0, num / uint_bit * sizeof(unsigned)); } unsigned mod = num % uint_bit; unsigned mask = (1 << mod) - 1; for (int i = LEN - 1; i > 0; i--) { sub[i] >>= mod; sub[i] |= (sub[i - 1] & mask) << (uint_bit - mod); } sub[0] >>= mod; } //TODO void test_shift_right() { unsigned *sub = new unsigned[LEN]; for (int i = 0; i < LEN; i++) sub[i] = 0xFFFFFFFF; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 1) + 6); assert(sub[LEN - 1] == 0x3FFFFFF && "shift error."); for (int i = 0; i < LEN - 1; i++) assert(sub[i] == 0 && "shift error."); for (int i = 0; i < LEN; i++) sub[i] = 0xABCDDCBE; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 2) + 4); assert(sub[LEN - 2] == 0xABCDDCB && "shift error."); assert(sub[LEN - 1] == 0xEABCDDCB && "shift error."); for (int i = 0; i < LEN - 2; i++) assert(sub[i] == 0 && "shift error."); delete[] sub; sub = new unsigned[3]; sub[0] = 0; sub[1] = 0x19999999; sub[2] = 0x99999999; shift_right(sub, 8); assert(sub[1] == 0x00199999 && "shift error!"); assert(sub[2] == 0x99999999 && "shift error!"); delete[] sub; } void cal_fraction(unsigned sub[], unsigned numerator, unsigned denominator, unsigned bit_num) { memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = numerator; divide(sub, denominator); shift_right(sub, bit_num); } bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; unsigned bit_num = 10 * k + 6; assert((unsigned long long)k * 10 + 9 < BASE && "sub Pi overflow."); cal_fraction(sub, 256, 10 * k + 1, bit_num); if (k & 1) minus(Pi, sub); else add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } cal_fraction(sub, 32, 4 * k + 1, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 1, 4 * k + 3, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 64, 10 * k + 3, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 4, 10 * k + 5, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 4, 10 * k + 7, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 1, 10 * k + 9, bit_num); if (k & 1) minus(Pi, sub); else add(Pi, sub); delete[] sub; return true; } /* BBP formula bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; assert((unsigned long long)k * 8 + 6 < BASE && "sub Pi overflow."); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 8 * k + 1); shift_right(sub, 4 * k); add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 2; divide(sub, 8 * k + 4); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 5); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 6); shift_right(sub, 4 * k); minus(Pi, sub); delete[] sub; return true; } */ void Pi_carry(unsigned long long Pi[]) { for (int i = LEN - 1; i >= 0; i--) if (Pi[i] >= BASE) { assert(i && "long long Pi overflow."); Pi[i - 1] += (Pi[i] & ~(BASE - 1)) >> SHIFT; Pi[i] &= (BASE - 1); } } void test_carray() { unsigned long long *ptr = new unsigned long long[LEN]; ptr[0] = 0; ptr[1] = 0xFFFFFFFFFF; Pi_carry(ptr); assert(ptr[0] == 0xFF && "carry error."); assert(ptr[1] == 0xFFFFFFFF && "carry error."); delete[] ptr; } int main(int argc, char *argv[]) { /* test_add_minus(); test_multiply_divide(); test_print(); test_shift_right(); test_carray(); */ double elapsed_time; MPI_Init(&argc, &argv); if (argc == 2) { VALID = atoi(argv[1]); LEN = VALID / 8 + 2; } unsigned long long *sub_Pi = new unsigned long long[LEN]; unsigned long long *Pi = new unsigned long long[LEN]; int compensation = 10; sub_Pi[0] = compensation; MPI_Barrier(MPI_COMM_WORLD); elapsed_time = -MPI_Wtime(); int size, id; MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &size); for (unsigned k = id; cal_sub_Pi(sub_Pi, k); k += size); MPI_Reduce(sub_Pi, Pi, LEN, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); elapsed_time += MPI_Wtime(); if (!id) { Pi[0] -= compensation * size; Pi_carry(Pi); output(Pi); printf("%.3fs\n", elapsed_time); } delete[] sub_Pi; delete[] Pi; MPI_Finalize(); return 0; } <commit_msg>unit test optimization<commit_after>#include <cstdio> #include <cstdlib> #include <mpi.h> #include <cstring> #include <cassert> const int SHIFT = 32; const unsigned long long BASE = (unsigned long long)1 << SHIFT; int VALID = 1000000; int LEN = VALID / 8 + 2; void add(unsigned long long dest[], unsigned src[]) { for (int i = LEN - 1; i >= 0; i--) if (dest[i] >= BASE - src[i]) { assert(i && "Oh carry overflow!"); dest[i] = (long long)dest[i] + src[i] - BASE; dest[i - 1]++; } else { dest[i] += src[i]; } } void minus(unsigned long long dest[], unsigned src[]) { bool borrow = false; for (int i = LEN - 1; i >= 0; i--) if (dest[i] < src[i] + (borrow? 1: 0)) { assert(i && "Oh borrow overflow!"); dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0); borrow = true; } else { dest[i] = dest[i] - src[i] - (borrow? 1: 0); borrow = false; } } void multiply(unsigned dest[], unsigned num) { unsigned carry = 0; for (int i = LEN - 1; i >= 0; i--) { unsigned long long tmp = (unsigned long long)num * dest[i] + carry; assert((tmp & (BASE - 1)) < BASE && "multiply truncation"); dest[i] = (tmp & (BASE - 1)); carry = tmp >> SHIFT; assert((i || !carry) && "Oh multiply overflow!"); } } void divide(unsigned dest[], unsigned num) { unsigned long long s = 0; for (int i = 0; i < LEN; i++) { s <<= SHIFT; s += dest[i]; if (s >= num) { assert(s / num < BASE && "divide truncation"); dest[i] = s / num; s %= num; } else { dest[i] = 0; } } } inline void print(unsigned num) { for (int pos = SHIFT - 4; pos >= 0; pos -= 4) printf("%01X", (num >> pos) & 0xF); } void test_print() { unsigned tmp = 180150013; print(tmp); } inline void output(unsigned long long array[]) { printf("%llu.\n", array[0]); int digit = 0; for (int i = 1; digit < VALID; i++) for (int pos = SHIFT - 4; pos >= 0; pos -= 4) { printf("%01X", ((unsigned)array[i] >> pos) & 0xF); if (++digit % 64 == 0) printf("\n"); } printf("\n"); } void shift_right(unsigned sub[], unsigned num) { unsigned uint_bit = 8 * sizeof(unsigned); if (LEN * uint_bit <= num) { memset(sub, 0, sizeof(unsigned) * LEN); return; } if (num >= uint_bit) { memmove(sub + num / uint_bit, sub, sizeof(unsigned) * LEN - num / uint_bit * sizeof(unsigned)); memset(sub, 0, num / uint_bit * sizeof(unsigned)); } unsigned mod = num % uint_bit; unsigned mask = (1 << mod) - 1; for (int i = LEN - 1; i > 0; i--) { sub[i] >>= mod; sub[i] |= (sub[i - 1] & mask) << (uint_bit - mod); } sub[0] >>= mod; } void cal_fraction(unsigned sub[], unsigned numerator, unsigned denominator, unsigned bit_num) { memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = numerator; divide(sub, denominator); shift_right(sub, bit_num); } bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; unsigned bit_num = 10 * k + 6; assert((unsigned long long)k * 10 + 9 < BASE && "sub Pi overflow."); cal_fraction(sub, 256, 10 * k + 1, bit_num); if (k & 1) minus(Pi, sub); else add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } cal_fraction(sub, 32, 4 * k + 1, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 1, 4 * k + 3, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 64, 10 * k + 3, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 4, 10 * k + 5, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 4, 10 * k + 7, bit_num); if (k & 1) add(Pi, sub); else minus(Pi, sub); cal_fraction(sub, 1, 10 * k + 9, bit_num); if (k & 1) minus(Pi, sub); else add(Pi, sub); delete[] sub; return true; } void Pi_carry(unsigned long long Pi[]) { for (int i = LEN - 1; i >= 0; i--) if (Pi[i] >= BASE) { assert(i && "long long Pi overflow."); Pi[i - 1] += (Pi[i] & ~(BASE - 1)) >> SHIFT; Pi[i] &= (BASE - 1); } } /* BBP formula bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; assert((unsigned long long)k * 8 + 6 < BASE && "sub Pi overflow."); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 8 * k + 1); shift_right(sub, 4 * k); add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 2; divide(sub, 8 * k + 4); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 5); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 6); shift_right(sub, 4 * k); minus(Pi, sub); delete[] sub; return true; } */ #ifdef DEBUG void test_carray() { unsigned long long *ptr = new unsigned long long[LEN]; ptr[0] = 0; ptr[1] = 0xFFFFFFFFFF; Pi_carry(ptr); assert(ptr[0] == 0xFF && "carry error."); assert(ptr[1] == 0xFFFFFFFF && "carry error."); delete[] ptr; } void test_multiply_divide() { unsigned *ptr = new unsigned[LEN]; for (int i = 0; i < LEN; i++) ptr[i] = i; unsigned num = 123454321; multiply(ptr, num); divide(ptr, num); for (int i = 0; i < LEN; i++) assert(ptr[i] == (unsigned)i && "multiply or divide error."); delete[] ptr; } void test_add_minus() { unsigned long long *ptr = new unsigned long long[LEN]; unsigned *ptr2 = new unsigned[LEN]; for (int i = 0; i < LEN; i++) { ptr[i] = LEN - i; ptr2[i] = ptr[i] + 1; } ptr[0] = 1, ptr2[0] = 0; minus(ptr, ptr2); assert(ptr[0] == 0 && "ptr[0] minus error."); assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error."); for (int i = 1; i < LEN - 1; i++) assert(ptr[i] == BASE - 2 && "substraction error."); add(ptr, ptr2); assert(ptr[0] == 1 && "ptr[0] add error."); for (int i = 1; i < LEN; i++) assert(ptr[i] == (unsigned)LEN - i && "addition error."); delete[] ptr; delete[] ptr2; } void test_shift_right() { unsigned *sub = new unsigned[LEN]; for (int i = 0; i < LEN; i++) sub[i] = 0xFFFFFFFF; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 1) + 6); assert(sub[LEN - 1] == 0x3FFFFFF && "shift error."); for (int i = 0; i < LEN - 1; i++) assert(sub[i] == 0 && "shift error."); for (int i = 0; i < LEN; i++) sub[i] = 0xABCDDCBE; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 2) + 4); assert(sub[LEN - 2] == 0xABCDDCB && "shift error."); assert(sub[LEN - 1] == 0xEABCDDCB && "shift error."); for (int i = 0; i < LEN - 2; i++) assert(sub[i] == 0 && "shift error."); sub[0] = 0; sub[1] = 0x19999999; sub[2] = 0x99999999; shift_right(sub, 8); assert(sub[1] == 0x00199999 && "shift error!"); assert(sub[2] == 0x99999999 && "shift error!"); delete[] sub; } #endif int main(int argc, char *argv[]) { #ifdef DEBUG test_add_minus(); test_multiply_divide(); test_print(); test_shift_right(); test_carray(); #else double elapsed_time; MPI_Init(&argc, &argv); if (argc == 2) { VALID = atoi(argv[1]); LEN = VALID / 8 + 2; } unsigned long long *sub_Pi = new unsigned long long[LEN]; unsigned long long *Pi = new unsigned long long[LEN]; int compensation = 10; sub_Pi[0] = compensation; MPI_Barrier(MPI_COMM_WORLD); elapsed_time = -MPI_Wtime(); int size, id; MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &size); for (unsigned k = id; cal_sub_Pi(sub_Pi, k); k += size); MPI_Reduce(sub_Pi, Pi, LEN, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); elapsed_time += MPI_Wtime(); if (!id) { Pi[0] -= compensation * size; Pi_carry(Pi); output(Pi); printf("%.3fs\n", elapsed_time); } delete[] sub_Pi; delete[] Pi; MPI_Finalize(); #endif return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief Predicate --- Dot 2 implementation. * * @author Christopher Alfeld <calfeld@qualys.com> */ #include <predicate/dot2.hpp> #include <predicate/merge_graph.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> using namespace std; namespace IronBee { namespace Predicate { namespace { //! List of const nodes. typedef list<node_cp> node_clist_t; /** * Determine if @a node can be absorbed. * * An absorbable node will be included in its parents label and will not be * rendered as a discrete node. * * @param[in] node Node to check. * @param[in] G Graph; used to check if @a node is a root. * @param[in] root_namer Root namer; used to check if one is defined. * @return true iff @a node should be absorbed into parent rendering. **/ bool is_absorbable( const node_cp& node, const MergeGraph& G, root_namer_t root_namer ) { if (! node->is_literal()) { return false; } try { G.root_indices(node); } catch (enoent) { // Not a root. return node->is_literal(); } // Root return ! root_namer; } /** * Generic HTML escaping routine. * * Turns various HTML special characters into their HTML escapes. This * routine should be used for any text that comes from the rest of Predicate, * especially user defined sexpressions that may include literals with HTML * escapes. * * @param[in] src Text to escape. * @return @a src with special characters escaped. **/ string escape_html( const string& src ) { string result; BOOST_FOREACH(char c, src) { switch (c) { case '&': result += "&amp;"; break; case '"': result += "&quot;"; break; case '\'': result += "&apos;"; break; case '<': result += "&lt;"; break; case '>': result += "&gt;"; break; case '\\': result += "\\\\"; break; default: result += (boost::format("%c") % c).str(); } } return result; } //! Construct unicode glyph for a circled number @a n (@a n <= 20). string circle_n( unsigned int n ) { if (n == 0) { return "%#9450;"; } else if (n > 20) { BOOST_THROW_EXCEPTION( einval() << errinfo_what("Cannot circle numbers above 20.") ); } else { return (boost::format("&#%d;") % (9311 + n)).str(); } } //! Render a node. void render_node( ostream& out, const node_cp& node, const string& attrs ) { out << " \"" << node << "\" [" << attrs << "];" << endl; } //! Render a literal. void render_literal( ostream& out, const node_cp& node ) { render_node(out, node, "label=<" + escape_html(node->to_s()) + ">"); } //! Render an edge. void render_edge( ostream& out, const node_cp& from, const node_cp& to, const string& label = string() ) { out << " \"" << from << "\" -> \"" << to << "\""; if (! label.empty()) { out << " [label=<" << label << ">]"; } out << ";" << endl; } //! Render roots. void render_roots( ostream& out, const node_cp& node, const MergeGraph& G, root_namer_t root_namer ) { if (! root_namer) { return; } try { BOOST_FOREACH(size_t index, G.root_indices(node)) { string name = root_namer(index); out << " \"root-" << index << "\" [" << "fontname=\"Times-Roman\", shape=none, label=<" << escape_html(name) << ">];" << endl; out << " \"root-" << index << "\" -> \"" << node << "\" [" << "style=dotted, dir=none];" << endl; } } catch (enoent) {} } //! Render a validation report. void render_report( ostream& out, const string& report, const node_cp& node ) { out << " { rank = same; \"" << node << "\" \"report-" << node << "\" }" << endl; out << " \"report-" << node << "\" [" << "fontsize=10, shape=none, " << "label=<<table border=\"0\" cellborder=\"0\">" << report << "</table>>];\n"; out << " \"" << node << "\" -> \"report-" << node << "\" [" << " weight=1000, dir=none, penwidth=0.5];\n"; } //! Validation status of a node. enum status_t { STATUS_OK, STATUS_WARN, STATUS_ERROR }; /** * Reporter; generates Dot reports for use with render_report(). * * @param[out] status Status of node. * @param[out] report Report for node. * @param[in] is_error Is an error being reported? * @param[in] message Message. **/ void dot_reporter( status_t& status, string& report, bool is_error, const string& message ) { status = is_error ? STATUS_ERROR : STATUS_WARN; report += string("<tr><td><font color=\"") + (is_error ? "red" : "orange") + "\">" + escape_html(message) + "</font></td></tr>"; } /** * Render a Value. * * @param[out] out Where to write. * @param[in] value What to write. **/ void render_value( ostream& out, const Value& value ); /** * Render a list of values. * * @param[out] out Where to write. * @param[in] values What to write. **/ void render_valuelist( ostream& out, const ValueList& values ) { out << "<table border=\"0\">"; BOOST_FOREACH(const Value& value, values) { out << "<tr><td align=\"right\">" << escape_html(value.name_as_s()) << "</td><td align=\"left\">"; render_value(out, value); out << "</td></tr>"; } out << "</table>"; } void render_value( ostream& out, const Value& value ) { if (value.type() != Value::LIST) { out << escape_html(value.to_s()); } else { render_valuelist(out, value.value_as_list<Value>()); } } /** * Render values of a node. * * @param[out] out Where to write. * @param[in] node Node to write values of. **/ void render_values( ostream& out, const node_cp& node ) { out << " { rank = same; \"" << node << "\" \"value-" << node << "\" }" << endl << " \"" << node << "\" -> \"value-" << node << "\" [weight=1000, dir=none, penwidth=0.5];\n" << " \"value-" << node << "\" [" << "fontsize=10, shape=none, label=<"; render_valuelist(out, node->values()); out << ">];" << endl; } /** * Node hook. * * First argument is output stream to output additional dot *before* node. * Second argument is a string of additional node properties. * Third argument is is the node itself. **/ typedef boost::function<void(ostream&, string&, const node_cp&)> node_hook_t; /** * Base to_dot2() routine. * * @param[in] out Where to write dot. * @param[in] G MergeGraph, used to detect roots. * @param[in] initial Initial vector for search. If empty, will default * to all nodes in graph. * @param[in] root_namer How to name roots. * @param[in] node_hook Additional rendering logic. **/ void to_dot2_base( ostream& out, const MergeGraph& G, const node_clist_t& initial, root_namer_t root_namer, node_hook_t node_hook ) { typedef set<node_cp> node_cset_t; node_clist_t queue; node_cset_t skip; if (! initial.empty()) { queue = initial; } else { copy(G.roots().first, G.roots().second, back_inserter(queue)); } // Header out << "digraph G {" << endl; out << " ordering = out;" << endl; out << " edge [arrowsize=0.5, fontsize=9];" << endl; out << " node [fontname=Courier, penwidth=0.2, shape=rect, height=0.4];" << endl; // Body while (! queue.empty()) { node_cp node = queue.front(); queue.pop_front(); if (skip.count(node)) { continue; } skip.insert(node); // If node is a literal... if (node->is_literal()) { render_literal(out, node); } else { boost::shared_ptr<const Call> call = boost::dynamic_pointer_cast<const Call>(node); assert(call); string extra; // Let node hook run. if (node_hook) { node_hook(out, extra, node); } // Otherwise node is a call. if (node->children().size() > 5) { // High degree nodes, have no absorbption. render_node(out, node, "label=<" + escape_html(call->name()) + ">" ); BOOST_FOREACH(const node_cp& child, node->children()) { render_edge(out, node, child); queue.push_back(child); } } else { // Try to absorb children. vector<string> name; name.push_back("<b>" + call->name() + "</b>"); unsigned int placeholder = 0; BOOST_FOREACH(const node_cp& child, node->children()) { if (is_absorbable(child, G, root_namer)) { if (child->to_s()[0] == '\'') { name.push_back( "<i>" + escape_html(child->to_s()) + "</i>" ); } else { name.push_back( "<font>" + escape_html(child->to_s()) + "</font>" ); } } else { ++placeholder; name.push_back( "<font>" + circle_n(placeholder) + "</font>" ); render_edge(out, node, child, circle_n(placeholder)); queue.push_back(child); } } render_node(out, node, "label=<" + boost::algorithm::join(name, " ") + ">" + extra ); } } render_roots(out, node, G, root_namer); } // Footer out << "}" << endl; } //! Node Hook: Validate void nh_validate( validation_e validate, ostream& out, string& extra, const node_cp& node ) { status_t status; string report; switch (validate) { case VALIDATE_NONE: return; case VALIDATE_PRE: node->pre_transform(NodeReporter( boost::bind( dot_reporter, boost::ref(status), boost::ref(report), _1, _2 ), node, false )); break; case VALIDATE_POST: node->post_transform(NodeReporter( boost::bind( dot_reporter, boost::ref(status), boost::ref(report), _1, _2 ), node, false )); break; }; switch (status) { case STATUS_OK: break; case STATUS_WARN: extra = ", style=filled, fillcolor=orange"; break; case STATUS_ERROR: extra = ", style=filled, fillcolor=red"; break; }; if (status != STATUS_OK) { render_report(out, report, node); } } //! Node Hook: Value void nh_value( ostream& out, string& extra, const node_cp& node ) { const ValueList& values = node->values(); bool finished = node->is_finished(); list<string> styles; if (finished) { styles.push_back("diagonals"); } if (! values.empty()) { styles.push_back("filled"); extra += ", fillcolor=\"#BDECB6\""; render_values(out, node); } if (! styles.empty()) { extra += ", style=\"" + boost::algorithm::join(styles, ",") + "\""; } } } void to_dot2( ostream& out, const MergeGraph& G, root_namer_t root_namer ) { to_dot2_base(out, G, node_clist_t(), root_namer, node_hook_t()); } void to_dot2_validate( ostream& out, const MergeGraph& G, validation_e validate, root_namer_t root_namer ) { to_dot2_base(out, G, node_clist_t(), root_namer, bind(nh_validate, validate, _1, _2, _3) ); } void to_dot2_value( ostream& out, const MergeGraph& G, const node_clist_t& initial, root_namer_t root_namer ) { to_dot2_base(out, G, initial, root_namer, nh_value); } } // Predicate } // IronBee <commit_msg>predicate/dot2: Fix uninitialized variable.<commit_after>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief Predicate --- Dot 2 implementation. * * @author Christopher Alfeld <calfeld@qualys.com> */ #include <predicate/dot2.hpp> #include <predicate/merge_graph.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> using namespace std; namespace IronBee { namespace Predicate { namespace { //! List of const nodes. typedef list<node_cp> node_clist_t; /** * Determine if @a node can be absorbed. * * An absorbable node will be included in its parents label and will not be * rendered as a discrete node. * * @param[in] node Node to check. * @param[in] G Graph; used to check if @a node is a root. * @param[in] root_namer Root namer; used to check if one is defined. * @return true iff @a node should be absorbed into parent rendering. **/ bool is_absorbable( const node_cp& node, const MergeGraph& G, root_namer_t root_namer ) { if (! node->is_literal()) { return false; } try { G.root_indices(node); } catch (enoent) { // Not a root. return node->is_literal(); } // Root return ! root_namer; } /** * Generic HTML escaping routine. * * Turns various HTML special characters into their HTML escapes. This * routine should be used for any text that comes from the rest of Predicate, * especially user defined sexpressions that may include literals with HTML * escapes. * * @param[in] src Text to escape. * @return @a src with special characters escaped. **/ string escape_html( const string& src ) { string result; BOOST_FOREACH(char c, src) { switch (c) { case '&': result += "&amp;"; break; case '"': result += "&quot;"; break; case '\'': result += "&apos;"; break; case '<': result += "&lt;"; break; case '>': result += "&gt;"; break; case '\\': result += "\\\\"; break; default: result += (boost::format("%c") % c).str(); } } return result; } //! Construct unicode glyph for a circled number @a n (@a n <= 20). string circle_n( unsigned int n ) { if (n == 0) { return "%#9450;"; } else if (n > 20) { BOOST_THROW_EXCEPTION( einval() << errinfo_what("Cannot circle numbers above 20.") ); } else { return (boost::format("&#%d;") % (9311 + n)).str(); } } //! Render a node. void render_node( ostream& out, const node_cp& node, const string& attrs ) { out << " \"" << node << "\" [" << attrs << "];" << endl; } //! Render a literal. void render_literal( ostream& out, const node_cp& node ) { render_node(out, node, "label=<" + escape_html(node->to_s()) + ">"); } //! Render an edge. void render_edge( ostream& out, const node_cp& from, const node_cp& to, const string& label = string() ) { out << " \"" << from << "\" -> \"" << to << "\""; if (! label.empty()) { out << " [label=<" << label << ">]"; } out << ";" << endl; } //! Render roots. void render_roots( ostream& out, const node_cp& node, const MergeGraph& G, root_namer_t root_namer ) { if (! root_namer) { return; } try { BOOST_FOREACH(size_t index, G.root_indices(node)) { string name = root_namer(index); out << " \"root-" << index << "\" [" << "fontname=\"Times-Roman\", shape=none, label=<" << escape_html(name) << ">];" << endl; out << " \"root-" << index << "\" -> \"" << node << "\" [" << "style=dotted, dir=none];" << endl; } } catch (enoent) {} } //! Render a validation report. void render_report( ostream& out, const string& report, const node_cp& node ) { out << " { rank = same; \"" << node << "\" \"report-" << node << "\" }" << endl; out << " \"report-" << node << "\" [" << "fontsize=10, shape=none, " << "label=<<table border=\"0\" cellborder=\"0\">" << report << "</table>>];\n"; out << " \"" << node << "\" -> \"report-" << node << "\" [" << " weight=1000, dir=none, penwidth=0.5];\n"; } //! Validation status of a node. enum status_t { STATUS_OK, STATUS_WARN, STATUS_ERROR }; /** * Reporter; generates Dot reports for use with render_report(). * * @param[out] status Status of node. * @param[out] report Report for node. * @param[in] is_error Is an error being reported? * @param[in] message Message. **/ void dot_reporter( status_t& status, string& report, bool is_error, const string& message ) { status = is_error ? STATUS_ERROR : STATUS_WARN; report += string("<tr><td><font color=\"") + (is_error ? "red" : "orange") + "\">" + escape_html(message) + "</font></td></tr>"; } /** * Render a Value. * * @param[out] out Where to write. * @param[in] value What to write. **/ void render_value( ostream& out, const Value& value ); /** * Render a list of values. * * @param[out] out Where to write. * @param[in] values What to write. **/ void render_valuelist( ostream& out, const ValueList& values ) { out << "<table border=\"0\">"; BOOST_FOREACH(const Value& value, values) { out << "<tr><td align=\"right\">" << escape_html(value.name_as_s()) << "</td><td align=\"left\">"; render_value(out, value); out << "</td></tr>"; } out << "</table>"; } void render_value( ostream& out, const Value& value ) { if (value.type() != Value::LIST) { out << escape_html(value.to_s()); } else { render_valuelist(out, value.value_as_list<Value>()); } } /** * Render values of a node. * * @param[out] out Where to write. * @param[in] node Node to write values of. **/ void render_values( ostream& out, const node_cp& node ) { out << " { rank = same; \"" << node << "\" \"value-" << node << "\" }" << endl << " \"" << node << "\" -> \"value-" << node << "\" [weight=1000, dir=none, penwidth=0.5];\n" << " \"value-" << node << "\" [" << "fontsize=10, shape=none, label=<"; render_valuelist(out, node->values()); out << ">];" << endl; } /** * Node hook. * * First argument is output stream to output additional dot *before* node. * Second argument is a string of additional node properties. * Third argument is is the node itself. **/ typedef boost::function<void(ostream&, string&, const node_cp&)> node_hook_t; /** * Base to_dot2() routine. * * @param[in] out Where to write dot. * @param[in] G MergeGraph, used to detect roots. * @param[in] initial Initial vector for search. If empty, will default * to all nodes in graph. * @param[in] root_namer How to name roots. * @param[in] node_hook Additional rendering logic. **/ void to_dot2_base( ostream& out, const MergeGraph& G, const node_clist_t& initial, root_namer_t root_namer, node_hook_t node_hook ) { typedef set<node_cp> node_cset_t; node_clist_t queue; node_cset_t skip; if (! initial.empty()) { queue = initial; } else { copy(G.roots().first, G.roots().second, back_inserter(queue)); } // Header out << "digraph G {" << endl; out << " ordering = out;" << endl; out << " edge [arrowsize=0.5, fontsize=9];" << endl; out << " node [fontname=Courier, penwidth=0.2, shape=rect, height=0.4];" << endl; // Body while (! queue.empty()) { node_cp node = queue.front(); queue.pop_front(); if (skip.count(node)) { continue; } skip.insert(node); // If node is a literal... if (node->is_literal()) { render_literal(out, node); } else { boost::shared_ptr<const Call> call = boost::dynamic_pointer_cast<const Call>(node); assert(call); string extra; // Let node hook run. if (node_hook) { node_hook(out, extra, node); } // Otherwise node is a call. if (node->children().size() > 5) { // High degree nodes, have no absorbption. render_node(out, node, "label=<" + escape_html(call->name()) + ">" ); BOOST_FOREACH(const node_cp& child, node->children()) { render_edge(out, node, child); queue.push_back(child); } } else { // Try to absorb children. vector<string> name; name.push_back("<b>" + call->name() + "</b>"); unsigned int placeholder = 0; BOOST_FOREACH(const node_cp& child, node->children()) { if (is_absorbable(child, G, root_namer)) { if (child->to_s()[0] == '\'') { name.push_back( "<i>" + escape_html(child->to_s()) + "</i>" ); } else { name.push_back( "<font>" + escape_html(child->to_s()) + "</font>" ); } } else { ++placeholder; name.push_back( "<font>" + circle_n(placeholder) + "</font>" ); render_edge(out, node, child, circle_n(placeholder)); queue.push_back(child); } } render_node(out, node, "label=<" + boost::algorithm::join(name, " ") + ">" + extra ); } } render_roots(out, node, G, root_namer); } // Footer out << "}" << endl; } //! Node Hook: Validate void nh_validate( validation_e validate, ostream& out, string& extra, const node_cp& node ) { status_t status = STATUS_OK; string report; switch (validate) { case VALIDATE_NONE: return; case VALIDATE_PRE: node->pre_transform(NodeReporter( boost::bind( dot_reporter, boost::ref(status), boost::ref(report), _1, _2 ), node, false )); break; case VALIDATE_POST: node->post_transform(NodeReporter( boost::bind( dot_reporter, boost::ref(status), boost::ref(report), _1, _2 ), node, false )); break; }; switch (status) { case STATUS_OK: break; case STATUS_WARN: extra = ", style=filled, fillcolor=orange"; break; case STATUS_ERROR: extra = ", style=filled, fillcolor=red"; break; }; if (status != STATUS_OK) { render_report(out, report, node); } } //! Node Hook: Value void nh_value( ostream& out, string& extra, const node_cp& node ) { const ValueList& values = node->values(); bool finished = node->is_finished(); list<string> styles; if (finished) { styles.push_back("diagonals"); } if (! values.empty()) { styles.push_back("filled"); extra += ", fillcolor=\"#BDECB6\""; render_values(out, node); } if (! styles.empty()) { extra += ", style=\"" + boost::algorithm::join(styles, ",") + "\""; } } } void to_dot2( ostream& out, const MergeGraph& G, root_namer_t root_namer ) { to_dot2_base(out, G, node_clist_t(), root_namer, node_hook_t()); } void to_dot2_validate( ostream& out, const MergeGraph& G, validation_e validate, root_namer_t root_namer ) { to_dot2_base(out, G, node_clist_t(), root_namer, bind(nh_validate, validate, _1, _2, _3) ); } void to_dot2_value( ostream& out, const MergeGraph& G, const node_clist_t& initial, root_namer_t root_namer ) { to_dot2_base(out, G, initial, root_namer, nh_value); } } // Predicate } // IronBee <|endoftext|>
<commit_before>namespace scheduler { inline Tag::Tag(libport::Symbol name) : parent_(0), blocked_(false), frozen_(false), name_(name) { } inline Tag::~Tag() { } inline Tag::Tag(const Tag&) { assert(false); } inline rTag Tag::fresh(libport::Symbol name) { rTag res = new Tag(name); return res; } inline rTag Tag::fresh(rTag parent, libport::Symbol name) { rTag res = new Tag(parent, name); return res; } inline bool Tag::frozen() const { return frozen_ || (parent_ && parent_->frozen()); } inline bool Tag::blocked() const { return blocked_ || (parent_ && parent_->blocked()); } inline bool Tag::derives_from(const Tag& other) const { return this == &other || (parent_ && parent_->derives_from(other)); } inline void Tag::freeze(Scheduler&) { frozen_ = true; } inline void Tag::unfreeze(Scheduler&) { frozen_ = false; } inline void Tag::block(Scheduler& sched, boost::any payload) { blocked_ = true; stop(sched, payload); } inline void Tag::unblock(Scheduler&) { blocked_ = false; } inline const libport::Symbol& Tag::name_get() const { return name_; } } // namespace scheduler <commit_msg>Initialize libport::RefCounted when cloning tag (with error).<commit_after>namespace scheduler { inline Tag::Tag(libport::Symbol name) : parent_(0), blocked_(false), frozen_(false), name_(name) { } inline Tag::~Tag() { } inline Tag::Tag(const Tag&) : libport::RefCounted() { assert(false); } inline rTag Tag::fresh(libport::Symbol name) { rTag res = new Tag(name); return res; } inline rTag Tag::fresh(rTag parent, libport::Symbol name) { rTag res = new Tag(parent, name); return res; } inline bool Tag::frozen() const { return frozen_ || (parent_ && parent_->frozen()); } inline bool Tag::blocked() const { return blocked_ || (parent_ && parent_->blocked()); } inline bool Tag::derives_from(const Tag& other) const { return this == &other || (parent_ && parent_->derives_from(other)); } inline void Tag::freeze(Scheduler&) { frozen_ = true; } inline void Tag::unfreeze(Scheduler&) { frozen_ = false; } inline void Tag::block(Scheduler& sched, boost::any payload) { blocked_ = true; stop(sched, payload); } inline void Tag::unblock(Scheduler&) { blocked_ = false; } inline const libport::Symbol& Tag::name_get() const { return name_; } } // namespace scheduler <|endoftext|>
<commit_before>#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <cmath> #include <sstream> #include <string> #include <vector> #include <popt.h> #include "defs.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "GreedyUnigrams.hh" using namespace std; void assert_single_chars(map<string, flt_type> &vocab, const map<string, flt_type> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(it->first) == vocab.end()) vocab[it->first] = val; } int main(int argc, char* argv[]) { float cutoff_value = 0.0; int n_candidates_per_iter = 5000; int max_removals_per_iter = 5000; int min_removals_per_iter = 0; float threshold = -25.0; float threshold_decrease = 25.0; int target_vocab_size = 50000; bool enable_forward_backward = false; flt_type one_char_min_lp = -25.0; string vocab_fname; string wordlist_fname; // Popt documentation: // http://linux.die.net/man/3/popt // http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html poptContext pc; struct poptOption po[] = { {"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"}, {"candidates", 'c', POPT_ARG_INT, &n_candidates_per_iter, 11002, NULL, "Number of candidate subwords to try to remove per iteration"}, {"max_removals", 'a', POPT_ARG_INT, &max_removals_per_iter, 11003, NULL, "Maximum number of removals per iteration"}, {"min_removals", 'i', POPT_ARG_INT, &min_removals_per_iter, 11004, NULL, "Minimum number of removals per iteration (stopping criterion)"}, {"threshold", 't', POPT_ARG_FLOAT, &threshold, 11005, NULL, "Likelihood threshold for removals"}, {"threshold_decrease", 'd', POPT_ARG_FLOAT, &threshold_decrease, 11006, NULL, "Threshold decrease between iterations"}, {"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"}, {"forward_backward", 'f', POPT_ARG_NONE, &enable_forward_backward, 11007, "Use Forward-backward segmentation instead of Viterbi", NULL}, POPT_AUTOHELP {NULL} }; pc = poptGetContext(NULL, argc, (const char **)argv, po, 0); poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST]"); int val; while ((val = poptGetNextOpt(pc)) >= 0) continue; // poptGetNextOpt returns -1 when the final argument has been parsed // otherwise an error occured if (val != -1) { switch (val) { case POPT_ERROR_NOARG: cerr << "Argument missing for an option" << endl; exit(1); case POPT_ERROR_BADOPT: cerr << "Option's argument could not be parsed" << endl; exit(1); case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: cerr << "Option could not be converted to number" << endl; exit(1); default: cerr << "Unknown error in option processing" << endl; exit(1); } } // Handle ARG part of command line if (poptPeekArg(pc) != NULL) vocab_fname.assign((char*)poptGetArg(pc)); else { cerr << "Initial vocabulary file not set" << endl; exit(1); } if (poptPeekArg(pc) != NULL) wordlist_fname.assign((char*)poptGetArg(pc)); else { cerr << "Wordlist file not set" << endl; exit(1); } cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl; cerr << "parameters, removals per iteration: " << max_removals_per_iter << endl; cerr << "parameters, threshold: " << threshold << endl; cerr << "parameters, threshold decrease per iteration: " << threshold_decrease << endl; cerr << "parameters, min removals per iteration: " << min_removals_per_iter << endl; cerr << "parameters, target vocab size: " << target_vocab_size << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; map<string, flt_type> all_chars; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) if (it->first.length() == 1) all_chars[it->first] = 0.0; cerr << "Reading word list " << wordlist_fname << endl; retval = read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; GreedyUnigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); cerr << "Initial cutoff" << endl; gg.resegment_words(words, vocab, freqs); flt_type densum = gg.get_sum(freqs); flt_type cost = gg.get_cost(freqs, densum); cerr << "cost: " << cost << endl; gg.cutoff(freqs, (flt_type)cutoff_value); cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl; vocab = freqs; densum = gg.get_sum(vocab); gg.freqs_to_logprobs(vocab, densum); assert_single_chars(vocab, all_chars, one_char_min_lp); cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; cerr << "collecting candidate subwords for removal" << endl; map<string, map<string, flt_type> > diffs; if ((int)vocab.size()-n_candidates_per_iter < target_vocab_size) n_candidates_per_iter = (int)vocab.size()-target_vocab_size; gg.init_removal_candidates(n_candidates_per_iter, words, vocab, diffs); cerr << "ranking candidate subwords" << endl; vector<pair<string, flt_type> > removal_scores; gg.rank_removal_candidates(words, vocab, diffs, freqs, removal_scores); // Perform removals one by one if likelihood change above threshold flt_type curr_densum = gg.get_sum(freqs); flt_type curr_cost = gg.get_cost(freqs, curr_densum); map<string, map<string, flt_type> > backpointers; gg.get_backpointers(words, vocab, backpointers); cerr << "starting cost before removing subwords one by one: " << curr_cost << endl; unsigned int n_removals = 0; for (unsigned int i=0; i<removal_scores.size(); i++) { if (removal_scores[i].first.length() == 1) continue; // Score most probably went to zero already if (vocab.find(removal_scores[i].first) == vocab.end()) continue; cout << removal_scores[i].first << "\t" << "expected ll diff: " << removal_scores[i].second << endl; map<string, flt_type> freq_diffs; map<string, map<string, flt_type> > backpointers_to_remove; map<string, map<string, flt_type> > backpointers_to_add; StringSet<flt_type> stringset_vocab(vocab); gg.hypo_removal(stringset_vocab, removal_scores[i].first, backpointers, backpointers_to_remove, backpointers_to_add, freq_diffs); flt_type hypo_densum = gg.get_sum(freqs, freq_diffs); flt_type hypo_cost = gg.get_cost(freqs, freq_diffs, hypo_densum); cout << removal_scores[i].first << "\t" << "change in likelihood: " << hypo_cost-curr_cost; if (hypo_cost-curr_cost < threshold) { cout << " was below threshold " << threshold << endl; continue; } cout << " removed, was above threshold " << threshold << endl; gg.apply_freq_diffs(freqs, freq_diffs); freqs.erase(removal_scores[i].first); gg.apply_backpointer_changes(backpointers, backpointers_to_remove, backpointers_to_add); backpointers.erase(removal_scores[i].first); curr_densum = hypo_densum; curr_cost = hypo_cost; vocab = freqs; gg.freqs_to_logprobs(vocab, hypo_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); n_removals++; if (vocab.size() % 5000 == 0) { ostringstream vocabfname; vocabfname << "iter" << itern << "_" << vocab.size() << ".vocab"; write_vocab(vocabfname.str(), vocab); } if (n_removals >= max_removals_per_iter) break; if (vocab.size() <= target_vocab_size) break; } int n_cutoff = gg.cutoff(freqs, cutoff_value); flt_type co_densum = gg.get_sum(freqs); vocab = freqs; gg.freqs_to_logprobs(vocab, co_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); gg.resegment_words(words, vocab, freqs); curr_densum = gg.get_sum(freqs); curr_cost = gg.get_cost(freqs, densum); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << curr_cost << endl; ostringstream vocabfname; vocabfname << "iter" << itern << ".vocab"; write_vocab(vocabfname.str(), vocab); itern++; threshold -= threshold_decrease; if (n_removals < min_removals_per_iter) { cerr << "stopping by min_removals_per_iter." << endl; break; } if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } exit(1); } <commit_msg>Removed unused includes.<commit_after>#include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include <popt.h> #include "defs.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "GreedyUnigrams.hh" using namespace std; void assert_single_chars(map<string, flt_type> &vocab, const map<string, flt_type> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(it->first) == vocab.end()) vocab[it->first] = val; } int main(int argc, char* argv[]) { float cutoff_value = 0.0; int n_candidates_per_iter = 5000; int max_removals_per_iter = 5000; int min_removals_per_iter = 0; float threshold = -25.0; float threshold_decrease = 25.0; int target_vocab_size = 50000; bool enable_forward_backward = false; flt_type one_char_min_lp = -25.0; string vocab_fname; string wordlist_fname; // Popt documentation: // http://linux.die.net/man/3/popt // http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html poptContext pc; struct poptOption po[] = { {"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"}, {"candidates", 'c', POPT_ARG_INT, &n_candidates_per_iter, 11002, NULL, "Number of candidate subwords to try to remove per iteration"}, {"max_removals", 'a', POPT_ARG_INT, &max_removals_per_iter, 11003, NULL, "Maximum number of removals per iteration"}, {"min_removals", 'i', POPT_ARG_INT, &min_removals_per_iter, 11004, NULL, "Minimum number of removals per iteration (stopping criterion)"}, {"threshold", 't', POPT_ARG_FLOAT, &threshold, 11005, NULL, "Likelihood threshold for removals"}, {"threshold_decrease", 'd', POPT_ARG_FLOAT, &threshold_decrease, 11006, NULL, "Threshold decrease between iterations"}, {"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"}, {"forward_backward", 'f', POPT_ARG_NONE, &enable_forward_backward, 11007, "Use Forward-backward segmentation instead of Viterbi", NULL}, POPT_AUTOHELP {NULL} }; pc = poptGetContext(NULL, argc, (const char **)argv, po, 0); poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST]"); int val; while ((val = poptGetNextOpt(pc)) >= 0) continue; // poptGetNextOpt returns -1 when the final argument has been parsed // otherwise an error occured if (val != -1) { switch (val) { case POPT_ERROR_NOARG: cerr << "Argument missing for an option" << endl; exit(1); case POPT_ERROR_BADOPT: cerr << "Option's argument could not be parsed" << endl; exit(1); case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: cerr << "Option could not be converted to number" << endl; exit(1); default: cerr << "Unknown error in option processing" << endl; exit(1); } } // Handle ARG part of command line if (poptPeekArg(pc) != NULL) vocab_fname.assign((char*)poptGetArg(pc)); else { cerr << "Initial vocabulary file not set" << endl; exit(1); } if (poptPeekArg(pc) != NULL) wordlist_fname.assign((char*)poptGetArg(pc)); else { cerr << "Wordlist file not set" << endl; exit(1); } cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl; cerr << "parameters, removals per iteration: " << max_removals_per_iter << endl; cerr << "parameters, threshold: " << threshold << endl; cerr << "parameters, threshold decrease per iteration: " << threshold_decrease << endl; cerr << "parameters, min removals per iteration: " << min_removals_per_iter << endl; cerr << "parameters, target vocab size: " << target_vocab_size << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; map<string, flt_type> all_chars; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) if (it->first.length() == 1) all_chars[it->first] = 0.0; cerr << "Reading word list " << wordlist_fname << endl; retval = read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; GreedyUnigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); cerr << "Initial cutoff" << endl; gg.resegment_words(words, vocab, freqs); flt_type densum = gg.get_sum(freqs); flt_type cost = gg.get_cost(freqs, densum); cerr << "cost: " << cost << endl; gg.cutoff(freqs, (flt_type)cutoff_value); cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl; vocab = freqs; densum = gg.get_sum(vocab); gg.freqs_to_logprobs(vocab, densum); assert_single_chars(vocab, all_chars, one_char_min_lp); cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; cerr << "collecting candidate subwords for removal" << endl; map<string, map<string, flt_type> > diffs; if ((int)vocab.size()-n_candidates_per_iter < target_vocab_size) n_candidates_per_iter = (int)vocab.size()-target_vocab_size; gg.init_removal_candidates(n_candidates_per_iter, words, vocab, diffs); cerr << "ranking candidate subwords" << endl; vector<pair<string, flt_type> > removal_scores; gg.rank_removal_candidates(words, vocab, diffs, freqs, removal_scores); // Perform removals one by one if likelihood change above threshold flt_type curr_densum = gg.get_sum(freqs); flt_type curr_cost = gg.get_cost(freqs, curr_densum); map<string, map<string, flt_type> > backpointers; gg.get_backpointers(words, vocab, backpointers); cerr << "starting cost before removing subwords one by one: " << curr_cost << endl; unsigned int n_removals = 0; for (unsigned int i=0; i<removal_scores.size(); i++) { if (removal_scores[i].first.length() == 1) continue; // Score most probably went to zero already if (vocab.find(removal_scores[i].first) == vocab.end()) continue; cout << removal_scores[i].first << "\t" << "expected ll diff: " << removal_scores[i].second << endl; map<string, flt_type> freq_diffs; map<string, map<string, flt_type> > backpointers_to_remove; map<string, map<string, flt_type> > backpointers_to_add; StringSet<flt_type> stringset_vocab(vocab); gg.hypo_removal(stringset_vocab, removal_scores[i].first, backpointers, backpointers_to_remove, backpointers_to_add, freq_diffs); flt_type hypo_densum = gg.get_sum(freqs, freq_diffs); flt_type hypo_cost = gg.get_cost(freqs, freq_diffs, hypo_densum); cout << removal_scores[i].first << "\t" << "change in likelihood: " << hypo_cost-curr_cost; if (hypo_cost-curr_cost < threshold) { cout << " was below threshold " << threshold << endl; continue; } cout << " removed, was above threshold " << threshold << endl; gg.apply_freq_diffs(freqs, freq_diffs); freqs.erase(removal_scores[i].first); gg.apply_backpointer_changes(backpointers, backpointers_to_remove, backpointers_to_add); backpointers.erase(removal_scores[i].first); curr_densum = hypo_densum; curr_cost = hypo_cost; vocab = freqs; gg.freqs_to_logprobs(vocab, hypo_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); n_removals++; if (vocab.size() % 5000 == 0) { ostringstream vocabfname; vocabfname << "iter" << itern << "_" << vocab.size() << ".vocab"; write_vocab(vocabfname.str(), vocab); } if (n_removals >= max_removals_per_iter) break; if (vocab.size() <= target_vocab_size) break; } int n_cutoff = gg.cutoff(freqs, cutoff_value); flt_type co_densum = gg.get_sum(freqs); vocab = freqs; gg.freqs_to_logprobs(vocab, co_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); gg.resegment_words(words, vocab, freqs); curr_densum = gg.get_sum(freqs); curr_cost = gg.get_cost(freqs, densum); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << curr_cost << endl; ostringstream vocabfname; vocabfname << "iter" << itern << ".vocab"; write_vocab(vocabfname.str(), vocab); itern++; threshold -= threshold_decrease; if (n_removals < min_removals_per_iter) { cerr << "stopping by min_removals_per_iter." << endl; break; } if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } exit(1); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <memory> #include "tuple/tuple.h" #include "endianess/little.h" #include "endianess/big.h" #include "container.h" class BufferTest : public ::testing::Test { protected: virtual void SetUp() { this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(10 * sizeof(uint32_t), sizeof(uint8_t)) ), 10 * sizeof(uint32_t) ) ); } std::unique_ptr<BinaryMapping::Buffer> buffer_; }; TEST_F(BufferTest, Basic) { EXPECT_EQ(this->buffer_->size<sizeof(uint32_t)>(), 10); EXPECT_EQ(this->buffer_->at<sizeof(uint32_t)>(0), this->buffer_->front()); EXPECT_EQ(this->buffer_->at<sizeof(uint32_t)>(1), this->buffer_->front() + sizeof(uint32_t)); EXPECT_EQ((*this->buffer_)[4], this->buffer_->front() + sizeof(uint32_t)); } TEST_F(BufferTest, Iterator) { auto iter1 = this->buffer_->begin<sizeof(uint32_t)>(); auto iter2 = this->buffer_->end<sizeof(uint32_t)>(); EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2 > iter1, true); EXPECT_EQ(iter2 < iter1, false); ++iter1; EXPECT_EQ(iter2 - iter1, 9); iter1 += 3; EXPECT_EQ(iter2 - iter1, 6); --iter1; EXPECT_EQ(iter2 - iter1, 7); iter1 -= 3; EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2-- - iter1, 10); EXPECT_EQ(iter2++ - iter1, 9); EXPECT_EQ(iter2-- - iter1, 10); auto iter3 = iter2 - 5; auto iter4 = iter3 + 2; auto iter5 = 2 + iter3; EXPECT_EQ(iter2 - iter3, 5); EXPECT_EQ(iter2 - iter4, 3); EXPECT_EQ(iter2 - iter5, 3); } class TupleTest : public ::testing::Test { }; TEST_F(TupleTest, Basic) { typedef BinaryMapping::PlainTuple< uint64_t, uint8_t, uint32_t, uint16_t, int64_t, int32_t, int16_t, int8_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size, sizeof(uint8_t)) ), TestMapping::size ); TestMapping mapping(&testBuffer); mapping.set<0>(UINT64_MAX); mapping.set<1>(UINT8_MAX); mapping.set<2>(UINT32_MAX); mapping.set<3>(UINT16_MAX); mapping.set<4>(INT64_MIN); mapping.set<5>(INT32_MIN); mapping.set<6>(INT16_MIN); mapping.set<7>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT64_MAX); EXPECT_EQ(mapping.get<1>(), UINT8_MAX); EXPECT_EQ(mapping.get<2>(), UINT32_MAX); EXPECT_EQ(mapping.get<3>(), UINT16_MAX); EXPECT_EQ(mapping.get<4>(), INT64_MIN); EXPECT_EQ(mapping.get<5>(), INT32_MIN); EXPECT_EQ(mapping.get<6>(), INT16_MIN); EXPECT_EQ(mapping.get<7>(), INT8_MIN); } TEST_F(TupleTest, Iterator) { typedef BinaryMapping::PlainTuple< uint32_t, uint16_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size * 10, sizeof(uint8_t)) ), TestMapping::size * 10 ); auto iter = testBuffer.begin<TestMapping::size>(); TestMapping mapping(iter); for ( size_t i = 0; i < 10; ++i ) { mapping.set<0>(i); mapping.set<1>(i); ++iter; } iter -= 10; for ( size_t i = 0; i < 10; ++i ) { EXPECT_EQ(mapping.get<0>(), i); EXPECT_EQ(mapping.get<1>(), i); ++iter; } } TEST_F(TupleTest, CarbonCopy) { typedef BinaryMapping::PlainTuple< uint32_t, uint16_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size, sizeof(uint8_t)) ), TestMapping::size ); TestMapping mapping(&testBuffer); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); TestMapping::carbon_copy copy = mapping.carbonCopy(); mapping.set<0>(1); mapping.set<1>(2); EXPECT_EQ(copy.get<0>(), UINT32_MAX); EXPECT_EQ(copy.get<1>(), UINT16_MAX); } class EndianTest : public ::testing::Test { protected: virtual void SetUp() { const size_t tupleSize = sizeof(uint64_t) + sizeof(uint32_t) + sizeof(int16_t); this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(tupleSize, sizeof(uint8_t)) ), tupleSize ) ); } std::unique_ptr<BinaryMapping::Buffer> buffer_; }; TEST_F(EndianTest, LittleEndian) { typedef BinaryMapping::Tuple< BinaryMapping::LittleEndian, uint64_t, uint32_t, int16_t > TestMapping; TestMapping mapping(this->buffer_.get()); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); mapping.set<2>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT32_MAX); EXPECT_EQ(mapping.get<1>(), UINT16_MAX); EXPECT_EQ(mapping.get<2>(), INT8_MIN); } TEST_F(EndianTest, BigEndian) { typedef BinaryMapping::Tuple< BinaryMapping::BigEndian, uint64_t, uint32_t, int16_t > TestMapping; TestMapping mapping(this->buffer_.get()); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); mapping.set<2>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT32_MAX); EXPECT_EQ(mapping.get<1>(), UINT16_MAX); EXPECT_EQ(mapping.get<2>(), INT8_MIN); } TEST_F(EndianTest, MixedEndian) { typedef BinaryMapping::Tuple< BinaryMapping::BigEndian, uint64_t, uint32_t, int16_t > BigTestMapping; typedef BinaryMapping::Tuple< BinaryMapping::LittleEndian, uint64_t, uint32_t, int16_t > LittleTestMapping; BigTestMapping bigMapping(this->buffer_.get()); bigMapping.set<0>(UINT32_MAX); bigMapping.set<1>(UINT16_MAX); bigMapping.set<2>(INT8_MIN); LittleTestMapping littleMapping(this->buffer_.get()); EXPECT_EQ(littleMapping.get<0>(), 18446744069414584320ul); EXPECT_EQ(littleMapping.get<1>(), 4294901760); EXPECT_EQ(littleMapping.get<2>(), -32513); } class ContainerTest : public ::testing::Test { protected: typedef BinaryMapping::PlainContainer< uint64_t, uint16_t > TestContainer; virtual void SetUp() { this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(10 * TestContainer::tuple_type::size, sizeof(uint8_t)) ), 10 * TestContainer::tuple_type::size ) ); this->container_ = std::unique_ptr<TestContainer>( new TestContainer(this->buffer_.get()) ); for ( size_t i = 0; i != 10; ++i ) { TestContainer::tuple_type tuple(this->container_->at(i)); tuple.set<0>(i); tuple.set<1>(i); } } std::unique_ptr<BinaryMapping::Buffer> buffer_; std::unique_ptr<TestContainer> container_; }; TEST_F(ContainerTest, Basic) { const TestContainer& constContainer = *this->container_.get(); EXPECT_EQ(this->container_->front().get<0>(), 0); EXPECT_EQ(this->container_->back().get<1>(), 9); EXPECT_EQ(this->container_->size(), 10); for ( size_t i = 0; i != 10; ++i ) { EXPECT_EQ(this->container_->at(i).get<0>(), i); EXPECT_EQ((*this->container_)[i].get<1>(), i); EXPECT_EQ(constContainer.at(i).get<0>(), i); EXPECT_EQ(constContainer[i].get<1>(), i); } } TEST_F(ContainerTest, Iterator) { TestContainer::iterator_type iter(this->container_->begin()); for ( size_t i = 0; i < 10; ++i ) { EXPECT_EQ((*iter).get<0>(), i); EXPECT_EQ((*iter).get<1>(), i); ++iter; } auto iter1 = this->container_->begin(); auto iter2 = this->container_->end(); EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2 > iter1, true); EXPECT_EQ(iter2 < iter1, false); ++iter1; EXPECT_EQ(iter2 - iter1, 9); iter1 += 3; EXPECT_EQ(iter2 - iter1, 6); --iter1; EXPECT_EQ(iter2 - iter1, 7); iter1 -= 3; EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2-- - iter1, 10); EXPECT_EQ(iter2++ - iter1, 9); EXPECT_EQ(iter2-- - iter1, 10); auto iter3 = iter2 - 5; auto iter4 = iter3 + 2; auto iter5 = 2 + iter3; EXPECT_EQ(iter2 - iter3, 5); EXPECT_EQ(iter2 - iter4, 3); EXPECT_EQ(iter2 - iter5, 3); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Added test case for serialize and deserialize template methods * They are only enabled when Endianess argument of template equals UndefinedEndian<commit_after>#include "gtest/gtest.h" #include <memory> #include "tuple/tuple.h" #include "endianess/little.h" #include "endianess/big.h" #include "container.h" class BufferTest : public ::testing::Test { protected: virtual void SetUp() { this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(10 * sizeof(uint32_t), sizeof(uint8_t)) ), 10 * sizeof(uint32_t) ) ); } std::unique_ptr<BinaryMapping::Buffer> buffer_; }; TEST_F(BufferTest, Basic) { EXPECT_EQ(this->buffer_->size<sizeof(uint32_t)>(), 10); EXPECT_EQ(this->buffer_->at<sizeof(uint32_t)>(0), this->buffer_->front()); EXPECT_EQ(this->buffer_->at<sizeof(uint32_t)>(1), this->buffer_->front() + sizeof(uint32_t)); EXPECT_EQ((*this->buffer_)[4], this->buffer_->front() + sizeof(uint32_t)); } TEST_F(BufferTest, Iterator) { auto iter1 = this->buffer_->begin<sizeof(uint32_t)>(); auto iter2 = this->buffer_->end<sizeof(uint32_t)>(); EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2 > iter1, true); EXPECT_EQ(iter2 < iter1, false); ++iter1; EXPECT_EQ(iter2 - iter1, 9); iter1 += 3; EXPECT_EQ(iter2 - iter1, 6); --iter1; EXPECT_EQ(iter2 - iter1, 7); iter1 -= 3; EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2-- - iter1, 10); EXPECT_EQ(iter2++ - iter1, 9); EXPECT_EQ(iter2-- - iter1, 10); auto iter3 = iter2 - 5; auto iter4 = iter3 + 2; auto iter5 = 2 + iter3; EXPECT_EQ(iter2 - iter3, 5); EXPECT_EQ(iter2 - iter4, 3); EXPECT_EQ(iter2 - iter5, 3); } class TupleTest : public ::testing::Test { }; TEST_F(TupleTest, Basic) { typedef BinaryMapping::PlainTuple< uint64_t, uint8_t, uint32_t, uint16_t, int64_t, int32_t, int16_t, int8_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size, sizeof(uint8_t)) ), TestMapping::size ); TestMapping mapping(&testBuffer); mapping.set<0>(UINT64_MAX); mapping.set<1>(UINT8_MAX); mapping.set<2>(UINT32_MAX); mapping.set<3>(UINT16_MAX); mapping.set<4>(INT64_MIN); mapping.set<5>(INT32_MIN); mapping.set<6>(INT16_MIN); mapping.set<7>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT64_MAX); EXPECT_EQ(mapping.get<1>(), UINT8_MAX); EXPECT_EQ(mapping.get<2>(), UINT32_MAX); EXPECT_EQ(mapping.get<3>(), UINT16_MAX); EXPECT_EQ(mapping.get<4>(), INT64_MIN); EXPECT_EQ(mapping.get<5>(), INT32_MIN); EXPECT_EQ(mapping.get<6>(), INT16_MIN); EXPECT_EQ(mapping.get<7>(), INT8_MIN); } TEST_F(TupleTest, Iterator) { typedef BinaryMapping::PlainTuple< uint32_t, uint16_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size * 10, sizeof(uint8_t)) ), TestMapping::size * 10 ); auto iter = testBuffer.begin<TestMapping::size>(); TestMapping mapping(iter); for ( size_t i = 0; i < 10; ++i ) { mapping.set<0>(i); mapping.set<1>(i); ++iter; } iter -= 10; for ( size_t i = 0; i < 10; ++i ) { EXPECT_EQ(mapping.get<0>(), i); EXPECT_EQ(mapping.get<1>(), i); ++iter; } } TEST_F(TupleTest, CarbonCopy) { typedef BinaryMapping::PlainTuple< uint32_t, uint16_t > TestMapping; BinaryMapping::Buffer testBuffer( reinterpret_cast<uint8_t*>( std::calloc(TestMapping::size, sizeof(uint8_t)) ), TestMapping::size ); TestMapping mapping(&testBuffer); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); TestMapping::carbon_copy copy = mapping.carbonCopy(); mapping.set<0>(1); mapping.set<1>(2); EXPECT_EQ(copy.get<0>(), UINT32_MAX); EXPECT_EQ(copy.get<1>(), UINT16_MAX); } class EndianTest : public ::testing::Test { protected: virtual void SetUp() { const size_t tupleSize = sizeof(uint64_t) + sizeof(uint32_t) + sizeof(int16_t); this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(tupleSize, sizeof(uint8_t)) ), tupleSize ) ); } std::unique_ptr<BinaryMapping::Buffer> buffer_; }; TEST_F(EndianTest, LittleEndian) { typedef BinaryMapping::Tuple< BinaryMapping::LittleEndian, uint64_t, uint32_t, int16_t > TestMapping; TestMapping mapping(this->buffer_.get()); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); mapping.set<2>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT32_MAX); EXPECT_EQ(mapping.get<1>(), UINT16_MAX); EXPECT_EQ(mapping.get<2>(), INT8_MIN); } TEST_F(EndianTest, BigEndian) { typedef BinaryMapping::Tuple< BinaryMapping::BigEndian, uint64_t, uint32_t, int16_t > TestMapping; TestMapping mapping(this->buffer_.get()); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); mapping.set<2>(INT8_MIN); EXPECT_EQ(mapping.get<0>(), UINT32_MAX); EXPECT_EQ(mapping.get<1>(), UINT16_MAX); EXPECT_EQ(mapping.get<2>(), INT8_MIN); } TEST_F(EndianTest, UndefinedEndian) { typedef BinaryMapping::Tuple< BinaryMapping::UndefinedEndian, uint64_t, uint32_t, int16_t > TestMapping; TestMapping mapping(this->buffer_.get()); mapping.set<0>(UINT32_MAX); mapping.set<1>(UINT16_MAX); mapping.set<2>(INT8_MIN); mapping.serialize<BinaryMapping::BigEndian>(); EXPECT_NE(mapping.get<0>(), UINT32_MAX); EXPECT_NE(mapping.get<1>(), UINT16_MAX); EXPECT_NE(mapping.get<2>(), INT8_MIN); mapping.deserialize<BinaryMapping::BigEndian>(); EXPECT_EQ(mapping.get<0>(), UINT32_MAX); EXPECT_EQ(mapping.get<1>(), UINT16_MAX); EXPECT_EQ(mapping.get<2>(), INT8_MIN); } TEST_F(EndianTest, MixedEndian) { typedef BinaryMapping::Tuple< BinaryMapping::BigEndian, uint64_t, uint32_t, int16_t > BigTestMapping; typedef BinaryMapping::Tuple< BinaryMapping::LittleEndian, uint64_t, uint32_t, int16_t > LittleTestMapping; BigTestMapping bigMapping(this->buffer_.get()); bigMapping.set<0>(UINT32_MAX); bigMapping.set<1>(UINT16_MAX); bigMapping.set<2>(INT8_MIN); LittleTestMapping littleMapping(this->buffer_.get()); EXPECT_EQ(littleMapping.get<0>(), 18446744069414584320ul); EXPECT_EQ(littleMapping.get<1>(), 4294901760); EXPECT_EQ(littleMapping.get<2>(), -32513); } class ContainerTest : public ::testing::Test { protected: typedef BinaryMapping::PlainContainer< uint64_t, uint16_t > TestContainer; virtual void SetUp() { this->buffer_ = std::unique_ptr<BinaryMapping::Buffer>( new BinaryMapping::Buffer( reinterpret_cast<uint8_t*>( std::calloc(10 * TestContainer::tuple_type::size, sizeof(uint8_t)) ), 10 * TestContainer::tuple_type::size ) ); this->container_ = std::unique_ptr<TestContainer>( new TestContainer(this->buffer_.get()) ); for ( size_t i = 0; i != 10; ++i ) { TestContainer::tuple_type tuple(this->container_->at(i)); tuple.set<0>(i); tuple.set<1>(i); } } std::unique_ptr<BinaryMapping::Buffer> buffer_; std::unique_ptr<TestContainer> container_; }; TEST_F(ContainerTest, Basic) { const TestContainer& constContainer = *this->container_.get(); EXPECT_EQ(this->container_->front().get<0>(), 0); EXPECT_EQ(this->container_->back().get<1>(), 9); EXPECT_EQ(this->container_->size(), 10); for ( size_t i = 0; i != 10; ++i ) { EXPECT_EQ(this->container_->at(i).get<0>(), i); EXPECT_EQ((*this->container_)[i].get<1>(), i); EXPECT_EQ(constContainer.at(i).get<0>(), i); EXPECT_EQ(constContainer[i].get<1>(), i); } } TEST_F(ContainerTest, Iterator) { TestContainer::iterator_type iter(this->container_->begin()); for ( size_t i = 0; i < 10; ++i ) { EXPECT_EQ((*iter).get<0>(), i); EXPECT_EQ((*iter).get<1>(), i); ++iter; } auto iter1 = this->container_->begin(); auto iter2 = this->container_->end(); EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2 > iter1, true); EXPECT_EQ(iter2 < iter1, false); ++iter1; EXPECT_EQ(iter2 - iter1, 9); iter1 += 3; EXPECT_EQ(iter2 - iter1, 6); --iter1; EXPECT_EQ(iter2 - iter1, 7); iter1 -= 3; EXPECT_EQ(iter2 - iter1, 10); EXPECT_EQ(iter2-- - iter1, 10); EXPECT_EQ(iter2++ - iter1, 9); EXPECT_EQ(iter2-- - iter1, 10); auto iter3 = iter2 - 5; auto iter4 = iter3 + 2; auto iter5 = 2 + iter3; EXPECT_EQ(iter2 - iter3, 5); EXPECT_EQ(iter2 - iter4, 3); EXPECT_EQ(iter2 - iter5, 3); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <cmath> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include "defs.hh" #include "conf.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "Unigrams.hh" using namespace std; void assert_short_subwords(map<string, flt_type> &vocab, const set<string> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(*it) == vocab.end()) vocab[*it] = val; } int main(int argc, char* argv[]) { conf::Config config; config("usage: g1g [OPTION...] WORDLIST VOCAB_INIT VOCAB_OUTNAME\n") ('h', "help", "", "", "display help") ('u', "cutoff=INT", "arg", "0", "Cutoff value for each iteration") ('c', "candidates=INT", "arg", "25000", "Number of subwords to consider for removal per iteration") ('r', "removals=INT", "arg", "500", "Number of removals per iteration") ('m', "min-length=INT", "arg", "2", "Minimum length of subwords to remove") ('v', "vocab-size=INT", "arg must", "", "Target vocabulary size (stopping criterion)") ('t', "temp-vocabs=INT", "arg", "0", "Write out intermediate vocabularies for #V mod INT == 0") ('f', "forward-backward", "", "", "Use Forward-backward segmentation instead of Viterbi"); config.default_parse(argc, argv); if (config.arguments.size() != 3) config.print_help(stderr, 1); flt_type short_subword_min_lp = -25.0; string wordlist_fname = config.arguments[0]; string vocab_fname = config.arguments[1]; string out_vocab_fname = config.arguments[2]; float cutoff_value = config["cutoff"].get_float(); int n_candidates_per_iter = config["candidates"].get_int(); int removals_per_iter = config["removals"].get_int(); int min_removal_length = config["min-length"].get_int(); int target_vocab_size = config["vocab-size"].get_int(); int temp_vocab_interval = config["temp-vocabs"].get_int(); bool enable_forward_backward = config["forward-backward"].specified; cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl; cerr << "parameters, minimum length for subwords to remove: " << min_removal_length << endl; cerr << "parameters, removals per iteration: " << removals_per_iter << endl; cerr << "parameters, target vocab size: " << target_vocab_size << endl; if (temp_vocab_interval > 0) cerr << "parameters, write temp vocabs: " << temp_vocab_interval << endl; else cerr << "parameters, write temp vocabs: NO" << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; set<string> short_subwords; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = Unigrams::read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) { if (it->first.length() < min_removal_length) short_subwords.insert(it->first); } cerr << "Reading word list " << wordlist_fname << endl; retval = Unigrams::read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; Unigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); cerr << "Initial cutoff" << endl; flt_type cost = gg.resegment_words(words, vocab, freqs); cerr << "cost: " << cost << endl; flt_type temp_cutoff = 1.0; while (true) { gg.cutoff(freqs, temp_cutoff, min_removal_length); cerr << "\tcutoff: " << temp_cutoff << "\t" << "vocabulary size: " << freqs.size() << endl; vocab = freqs; Unigrams::freqs_to_logprobs(vocab); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); temp_cutoff += 1.0; if (temp_cutoff > (flt_type)cutoff_value) break; cost = gg.resegment_words(words, vocab, freqs); cerr << "cost: " << cost << endl; } cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; cerr << "collecting candidate subwords for removal" << endl; set<string> candidates; gg.init_candidates_by_usage(words, vocab, candidates, n_candidates_per_iter/3, min_removal_length); gg.init_candidates_by_random(vocab, candidates, (n_candidates_per_iter-candidates.size())/4, min_removal_length); gg.init_candidates(vocab, candidates, n_candidates_per_iter, min_removal_length); cerr << "ranking candidate subwords (" << candidates.size() << ")" << endl; vector<pair<string, flt_type> > removal_scores; cost = gg.rank_candidates(words, vocab, candidates, freqs, removal_scores); cerr << "starting cost before removing subwords one by one: " << cost << endl; // Remove subwords one by one unsigned int n_removals = 0; for (unsigned int i=0; i<removal_scores.size(); i++) { if (removal_scores[i].first.length() == 1) continue; // Score most probably went to zero already if (vocab.find(removal_scores[i].first) == vocab.end()) continue; if (freqs.find(removal_scores[i].first) == freqs.end()) continue; vocab.erase(removal_scores[i].first); freqs.erase(removal_scores[i].first); n_removals++; if (temp_vocab_interval > 0 && freqs.size() % temp_vocab_interval == 0) { vocab = freqs; Unigrams::freqs_to_logprobs(vocab); ostringstream vocabfname; vocabfname << "iteration_" << itern << "_" << vocab.size() << ".vocab"; Unigrams::write_vocab(vocabfname.str(), vocab); } if (n_removals >= removals_per_iter) break; if (vocab.size() <= target_vocab_size) break; } int n_cutoff = Unigrams::cutoff(freqs, cutoff_value, min_removal_length); vocab = freqs; Unigrams::freqs_to_logprobs(vocab); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); cost = gg.iterate(words, vocab, 2); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << cost << endl; itern++; if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } Unigrams::write_vocab(out_vocab_fname, vocab); exit(1); } <commit_msg>Option for setting the number of removed subwords depending on vocabulary size.<commit_after>#include <cmath> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include "defs.hh" #include "conf.hh" #include "str.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "Unigrams.hh" using namespace std; void assert_short_subwords(map<string, flt_type> &vocab, const set<string> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(*it) == vocab.end()) vocab[*it] = val; } void parse_limits(string limitstr, map<int,int> &limits) { vector<string> fields; str::split_with_quotes(&limitstr, " ,", true, &fields); if (fields.size() % 2 != 0) throw string("Problem parsing the removal limits"); for (int i=0; i<fields.size(); i=i+2) limits[stoi(fields[i])] = stoi(fields[i+1]); } int main(int argc, char* argv[]) { conf::Config config; config("usage: g1g [OPTION...] WORDLIST VOCAB_INIT VOCAB_OUTNAME\n") ('h', "help", "", "", "display help") ('u', "cutoff=INT", "arg", "0", "Cutoff value for each iteration") ('c', "candidates=INT", "arg", "25000", "Number of subwords to consider for removal per iteration") ('r', "removals=INT", "arg", "500", "Number of removals per iteration") ('l', "removal-limits=STRING", "arg", "", "Limits for subword removal LIMIT1,REMOVALS1,LIMIT2,REMOVALS2,..") ('m', "min-length=INT", "arg", "2", "Minimum length of subwords to remove") ('v', "vocab-size=INT", "arg must", "", "Target vocabulary size (stopping criterion)") ('t', "temp-vocabs=INT", "arg", "0", "Write out intermediate vocabularies for #V mod INT == 0") ('f', "forward-backward", "", "", "Use Forward-backward segmentation instead of Viterbi"); config.default_parse(argc, argv); if (config.arguments.size() != 3) config.print_help(stderr, 1); flt_type short_subword_min_lp = -25.0; string wordlist_fname = config.arguments[0]; string vocab_fname = config.arguments[1]; string out_vocab_fname = config.arguments[2]; float cutoff_value = config["cutoff"].get_float(); int n_candidates_per_iter = config["candidates"].get_int(); int removals_per_iter = config["removals"].get_int(); int min_removal_length = config["min-length"].get_int(); int target_vocab_size = config["vocab-size"].get_int(); int temp_vocab_interval = config["temp-vocabs"].get_int(); bool enable_forward_backward = config["forward-backward"].specified; map<int,int> removal_limits; if (config["removal-limits"].specified) parse_limits(config["removal-limits"].get_str(), removal_limits); cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, candidates per iteration: " << n_candidates_per_iter << endl; cerr << "parameters, minimum length for subwords to remove: " << min_removal_length << endl; cerr << "parameters, removals per iteration: " << removals_per_iter << endl; if (removal_limits.size() > 0) { int limitc = 1; for (auto it = removal_limits.begin(); it != removal_limits.end(); ++it) { cerr << "parameters, removal limit " << limitc << ": " << it->second << " removals per iteration below vocabulary size " << it->first << endl; limitc++; } } cerr << "parameters, target vocab size: " << target_vocab_size << endl; if (temp_vocab_interval > 0) cerr << "parameters, write temp vocabs: " << temp_vocab_interval << endl; else cerr << "parameters, write temp vocabs: NO" << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; set<string> short_subwords; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = Unigrams::read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) { if (it->first.length() < min_removal_length) short_subwords.insert(it->first); } cerr << "Reading word list " << wordlist_fname << endl; retval = Unigrams::read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; Unigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); cerr << "Initial cutoff" << endl; flt_type cost = gg.resegment_words(words, vocab, freqs); cerr << "cost: " << cost << endl; flt_type temp_cutoff = 1.0; while (true) { gg.cutoff(freqs, temp_cutoff, min_removal_length); cerr << "\tcutoff: " << temp_cutoff << "\t" << "vocabulary size: " << freqs.size() << endl; vocab = freqs; Unigrams::freqs_to_logprobs(vocab); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); temp_cutoff += 1.0; if (temp_cutoff > (flt_type)cutoff_value) break; cost = gg.resegment_words(words, vocab, freqs); cerr << "cost: " << cost << endl; } cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; for (auto it = removal_limits.rbegin(); it != removal_limits.rend(); it++) if (vocab.size() <= it->first) removals_per_iter = it->second; cerr << "collecting candidate subwords for removal" << endl; set<string> candidates; gg.init_candidates_by_usage(words, vocab, candidates, n_candidates_per_iter/3, min_removal_length); gg.init_candidates_by_random(vocab, candidates, (n_candidates_per_iter-candidates.size())/4, min_removal_length); gg.init_candidates(vocab, candidates, n_candidates_per_iter, min_removal_length); cerr << "ranking candidate subwords (" << candidates.size() << ")" << endl; vector<pair<string, flt_type> > removal_scores; cost = gg.rank_candidates(words, vocab, candidates, freqs, removal_scores); cerr << "starting cost before removing subwords one by one: " << cost << endl; // Remove subwords one by one unsigned int n_removals = 0; for (unsigned int i=0; i<removal_scores.size(); i++) { if (removal_scores[i].first.length() == 1) continue; // Score most probably went to zero already if (vocab.find(removal_scores[i].first) == vocab.end()) continue; if (freqs.find(removal_scores[i].first) == freqs.end()) continue; vocab.erase(removal_scores[i].first); freqs.erase(removal_scores[i].first); n_removals++; if (temp_vocab_interval > 0 && freqs.size() % temp_vocab_interval == 0) { vocab = freqs; Unigrams::freqs_to_logprobs(vocab); ostringstream vocabfname; vocabfname << "iteration_" << itern << "_" << vocab.size() << ".vocab"; Unigrams::write_vocab(vocabfname.str(), vocab); } if (n_removals >= removals_per_iter) break; if (vocab.size() <= target_vocab_size) break; } int n_cutoff = Unigrams::cutoff(freqs, cutoff_value, min_removal_length); vocab = freqs; Unigrams::freqs_to_logprobs(vocab); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); cost = gg.iterate(words, vocab, 2); assert_short_subwords(vocab, short_subwords, short_subword_min_lp); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << cost << endl; itern++; if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } Unigrams::write_vocab(out_vocab_fname, vocab); exit(1); } <|endoftext|>
<commit_before>/* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !COMPONENT_FPGA_CI_TEST_SHIELD #error [NOT_SUPPORTED] FPGA CI Test Shield is needed to run this test #elif !defined(TARGET_FF_ARDUINO) && !defined(MBED_CONF_TARGET_DEFAULT_FORM_FACTOR) #error [NOT_SUPPORTED] Test not supported for this form factor #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" using namespace utest::v1; #include "MbedTester.h" #include "pinmap.h" #include "test_utils.h" // This delay is used when reading a floating input that has an internal pull-up // or pull-down resistor. The voltage response is much slower when the input // is not driven externally. #define HI_Z_READ_DELAY_US 5 MbedTester tester(DefaultFormFactor::pins(), DefaultFormFactor::restricted_pins()); /* Test basic input & output operations. * * Given a GPIO instance initialized with a generic gpio_init() function, * when basic input and output operations are performed, * then all operations succeed. */ void test_basic_input_output(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); // Initialize GPIO pin with a generic init fun. gpio_t gpio; // Test gpio_is_connected() returned value. gpio_init(&gpio, NC); TEST_ASSERT_EQUAL_INT(0, gpio_is_connected(&gpio)); gpio_init(&gpio, pin); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); // Test GPIO used as an input. gpio_dir(&gpio, PIN_INPUT); // Test input, pull-up mode. gpio_mode(&gpio, PullUp); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Test input, pull-down mode. gpio_mode(&gpio, PullDown); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down // Test input, pull-none mode. gpio_mode(&gpio, PullNone); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // Test GPIO used as an output. tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); gpio_dir(&gpio, PIN_OUTPUT); gpio_write(&gpio, 0); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); gpio_write(&gpio, 1); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); gpio_write(&gpio, 0); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); } /* Test explicit input initialization. * * Given a GPIO instance, * when additional parameters are passed to the input init function, * then the GPIO is correctly initialized as an input. */ void test_explicit_input(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); gpio_t gpio; // Initialize GPIO pin as an input, pull-up mode. memset(&gpio, 0, sizeof gpio); gpio_init_in_ex(&gpio, pin, PullUp); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Initialize GPIO pin as an input, pull-down mode. memset(&gpio, 0, sizeof gpio); gpio_init_in_ex(&gpio, pin, PullDown); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down // Initialize GPIO pin as an input, pull-up mode. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_INPUT, PullUp, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Initialize GPIO pin as an input, pull-down mode. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_INPUT, PullDown, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down } /* Test explicit output initialization. * * Given a GPIO instance, * when additional parameters are passed to the output init function, * then the GPIO is correctly initialized as an output. */ void test_explicit_output(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); gpio_t gpio; // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_out(&gpio, pin); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 1. memset(&gpio, 0, sizeof gpio); gpio_init_out_ex(&gpio, pin, 1); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_out_ex(&gpio, pin, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 1. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_OUTPUT, PullNone, 1); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_OUTPUT, PullNone, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); } Case cases[] = { Case("generic init, input & output", all_ports<GPIOPort, DefaultFormFactor, test_basic_input_output>), Case("explicit init, input", all_ports<GPIOPort, DefaultFormFactor, test_explicit_input>), Case("explicit init, output", all_ports<GPIOPort, DefaultFormFactor, test_explicit_output>), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } #endif /* !COMPONENT_FPGA_CI_TEST_SHIELD */ <commit_msg>FPGA: Skip some Nuvoton targets not supporting input pull-up/pull-down mode<commit_after>/* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if !COMPONENT_FPGA_CI_TEST_SHIELD #error [NOT_SUPPORTED] FPGA CI Test Shield is needed to run this test #elif !defined(TARGET_FF_ARDUINO) && !defined(MBED_CONF_TARGET_DEFAULT_FORM_FACTOR) #error [NOT_SUPPORTED] Test not supported for this form factor #else #include "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" using namespace utest::v1; #include "MbedTester.h" #include "pinmap.h" #include "test_utils.h" // This delay is used when reading a floating input that has an internal pull-up // or pull-down resistor. The voltage response is much slower when the input // is not driven externally. #define HI_Z_READ_DELAY_US 5 MbedTester tester(DefaultFormFactor::pins(), DefaultFormFactor::restricted_pins()); /* Test basic input & output operations. * * Given a GPIO instance initialized with a generic gpio_init() function, * when basic input and output operations are performed, * then all operations succeed. */ void test_basic_input_output(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); // Initialize GPIO pin with a generic init fun. gpio_t gpio; // Test gpio_is_connected() returned value. gpio_init(&gpio, NC); TEST_ASSERT_EQUAL_INT(0, gpio_is_connected(&gpio)); gpio_init(&gpio, pin); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); // Some targets don't support input pull mode. #if !defined(TARGET_NANO100) && \ !defined(TARGET_NUC472) && \ !defined(TARGET_M451) // Test GPIO used as an input. gpio_dir(&gpio, PIN_INPUT); // Test input, pull-up mode. gpio_mode(&gpio, PullUp); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Test input, pull-down mode. gpio_mode(&gpio, PullDown); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down // Test input, pull-none mode. gpio_mode(&gpio, PullNone); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, true); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 1, true); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); #endif // Test GPIO used as an output. tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); gpio_dir(&gpio, PIN_OUTPUT); gpio_write(&gpio, 0); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); gpio_write(&gpio, 1); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); gpio_write(&gpio, 0); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); } /* Test explicit input initialization. * * Given a GPIO instance, * when additional parameters are passed to the input init function, * then the GPIO is correctly initialized as an input. */ void test_explicit_input(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); gpio_t gpio; // Initialize GPIO pin as an input, pull-up mode. memset(&gpio, 0, sizeof gpio); gpio_init_in_ex(&gpio, pin, PullUp); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Initialize GPIO pin as an input, pull-down mode. memset(&gpio, 0, sizeof gpio); gpio_init_in_ex(&gpio, pin, PullDown); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down // Initialize GPIO pin as an input, pull-up mode. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_INPUT, PullUp, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(1, gpio_read(&gpio)); // hi-Z, pulled up // Initialize GPIO pin as an input, pull-down mode. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_INPUT, PullDown, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); tester.gpio_write(MbedTester::LogicalPinGPIO0, 0, false); wait_us(HI_Z_READ_DELAY_US); TEST_ASSERT_EQUAL_INT(0, gpio_read(&gpio)); // hi-Z, pulled down } /* Test explicit output initialization. * * Given a GPIO instance, * when additional parameters are passed to the output init function, * then the GPIO is correctly initialized as an output. */ void test_explicit_output(PinName pin) { // Reset everything and set all tester pins to hi-Z. tester.reset(); // Map pins for test. tester.pin_map_set(pin, MbedTester::LogicalPinGPIO0); // Select GPIO0. tester.select_peripheral(MbedTester::PeripheralGPIO); gpio_t gpio; // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_out(&gpio, pin); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 1. memset(&gpio, 0, sizeof gpio); gpio_init_out_ex(&gpio, pin, 1); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_out_ex(&gpio, pin, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 1. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_OUTPUT, PullNone, 1); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(1, tester.gpio_read(MbedTester::LogicalPinGPIO0)); // Initialize GPIO pin as an output, output value = 0. memset(&gpio, 0, sizeof gpio); gpio_init_inout(&gpio, pin, PIN_OUTPUT, PullNone, 0); TEST_ASSERT_NOT_EQUAL(0, gpio_is_connected(&gpio)); TEST_ASSERT_EQUAL_INT(0, tester.gpio_read(MbedTester::LogicalPinGPIO0)); } Case cases[] = { Case("generic init, input & output", all_ports<GPIOPort, DefaultFormFactor, test_basic_input_output>), // Some targets don't support input pull mode. #if !defined(TARGET_NANO100) && \ !defined(TARGET_NUC472) && \ !defined(TARGET_M451) Case("explicit init, input", all_ports<GPIOPort, DefaultFormFactor, test_explicit_input>), #endif Case("explicit init, output", all_ports<GPIOPort, DefaultFormFactor, test_explicit_output>), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(60, "default_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); int main() { Harness::run(specification); } #endif /* !COMPONENT_FPGA_CI_TEST_SHIELD */ <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkCurvatureFlowTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkCurvatureFlowImageFilter.h" #include "itkRandomImageSource.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkVTKImageIO.h" #include "itkTextOutput.h" #include "itkCommand.h" #include "itkCastImageFilter.h" #include "itkStreamingImageFilter.h" #include "itkImageRegionIterator.h" #include "itkFiniteDifferenceFunction.h" namespace { // The following three classes are used to support callbacks // on the filter in the pipeline that follows later class ShowProgressObject { public: ShowProgressObject(itk::ProcessObject* o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::ProcessObject::Pointer m_Process; }; } namespace itk { // Dummy difference function for error testing template <class TImageType> class DummyFunction : public FiniteDifferenceFunction<TImageType> { public: typedef DummyFunction Self; typedef FiniteDifferenceFunction<TImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; itkNewMacro(Self); typedef typename Superclass::NeighborhoodType NeighborhoodType; typedef typename Superclass::FloatOffsetType FloatOffsetType; typedef typename Superclass::PixelType PixelType; typedef typename Superclass::TimeStepType TimeStepType; virtual PixelType ComputeUpdate( const NeighborhoodType &, void *, const FloatOffsetType & ) { return 0; } virtual TimeStepType ComputeGlobalTimeStep( void * ) const { return 0; } virtual void *GetGlobalDataPointer() const { return NULL; } virtual void ReleaseGlobalDataPointer(void *) const {} protected: DummyFunction() {} ~DummyFunction() {} private: DummyFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } int itkCurvatureFlowTest(int argc, char* argv[] ) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " outputFile" << std::endl; return EXIT_FAILURE; } itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); typedef float PixelType; enum { ImageDimension = 2 }; typedef itk::Image<PixelType, ImageDimension> ImageType; //------------------------------------------------------------------------ std::cout << "Test error handling." << std::endl; typedef itk::CurvatureFlowImageFilter<ImageType,ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( NULL ); bool passed = false; try { std::cout << "Test when input is NULL." << std::endl; filter->Update(); } catch( itk::ExceptionObject& err ) { std::cout << "Caught expected error." << std::endl; std::cout << err << std::endl; passed = true; } if ( !passed ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } // --------------------------------------------------------------------------- try { std::cout << "Test when wrong function type." << std::endl; typedef itk::DummyFunction<ImageType> FunctionType; filter = FilterType::New(); FunctionType::Pointer function = FunctionType::New(); ImageType::Pointer dummy = ImageType::New(); ImageType::SizeType size; size.Fill( 3 ); ImageType::RegionType region(size); dummy->SetRegions( region ); dummy->Allocate(); dummy->FillBuffer( 0.2 ); filter->SetInput( dummy ); filter->SetNumberOfIterations( 2 ); filter->SetDifferenceFunction( function ); filter->Update(); } catch( itk::ExceptionObject& err ) { std::cout << "Caught expected error." << std::endl; std::cout << err << std::endl; } //----------------------------------------------------------------------- std::cout << "Create input image using RandomImageSource" << std::endl; typedef itk::RandomImageSource<ImageType> SourceType; SourceType::Pointer source = SourceType::New(); unsigned long size[ImageDimension] = {64,64}; source->SetSize( size ); source->SetMin(0.0); source->SetMax(1.0); source->Update(); std::cout << "Run CurvatureFlowImageFiler with progress cout's" << std::endl; typedef itk::CurvatureFlowImageFilter<ImageType,ImageType> DenoiserType; DenoiserType::Pointer denoiser = DenoiserType::New(); denoiser->SetInput( source->GetOutput() ); denoiser->SetTimeStep( 0.05 ); denoiser->SetNumberOfIterations( 8 ); ShowProgressObject progressWatch(denoiser); itk::SimpleMemberCommand<ShowProgressObject>::Pointer command; command = itk::SimpleMemberCommand<ShowProgressObject>::New(); command->SetCallbackFunction(&progressWatch, &ShowProgressObject::ShowProgress); denoiser->AddObserver( itk::ProgressEvent(), command); denoiser->Update(); std::cout << "Run CurvatureFlowImageFilter using streamer" << std::endl; typedef itk::CastImageFilter<ImageType,ImageType> CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput( denoiser->GetInput() ); DenoiserType::Pointer denoiser2 = DenoiserType::New(); denoiser2->SetInput( caster->GetOutput() ); denoiser2->SetTimeStep( denoiser->GetTimeStep() ); denoiser2->SetNumberOfIterations( denoiser->GetNumberOfIterations() ); typedef itk::StreamingImageFilter<ImageType,ImageType> StreamerType; StreamerType::Pointer streamer = StreamerType::New(); streamer->SetInput( denoiser2->GetOutput() ); streamer->SetNumberOfStreamDivisions( 3 ); streamer->Update(); std::cout << "Compare stand-alone and streamer outputs" << std::endl; typedef itk::ImageRegionIterator<ImageType> IteratorType; IteratorType it1( denoiser->GetOutput(), denoiser->GetOutput()->GetBufferedRegion() ); IteratorType it2( streamer->GetOutput(), streamer->GetOutput()->GetBufferedRegion() ); bool testPass = true; while( !it1.IsAtEnd() ) { if( it1.Get() != it2.Get() ) { testPass = false; } ++it1; ++it2; } if( !testPass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } // Exercise other member functions here denoiser->Print( std::cout ); itk::VTKImageIO::Pointer vtkIO; vtkIO = itk::VTKImageIO::New(); typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( streamer->GetOutput() ); writer->SetFileName(argv[1]); writer->SetImageIO(vtkIO); writer->Write(); std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <commit_msg>COMP: Adding additional output if a test fails.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkCurvatureFlowTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkCurvatureFlowImageFilter.h" #include "itkRandomImageSource.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkVTKImageIO.h" #include "itkTextOutput.h" #include "itkCommand.h" #include "itkCastImageFilter.h" #include "itkStreamingImageFilter.h" #include "itkImageRegionIterator.h" #include "itkFiniteDifferenceFunction.h" namespace { // The following three classes are used to support callbacks // on the filter in the pipeline that follows later class ShowProgressObject { public: ShowProgressObject(itk::ProcessObject* o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::ProcessObject::Pointer m_Process; }; } namespace itk { // Dummy difference function for error testing template <class TImageType> class DummyFunction : public FiniteDifferenceFunction<TImageType> { public: typedef DummyFunction Self; typedef FiniteDifferenceFunction<TImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; itkNewMacro(Self); typedef typename Superclass::NeighborhoodType NeighborhoodType; typedef typename Superclass::FloatOffsetType FloatOffsetType; typedef typename Superclass::PixelType PixelType; typedef typename Superclass::TimeStepType TimeStepType; virtual PixelType ComputeUpdate( const NeighborhoodType &, void *, const FloatOffsetType & ) { return 0; } virtual TimeStepType ComputeGlobalTimeStep( void * ) const { return 0; } virtual void *GetGlobalDataPointer() const { return NULL; } virtual void ReleaseGlobalDataPointer(void *) const {} protected: DummyFunction() {} ~DummyFunction() {} private: DummyFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } int itkCurvatureFlowTest(int argc, char* argv[] ) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " outputFile" << std::endl; return EXIT_FAILURE; } itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); typedef float PixelType; enum { ImageDimension = 2 }; typedef itk::Image<PixelType, ImageDimension> ImageType; //------------------------------------------------------------------------ std::cout << "Test error handling." << std::endl; typedef itk::CurvatureFlowImageFilter<ImageType,ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( NULL ); bool passed = false; try { std::cout << "Test when input is NULL." << std::endl; filter->Update(); } catch( itk::ExceptionObject& err ) { std::cout << "Caught expected error." << std::endl; std::cout << err << std::endl; passed = true; } if ( !passed ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } // --------------------------------------------------------------------------- try { std::cout << "Test when wrong function type." << std::endl; typedef itk::DummyFunction<ImageType> FunctionType; filter = FilterType::New(); FunctionType::Pointer function = FunctionType::New(); ImageType::Pointer dummy = ImageType::New(); ImageType::SizeType size; size.Fill( 3 ); ImageType::RegionType region(size); dummy->SetRegions( region ); dummy->Allocate(); dummy->FillBuffer( 0.2 ); filter->SetInput( dummy ); filter->SetNumberOfIterations( 2 ); filter->SetDifferenceFunction( function ); filter->Update(); } catch( itk::ExceptionObject& err ) { std::cout << "Caught expected error." << std::endl; std::cout << err << std::endl; } //----------------------------------------------------------------------- std::cout << "Create input image using RandomImageSource" << std::endl; typedef itk::RandomImageSource<ImageType> SourceType; SourceType::Pointer source = SourceType::New(); unsigned long size[ImageDimension] = {64,64}; source->SetSize( size ); source->SetMin(0.0); source->SetMax(1.0); source->Update(); std::cout << "Run CurvatureFlowImageFiler with progress cout's" << std::endl; typedef itk::CurvatureFlowImageFilter<ImageType,ImageType> DenoiserType; DenoiserType::Pointer denoiser = DenoiserType::New(); denoiser->SetInput( source->GetOutput() ); denoiser->SetTimeStep( 0.05 ); denoiser->SetNumberOfIterations( 8 ); ShowProgressObject progressWatch(denoiser); itk::SimpleMemberCommand<ShowProgressObject>::Pointer command; command = itk::SimpleMemberCommand<ShowProgressObject>::New(); command->SetCallbackFunction(&progressWatch, &ShowProgressObject::ShowProgress); denoiser->AddObserver( itk::ProgressEvent(), command); denoiser->Update(); std::cout << "Run CurvatureFlowImageFilter using streamer" << std::endl; typedef itk::CastImageFilter<ImageType,ImageType> CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput( denoiser->GetInput() ); DenoiserType::Pointer denoiser2 = DenoiserType::New(); denoiser2->SetInput( caster->GetOutput() ); denoiser2->SetTimeStep( denoiser->GetTimeStep() ); denoiser2->SetNumberOfIterations( denoiser->GetNumberOfIterations() ); typedef itk::StreamingImageFilter<ImageType,ImageType> StreamerType; StreamerType::Pointer streamer = StreamerType::New(); streamer->SetInput( denoiser2->GetOutput() ); streamer->SetNumberOfStreamDivisions( 3 ); streamer->Update(); std::cout << "Compare stand-alone and streamer outputs" << std::endl; typedef itk::ImageRegionIterator<ImageType> IteratorType; IteratorType it1( denoiser->GetOutput(), denoiser->GetOutput()->GetBufferedRegion() ); IteratorType it2( streamer->GetOutput(), streamer->GetOutput()->GetBufferedRegion() ); bool testPass = true; unsigned int failedPixels = 0; while( !it1.IsAtEnd() ) { if( it1.Get() != it2.Get() ) { if (failedPixels == 0) { std::cout << "it1.Get() != it2.Get(): " << it1.Get() << " != " << it2.Get() << std::endl; } failedPixels++; testPass = false; } ++it1; ++it2; } if( !testPass ) { std::cout << "Test failed." << std::endl; std::cout << "Number of failed pixels: " << failedPixels << std::endl; return EXIT_FAILURE; } // Exercise other member functions here denoiser->Print( std::cout ); itk::VTKImageIO::Pointer vtkIO; vtkIO = itk::VTKImageIO::New(); typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( streamer->GetOutput() ); writer->SetFileName(argv[1]); writer->SetImageIO(vtkIO); writer->Write(); std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbVcaImageFilter.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" const unsigned int Dimension = 2; typedef double PixelType; typedef double PrecisionType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VCAImageFilter<VectorImageType> VCAFilterType; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileWriter<VectorImageType> WriterType; int otbVCAImageFilterTestHighSNR(int argc, char * argv[]) { const char * inputImage = argv[1]; const char * outputImage = argv[2]; const unsigned int nbEndmembers = atoi(argv[3]); ReaderType::Pointer readerImage = ReaderType::New(); readerImage->SetFileName(inputImage); VCAFilterType::Pointer vca = VCAFilterType::New(); vca->SetNumberOfEndmembers(nbEndmembers); vca->SetInput(readerImage->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputImage); writer->SetInput(vca->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <commit_msg>ENH: add instanciation test for VCA<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbVcaImageFilter.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" const unsigned int Dimension = 2; typedef double PixelType; typedef double PrecisionType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VCAImageFilter<VectorImageType> VCAFilterType; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileWriter<VectorImageType> WriterType; int otbVCAImageFilterNew(int argc, char * argv[]) { VCAFilterType::Pointer vca = VCAFilterType::New(); std::cout << vca << std::endl; return EXIT_SUCCESS; } int otbVCAImageFilterTestHighSNR(int argc, char * argv[]) { const char * inputImage = argv[1]; const char * outputImage = argv[2]; const unsigned int nbEndmembers = atoi(argv[3]); ReaderType::Pointer readerImage = ReaderType::New(); readerImage->SetFileName(inputImage); VCAFilterType::Pointer vca = VCAFilterType::New(); vca->SetNumberOfEndmembers(nbEndmembers); vca->SetInput(readerImage->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputImage); writer->SetInput(vca->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include "uct_p2p_test.h" extern "C" { #include <ucs/arch/atomic.h> } class uct_flush_test : public uct_test { public: static const uint64_t SEED1 = 0x1111111111111111lu; static const uint64_t SEED2 = 0x2222222222222222lu; static const uint64_t SEED3 = 0x3333333333333333lu; static const int AM_ID = 1; typedef void (uct_flush_test::* flush_func_t)(); struct test_req_t { uct_pending_req_t uct; uct_completion_t comp; mapped_buffer *sendbuf; uct_flush_test *test; }; void init() { if (UCT_DEVICE_TYPE_SELF == GetParam()->dev_type) { entity *e = uct_test::create_entity(0); m_entities.push_back(e); e->connect(0, *e, 0); } else { entity *m_sender = uct_test::create_entity(0); m_entities.push_back(m_sender); entity *m_receiver = uct_test::create_entity(0); m_entities.push_back(m_receiver); m_sender->connect(0, *m_receiver, 0); } am_rx_count = 0; } static size_t pack_cb(void *dest, void *arg) { const mapped_buffer *sendbuf = (const mapped_buffer *)arg; memcpy(dest, sendbuf->ptr(), sendbuf->length()); return sendbuf->length(); } void blocking_put_bcopy(const mapped_buffer &sendbuf, const mapped_buffer &recvbuf) { ssize_t status; for (;;) { status = uct_ep_put_bcopy(sender().ep(0), pack_cb, (void*)&sendbuf, recvbuf.addr(), recvbuf.rkey()); if (status >= 0) { return; } else if (status == UCS_ERR_NO_RESOURCE) { progress(); continue; } else { ASSERT_UCS_OK((ucs_status_t)status); } } } void blocking_am_bcopy(const mapped_buffer &sendbuf) { ssize_t status; for (;;) { status = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)&sendbuf); if (status >= 0) { return; } else if (status == UCS_ERR_NO_RESOURCE) { progress(); continue; } else { ASSERT_UCS_OK((ucs_status_t)status); } } } static ucs_status_t am_handler(void *arg, void *data, size_t length, void *desc) { const mapped_buffer *recvbuf = (const mapped_buffer *)arg; memcpy(recvbuf->ptr(), data, ucs_min(length, recvbuf->length())); ucs_atomic_add32(&am_rx_count, 1); return UCS_OK; } ucs_status_t am_send_pending(test_req_t *am_req) { ssize_t status; status = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)am_req->sendbuf); if (status >= 0) { --am_req->comp.count; return UCS_OK; } else { return (ucs_status_t)status; } } static ucs_status_t am_progress(uct_pending_req_t *req) { test_req_t *am_req = ucs_container_of(req, test_req_t, uct); return am_req->test->am_send_pending(am_req); } static ucs_status_t flush_progress(uct_pending_req_t *req) { test_req_t *flush_req = ucs_container_of(req, test_req_t, uct); ucs_status_t status; status = uct_ep_flush(flush_req->test->sender().ep(0), 0, &flush_req->comp); if (status == UCS_OK) { --flush_req->comp.count; return UCS_OK; } else if (status == UCS_INPROGRESS) { return UCS_OK; } else if (status == UCS_ERR_NO_RESOURCE) { return UCS_ERR_NO_RESOURCE; } else { UCS_TEST_ABORT("Error: " << ucs_status_string(status)); } } void test_flush_put_bcopy(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_PUT_SHORT); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); blocking_put_bcopy(sendbuf, recvbuf); (this->*flush)(); recvbuf.pattern_check(SEED3); } void wait_am(unsigned count) { while (am_rx_count < count) { short_progress_loop(); } } void test_flush_am_zcopy(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_ZCOPY); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); uct_completion_t zcomp; zcomp.count = 2; zcomp.func = NULL; ucs_status_t status; UCS_TEST_GET_BUFFER_IOV(iov, iovcnt, sendbuf.ptr(), sendbuf.length(), sendbuf.memh(), sender().iface_attr().cap.am.max_iov); do { status = uct_ep_am_zcopy(sender().ep(0), AM_ID, NULL, 0, iov, iovcnt, &zcomp); } while (status == UCS_ERR_NO_RESOURCE); ASSERT_UCS_OK_OR_INPROGRESS(status); if (status == UCS_OK) { --zcomp.count; } (this->*flush)(); EXPECT_EQ(1, zcomp.count); /* Zero copy op should be already completed since flush returned */ sender().destroy_ep(0); wait_am(1); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } void test_flush_am_disconnect(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_BCOPY); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); blocking_am_bcopy(sendbuf); (this->*flush)(); sender().destroy_ep(0); wait_am(1); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } void flush_ep_no_comp() { ucs_status_t status; do { progress(); status = uct_ep_flush(sender().ep(0), 0, NULL); } while ((status == UCS_ERR_NO_RESOURCE) || (status == UCS_INPROGRESS)); ASSERT_UCS_OK(status); } void flush_iface_no_comp() { ucs_status_t status; do { progress(); status = uct_iface_flush(sender().iface(), 0, NULL); } while ((status == UCS_ERR_NO_RESOURCE) || (status == UCS_INPROGRESS)); ASSERT_UCS_OK(status); } void flush_ep_nb() { uct_completion_t comp; ucs_status_t status; comp.count = 2; comp.func = NULL; do { progress(); status = uct_ep_flush(sender().ep(0), 0, &comp); } while (status == UCS_ERR_NO_RESOURCE); ASSERT_UCS_OK_OR_INPROGRESS(status); if (status == UCS_OK) { return; } /* coverity[loop_condition] */ while (comp.count != 1) { progress(); } } protected: uct_test::entity& sender() { return **m_entities.begin(); } uct_test::entity& receiver() { return **(m_entities.end() - 1); } static uint32_t am_rx_count; }; uint32_t uct_flush_test::am_rx_count = 0; UCS_TEST_P(uct_flush_test, put_bcopy_flush_ep_no_comp) { test_flush_put_bcopy(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, put_bcopy_flush_iface_no_comp) { test_flush_put_bcopy(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, put_bcopy_flush_ep_nb) { test_flush_put_bcopy(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_ep_no_comp) { test_flush_am_zcopy(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_iface_no_comp) { test_flush_am_zcopy(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_ep_nb) { test_flush_am_zcopy(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_flush_ep_no_comp) { test_flush_am_disconnect(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, am_flush_iface_no_comp) { test_flush_am_disconnect(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, am_flush_ep_nb) { test_flush_am_disconnect(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_pending_flush_nb) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_BCOPY | UCT_IFACE_FLAG_PENDING); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); /* Send until resources are exhausted or timeout in 1sec*/ unsigned count = 0; ucs_time_t loop_end_limit = ucs_get_time() + ucs_time_from_sec(1.0); ssize_t packed_len; for (;;) { packed_len = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)&sendbuf); if ((packed_len == UCS_ERR_NO_RESOURCE) || (ucs_get_time() > loop_end_limit)) { break; } if (packed_len >= 0) { ++count; } else { ASSERT_UCS_OK((ucs_status_t)packed_len); } } /* Queue some pending AMs */ ucs_status_t status; std::vector<test_req_t> reqs; reqs.resize(10); for (std::vector<test_req_t>::iterator it = reqs.begin(); it != reqs.end();) { it->sendbuf = &sendbuf; it->test = this; it->uct.func = am_progress; it->comp.count = 2; it->comp.func = NULL; status = uct_ep_pending_add(sender().ep(0), &it->uct); if (UCS_ERR_BUSY == status) { /* User advised to retry the send. It means no requests added * to the queue */ it = reqs.erase(it); status = UCS_OK; } else { ++it; } ASSERT_UCS_OK(status); } /* Try to start a flush */ test_req_t flush_req; flush_req.comp.count = 2; flush_req.comp.func = NULL; status = uct_ep_flush(sender().ep(0), 0, &flush_req.comp); if (status == UCS_OK) { --flush_req.comp.count; } else if (status == UCS_ERR_NO_RESOURCE) { /* If flush returned NO_RESOURCE, add to pending must succeed */ flush_req.test = this; flush_req.uct.func = flush_progress; status = uct_ep_pending_add(sender().ep(0), &flush_req.uct); EXPECT_EQ(UCS_OK, status); } else if (status == UCS_INPROGRESS) { } else { ASSERT_UCS_OK(status); } /* timeout used to prevent test hung */ ucs_time_t loop_end_limit_comp = ucs_get_time() + ucs_time_from_sec(1.0); /* coverity[loop_condition] */ while (flush_req.comp.count != 1) { if (ucs_get_time() > loop_end_limit_comp) { break; } progress(); } EXPECT_TRUE(flush_req.comp.count == 1); while (!reqs.empty()) { EXPECT_EQ(1, reqs.back().comp.count); reqs.pop_back(); } sender().destroy_ep(0); wait_am(count); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } UCT_INSTANTIATE_TEST_CASE(uct_flush_test) <commit_msg>TEST/FLUSH: Fix counting active messages - pending should be counted too<commit_after>/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include "uct_p2p_test.h" extern "C" { #include <ucs/arch/atomic.h> } class uct_flush_test : public uct_test { public: static const uint64_t SEED1 = 0x1111111111111111lu; static const uint64_t SEED2 = 0x2222222222222222lu; static const uint64_t SEED3 = 0x3333333333333333lu; static const int AM_ID = 1; typedef void (uct_flush_test::* flush_func_t)(); struct test_req_t { uct_pending_req_t uct; uct_completion_t comp; mapped_buffer *sendbuf; uct_flush_test *test; }; void init() { if (UCT_DEVICE_TYPE_SELF == GetParam()->dev_type) { entity *e = uct_test::create_entity(0); m_entities.push_back(e); e->connect(0, *e, 0); } else { entity *m_sender = uct_test::create_entity(0); m_entities.push_back(m_sender); entity *m_receiver = uct_test::create_entity(0); m_entities.push_back(m_receiver); m_sender->connect(0, *m_receiver, 0); } am_rx_count = 0; } static size_t pack_cb(void *dest, void *arg) { const mapped_buffer *sendbuf = (const mapped_buffer *)arg; memcpy(dest, sendbuf->ptr(), sendbuf->length()); return sendbuf->length(); } void blocking_put_bcopy(const mapped_buffer &sendbuf, const mapped_buffer &recvbuf) { ssize_t status; for (;;) { status = uct_ep_put_bcopy(sender().ep(0), pack_cb, (void*)&sendbuf, recvbuf.addr(), recvbuf.rkey()); if (status >= 0) { return; } else if (status == UCS_ERR_NO_RESOURCE) { progress(); continue; } else { ASSERT_UCS_OK((ucs_status_t)status); } } } void blocking_am_bcopy(const mapped_buffer &sendbuf) { ssize_t status; for (;;) { status = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)&sendbuf); if (status >= 0) { return; } else if (status == UCS_ERR_NO_RESOURCE) { progress(); continue; } else { ASSERT_UCS_OK((ucs_status_t)status); } } } static ucs_status_t am_handler(void *arg, void *data, size_t length, void *desc) { const mapped_buffer *recvbuf = (const mapped_buffer *)arg; memcpy(recvbuf->ptr(), data, ucs_min(length, recvbuf->length())); ucs_atomic_add32(&am_rx_count, 1); return UCS_OK; } ucs_status_t am_send_pending(test_req_t *am_req) { ssize_t status; status = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)am_req->sendbuf); if (status >= 0) { --am_req->comp.count; return UCS_OK; } else { return (ucs_status_t)status; } } static ucs_status_t am_progress(uct_pending_req_t *req) { test_req_t *am_req = ucs_container_of(req, test_req_t, uct); return am_req->test->am_send_pending(am_req); } static ucs_status_t flush_progress(uct_pending_req_t *req) { test_req_t *flush_req = ucs_container_of(req, test_req_t, uct); ucs_status_t status; status = uct_ep_flush(flush_req->test->sender().ep(0), 0, &flush_req->comp); if (status == UCS_OK) { --flush_req->comp.count; return UCS_OK; } else if (status == UCS_INPROGRESS) { return UCS_OK; } else if (status == UCS_ERR_NO_RESOURCE) { return UCS_ERR_NO_RESOURCE; } else { UCS_TEST_ABORT("Error: " << ucs_status_string(status)); } } void test_flush_put_bcopy(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_PUT_SHORT); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); blocking_put_bcopy(sendbuf, recvbuf); (this->*flush)(); recvbuf.pattern_check(SEED3); } void wait_am(unsigned count) { while (am_rx_count < count) { short_progress_loop(); } } void test_flush_am_zcopy(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_ZCOPY); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); uct_completion_t zcomp; zcomp.count = 2; zcomp.func = NULL; ucs_status_t status; UCS_TEST_GET_BUFFER_IOV(iov, iovcnt, sendbuf.ptr(), sendbuf.length(), sendbuf.memh(), sender().iface_attr().cap.am.max_iov); do { status = uct_ep_am_zcopy(sender().ep(0), AM_ID, NULL, 0, iov, iovcnt, &zcomp); } while (status == UCS_ERR_NO_RESOURCE); ASSERT_UCS_OK_OR_INPROGRESS(status); if (status == UCS_OK) { --zcomp.count; } (this->*flush)(); EXPECT_EQ(1, zcomp.count); /* Zero copy op should be already completed since flush returned */ sender().destroy_ep(0); wait_am(1); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } void test_flush_am_disconnect(flush_func_t flush) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_BCOPY); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); blocking_am_bcopy(sendbuf); (this->*flush)(); sender().destroy_ep(0); wait_am(1); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } void flush_ep_no_comp() { ucs_status_t status; do { progress(); status = uct_ep_flush(sender().ep(0), 0, NULL); } while ((status == UCS_ERR_NO_RESOURCE) || (status == UCS_INPROGRESS)); ASSERT_UCS_OK(status); } void flush_iface_no_comp() { ucs_status_t status; do { progress(); status = uct_iface_flush(sender().iface(), 0, NULL); } while ((status == UCS_ERR_NO_RESOURCE) || (status == UCS_INPROGRESS)); ASSERT_UCS_OK(status); } void flush_ep_nb() { uct_completion_t comp; ucs_status_t status; comp.count = 2; comp.func = NULL; do { progress(); status = uct_ep_flush(sender().ep(0), 0, &comp); } while (status == UCS_ERR_NO_RESOURCE); ASSERT_UCS_OK_OR_INPROGRESS(status); if (status == UCS_OK) { return; } /* coverity[loop_condition] */ while (comp.count != 1) { progress(); } } protected: uct_test::entity& sender() { return **m_entities.begin(); } uct_test::entity& receiver() { return **(m_entities.end() - 1); } static uint32_t am_rx_count; }; uint32_t uct_flush_test::am_rx_count = 0; UCS_TEST_P(uct_flush_test, put_bcopy_flush_ep_no_comp) { test_flush_put_bcopy(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, put_bcopy_flush_iface_no_comp) { test_flush_put_bcopy(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, put_bcopy_flush_ep_nb) { test_flush_put_bcopy(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_ep_no_comp) { test_flush_am_zcopy(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_iface_no_comp) { test_flush_am_zcopy(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, am_zcopy_flush_ep_nb) { test_flush_am_zcopy(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_flush_ep_no_comp) { test_flush_am_disconnect(&uct_flush_test::flush_ep_no_comp); } UCS_TEST_P(uct_flush_test, am_flush_iface_no_comp) { test_flush_am_disconnect(&uct_flush_test::flush_iface_no_comp); } UCS_TEST_P(uct_flush_test, am_flush_ep_nb) { test_flush_am_disconnect(&uct_flush_test::flush_ep_nb); } UCS_TEST_P(uct_flush_test, am_pending_flush_nb) { const size_t length = 8; check_caps(UCT_IFACE_FLAG_AM_BCOPY | UCT_IFACE_FLAG_PENDING); mapped_buffer sendbuf(length, SEED1, sender()); mapped_buffer recvbuf(length, SEED2, receiver()); sendbuf.pattern_fill(SEED3); uct_iface_set_am_handler(receiver().iface(), AM_ID, am_handler, &recvbuf, UCT_AM_CB_FLAG_ASYNC); /* Send until resources are exhausted or timeout in 1sec*/ unsigned count = 0; ucs_time_t loop_end_limit = ucs_get_time() + ucs_time_from_sec(1.0); ssize_t packed_len; for (;;) { packed_len = uct_ep_am_bcopy(sender().ep(0), AM_ID, pack_cb, (void*)&sendbuf); if ((packed_len == UCS_ERR_NO_RESOURCE) || (ucs_get_time() > loop_end_limit)) { break; } if (packed_len >= 0) { ++count; } else { ASSERT_UCS_OK((ucs_status_t)packed_len); } } /* Queue some pending AMs */ ucs_status_t status; std::vector<test_req_t> reqs; reqs.resize(10); for (std::vector<test_req_t>::iterator it = reqs.begin(); it != reqs.end();) { it->sendbuf = &sendbuf; it->test = this; it->uct.func = am_progress; it->comp.count = 2; it->comp.func = NULL; status = uct_ep_pending_add(sender().ep(0), &it->uct); if (UCS_ERR_BUSY == status) { /* User advised to retry the send. It means no requests added * to the queue */ it = reqs.erase(it); status = UCS_OK; } else { ++count; ++it; } ASSERT_UCS_OK(status); } /* Try to start a flush */ test_req_t flush_req; flush_req.comp.count = 2; flush_req.comp.func = NULL; status = uct_ep_flush(sender().ep(0), 0, &flush_req.comp); if (status == UCS_OK) { --flush_req.comp.count; } else if (status == UCS_ERR_NO_RESOURCE) { /* If flush returned NO_RESOURCE, add to pending must succeed */ flush_req.test = this; flush_req.uct.func = flush_progress; status = uct_ep_pending_add(sender().ep(0), &flush_req.uct); EXPECT_EQ(UCS_OK, status); } else if (status == UCS_INPROGRESS) { } else { ASSERT_UCS_OK(status); } /* timeout used to prevent test hung */ ucs_time_t loop_end_limit_comp = ucs_get_time() + ucs_time_from_sec(1.0); /* coverity[loop_condition] */ while (flush_req.comp.count != 1) { if (ucs_get_time() > loop_end_limit_comp) { break; } progress(); } EXPECT_TRUE(flush_req.comp.count == 1); while (!reqs.empty()) { EXPECT_EQ(1, reqs.back().comp.count); reqs.pop_back(); } sender().destroy_ep(0); wait_am(count); uct_iface_set_am_handler(receiver().iface(), AM_ID, NULL, NULL, 0); recvbuf.pattern_check(SEED3); } UCT_INSTANTIATE_TEST_CASE(uct_flush_test) <|endoftext|>
<commit_before>#include <sh.h> #include <stdio.h> int main(void) { MCU_sw ic; ic.led.set(); //ic.Uart.putch('H'); //ic.Uart.putch('e'); //ic.Uart.putch('l'); //ic.Uart.putch('l'); //ic.Uart.putch('o'); ic.stdio.setio(&ic.Uart); icprintf("Hello world from printf\n"); while (1) { if (ic.buttons.b1.isOn() != ic.buttons.b2.isOn()) { ic.led.clr(); ic.relay.r1.set(); } else { ic.led.set(); ic.relay.r1.clr(); } ic.sleep_ms(100); } return 0; } <commit_msg>Test for autogenerating GUI for C model<commit_after>#include <sh.h> #include <stdio.h> int main(void) { MCU_sw ic; ic.led.set(); ic.stdio.setio(&ic.Uart); icprintf("Hello world from printf\n"); while (1) { if (ic.buttons.b1.isOn() != ic.buttons.b2.isOn()) { ic.led.clr(); ic.relay.r1.set(); } else { ic.led.set(); ic.relay.r1.clr(); } ic.sleep_ms(100); } return 0; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- //-----------------------------------------------------------------------el- //Antioch #include "antioch/vector_utils_decl.h" #include "antioch/physical_constants.h" #include "antioch/sigma_bin_converter.h" #include "antioch/vector_utils.h" //Planet #include "planet/photon_evaluator.h" #include "planet/planet_constants.h" //C++ #include <vector> #include <iostream> #include <fstream> #include <string> #include <cmath> #include <limits> template<typename Scalar> int check_test(Scalar theory, Scalar cal, const std::string &words) { const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100.; if(std::abs((theory-cal)/theory) < tol)return 0; std::cout << std::scientific << std::setprecision(20) << "failed test: " << words << "\n" << "theory: " << theory << "\ncalculated: " << cal << "\ndifference: " << std::abs((theory-cal)/cal) << "\ntolerance: " << tol << std::endl; return 1; } template<typename VectorScalar> void linear_interpolation(const VectorScalar &temp0, const VectorScalar &alt0, const VectorScalar &alt1, VectorScalar &temp1) { unsigned int j(0); typename Antioch::value_type<VectorScalar>::type a; typename Antioch::value_type<VectorScalar>::type b; temp1.resize(alt1.size()); for(unsigned int iz = 0; iz < alt1.size(); iz++) { while(alt0[j] < alt1[iz]) { j++; if(!(j < alt0.size()))break; } if(j == 0) { Antioch::set_zero(a); b = temp0[j]; }else if(j < alt0.size() - 1) { a = (temp0[j] - temp0[j-1])/(alt0[j] - alt0[j-1]); b = temp0[j] - a * alt0[j]; }else { Antioch::set_zero(a); b = temp0.back(); } temp1[iz] = a * alt1[iz] + b; } } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_temperature(VectorScalar &T0, VectorScalar &Tz, const std::string &file) { T0.clear(); Tz.clear(); std::string line; std::ifstream temp(file); getline(temp,line); while(!temp.eof()) { Scalar t,tz,dt,dtz; temp >> t >> tz >> dt >> dtz; T0.push_back(t); Tz.push_back(tz); } temp.close(); return; } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_crossSection(const std::string &file, unsigned int nbr, VectorScalar &lambda, VectorScalar &sigma) { std::string line; std::ifstream sig_f(file); getline(sig_f,line); while(!sig_f.eof()) { Scalar wv,sigt,sigbr; sig_f >> wv >> sigt; for(unsigned int i = 0; i < nbr; i++)sig_f >> sigbr; lambda.push_back(wv/10.);//A -> nm sigma.push_back(sigt*10.);//cm-2/A -> m-2/nm } sig_f.close(); return; } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_hv_flux(VectorScalar &lambda, VectorScalar &phy1AU, const std::string &file) { std::string line; std::ifstream flux_1AU(file); getline(flux_1AU,line); while(!flux_1AU.eof()) { Scalar wv,ir,dirr; flux_1AU >> wv >> ir >> dirr; if(!lambda.empty() && wv == lambda.back())continue; lambda.push_back(wv);//nm phy1AU.push_back(ir);//W/m2/nm } flux_1AU.close(); return; } template<typename Scalar> Scalar barometry(const Scalar &zmin, const Scalar &z, const Scalar &T, const Scalar &Mm, const Scalar &botdens) { return botdens * Antioch::ant_exp(-(z - zmin)/((Planet::Constants::Titan::radius<Scalar>() + z) * (Planet::Constants::Titan::radius<Scalar>() + zmin) * 1e3 * Antioch::Constants::Avogadro<Scalar>() * Planet::Constants::Universal::kb<Scalar>() * T / (Planet::Constants::Universal::G<Scalar>() * Planet::Constants::Titan::mass<Scalar>() * Mm)) ); } template<typename Scalar, typename VectorScalar, typename MatrixScalar> void calculate_densities(MatrixScalar &densities, const Scalar &tot_dens, const VectorScalar &molar_frac, const Scalar &zmin,const Scalar &zmax,const Scalar &zstep, const VectorScalar &T, const VectorScalar &mm) { unsigned int iz(0); Scalar Mm; Antioch::set_zero(Mm); for(unsigned int s = 0; s < molar_frac.size(); s++) { Mm += molar_frac[s] * mm[s]; } Mm *= 1e-3;//to kg densities.clear(); densities.resize(molar_frac.size()); for(Scalar z = zmin; z <= zmax; z += zstep) { for(unsigned int s = 0; s < molar_frac.size(); s++) { densities[s].push_back(molar_frac[s] * barometry(zmin,z,T[iz],Mm,tot_dens)); } iz++; } return; } template<typename Scalar, typename VectorScalar, typename MatrixScalar> void calculate_tau(MatrixScalar &opacity, const Planet::Chapman<Scalar> &chapman, const std::vector<VectorScalar*> &cs, const VectorScalar &lambda_ref, const MatrixScalar &sum_dens, const Scalar &bot_tot_dens, const VectorScalar &molar_frac, const VectorScalar &mm, const VectorScalar &T, const Scalar &zmin, const Scalar &zmax, const Scalar &zstep) { Scalar Mm; Antioch::set_zero(Mm); for(unsigned int s = 0; s < molar_frac.size(); s++) { Mm += molar_frac[s] * mm[s]; } Mm *= 1e-3; //to kg opacity.resize(T.size()); Antioch::SigmaBinConverter<VectorScalar> bin_converter; unsigned int iz(0); for(Scalar z = zmin; z <= zmax; z += zstep) { Scalar g = Planet::Constants::g(Planet::Constants::Titan::radius<Scalar>(),z,Planet::Constants::Titan::mass<Scalar>()); Scalar H = Planet::Constants::Universal::kb<Scalar>() * T[iz] / (g * Mm ) * Antioch::Constants::Avogadro<Scalar>(); //to m-3 Scalar a = (Planet::Constants::Titan::radius<Scalar>() + z) / H; //to m opacity[iz].resize(lambda_ref.size(),0.L); for(unsigned int s = 0; s < sum_dens.size(); s++) { VectorScalar sigma_process; bin_converter.y_on_custom_grid(*(cs[2*s]),*(cs[2*s+1]),lambda_ref,sigma_process); for(unsigned int il = 0; il < lambda_ref.size(); il++) { opacity[iz][il] += sigma_process[il] * sum_dens[s][iz]; } } for(unsigned int il = 0; il < lambda_ref.size(); il++) { opacity[iz][il] *= chapman(a); } iz++; } } template <typename Scalar> int tester() { //description std::vector<std::string> neutrals; std::vector<std::string> ions; neutrals.push_back("N2"); neutrals.push_back("CH4"); //ionic system contains neutral system ions = neutrals; ions.push_back("N2+"); Scalar MN(14.008L), MC(12.011), MH(1.008L); Scalar MN2 = 2.L*MN , MCH4 = MC + 4.L*MH; std::vector<Scalar> Mm; Mm.push_back(MN2); Mm.push_back(MCH4); //densities std::vector<Scalar> molar_frac; molar_frac.push_back(0.96L); molar_frac.push_back(0.04L); molar_frac.push_back(0.L); Scalar dens_tot(1e12L); //hard sphere radius std::vector<Scalar> hard_sphere_radius; hard_sphere_radius.push_back(2.0675e-8L * 1e-2L); //N2 in cm -> m hard_sphere_radius.push_back(2.3482e-8L * 1e-2L); //CH4 in cm -> m //zenith angle Scalar chi(120); //photon flux std::vector<Scalar> lambda_hv,phy1AU; read_hv_flux<Scalar>(lambda_hv,phy1AU,"./input/hv_SSI.dat"); ////cross-section std::vector<Scalar> lambda_N2,sigma_N2; std::vector<Scalar> lambda_CH4, sigma_CH4; read_crossSection<Scalar>("./input/N2_hv_cross-sections.dat",3,lambda_N2,sigma_N2); read_crossSection<Scalar>("./input/CH4_hv_cross-sections.dat",9,lambda_CH4,sigma_CH4); //altitudes Scalar zmin(600.),zmax(1400.),zstep(10.); /************************ * first level ************************/ //altitude Planet::Altitude<Scalar,std::vector<Scalar> > altitude(zmin,zmax,zstep); //neutrals Antioch::ChemicalMixture<Scalar> neutral_species(neutrals); //ions Antioch::ChemicalMixture<Scalar> ionic_species(ions); //chapman Planet::Chapman<Scalar> chapman(chi); //binary diffusion //not needed /************************ * second level ************************/ //temperature std::vector<Scalar> T0,Tz; read_temperature<Scalar>(T0,Tz,"input/temperature.dat"); std::vector<Scalar> neutral_temperature; linear_interpolation(T0,Tz,altitude.altitudes(),neutral_temperature); Planet::AtmosphericTemperature<Scalar, std::vector<Scalar> > temperature(neutral_temperature, neutral_temperature, altitude); //photon opacity Planet::PhotonOpacity<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > tau(altitude,chapman); //reaction sets //not needed /************************ * third level ************************/ //atmospheric mixture Planet::AtmosphericMixture<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > composition(neutral_species, ionic_species, altitude, temperature); composition.init_composition(molar_frac,dens_tot); composition.set_hard_sphere_radius(hard_sphere_radius); composition.initialize(); //kinetics evaluators //not needed /************************ * fourth level ************************/ //photon evaluator Planet::PhotonEvaluator<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > photon(altitude,tau,composition); photon.add_cross_section(lambda_N2, sigma_N2, Antioch::Species::N2); photon.add_cross_section(lambda_CH4, sigma_CH4, Antioch::Species::CH4); photon.set_photon_flux_at_top(lambda_hv, phy1AU, Planet::Constants::Saturn::d_Sun<Scalar>()); photon.update_photon_flux(); //molecular diffusion //not needed //eddy diffusion //not needed /************************ * checks ************************/ molar_frac.pop_back();//get the ion outta here std::vector<std::vector<Scalar> > densities; std::vector<Scalar> mm; mm.push_back(MN2); mm.push_back(MCH4); calculate_densities(densities,dens_tot,molar_frac,zmin,zmax,zstep,neutral_temperature,mm); for(Scalar z = zmax-zstep; z >= zmin; z -= zstep) { unsigned int iz = altitude.altitudes_map().at(z); unsigned int jz = altitude.altitudes_map().at(z+zstep); for(unsigned int s = 0; s < densities.size(); s++) { densities[s][iz] += densities[s][jz]; } } std::vector<std::vector<Scalar> > opacity; std::vector<std::vector<Scalar>*> cs; cs.push_back(&lambda_N2); cs.push_back(&sigma_N2); cs.push_back(&lambda_CH4); cs.push_back(&sigma_CH4); calculate_tau(opacity,chapman,cs,lambda_hv, densities,dens_tot,molar_frac,mm, neutral_temperature, zmin,zmax,zstep); std::vector<std::vector<Scalar> > phy_theo; phy_theo.resize(altitude.altitudes().size()); for(unsigned int iz = 0; iz < altitude.altitudes().size(); iz++) { phy_theo[iz].resize(lambda_hv.size()); for(unsigned int il = 0; il < lambda_hv.size(); il++) { phy_theo[iz][il] = phy1AU[il] / (Planet::Constants::Saturn::d_Sun<Scalar>() * Planet::Constants::Saturn::d_Sun<Scalar>()) * Antioch::ant_exp(-opacity[iz][il]); } } int return_flag(0); for(unsigned int iz = 0; iz < altitude.altitudes().size(); iz++) { for(unsigned int il = 0; il < lambda_hv.size(); il++) { return_flag = return_flag || check_test(phy_theo[iz][il], photon.photon_flux()[iz].flux()[il], "phy at altitude and wavelength"); if(return_flag) { std::cout << altitude.altitudes()[iz] << " " << lambda_hv[il] << std::endl; return return_flag; } } } return return_flag; } int main() { return (tester<float>() || tester<double>() || tester<long double>()); } <commit_msg>Simple correction, unnecessary line deleted<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- //-----------------------------------------------------------------------el- //Antioch #include "antioch/vector_utils_decl.h" #include "antioch/physical_constants.h" #include "antioch/sigma_bin_converter.h" #include "antioch/vector_utils.h" //Planet #include "planet/photon_evaluator.h" #include "planet/planet_constants.h" //C++ #include <vector> #include <iostream> #include <fstream> #include <string> #include <cmath> #include <limits> template<typename Scalar> int check_test(Scalar theory, Scalar cal, const std::string &words) { const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100.; if(std::abs((theory-cal)/theory) < tol)return 0; std::cout << std::scientific << std::setprecision(20) << "failed test: " << words << "\n" << "theory: " << theory << "\ncalculated: " << cal << "\ndifference: " << std::abs((theory-cal)/cal) << "\ntolerance: " << tol << std::endl; return 1; } template<typename VectorScalar> void linear_interpolation(const VectorScalar &temp0, const VectorScalar &alt0, const VectorScalar &alt1, VectorScalar &temp1) { unsigned int j(0); typename Antioch::value_type<VectorScalar>::type a; typename Antioch::value_type<VectorScalar>::type b; temp1.resize(alt1.size()); for(unsigned int iz = 0; iz < alt1.size(); iz++) { while(alt0[j] < alt1[iz]) { j++; if(!(j < alt0.size()))break; } if(j == 0) { Antioch::set_zero(a); b = temp0[j]; }else if(j < alt0.size() - 1) { a = (temp0[j] - temp0[j-1])/(alt0[j] - alt0[j-1]); b = temp0[j] - a * alt0[j]; }else { Antioch::set_zero(a); b = temp0.back(); } temp1[iz] = a * alt1[iz] + b; } } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_temperature(VectorScalar &T0, VectorScalar &Tz, const std::string &file) { T0.clear(); Tz.clear(); std::string line; std::ifstream temp(file); getline(temp,line); while(!temp.eof()) { Scalar t,tz,dt,dtz; temp >> t >> tz >> dt >> dtz; T0.push_back(t); Tz.push_back(tz); } temp.close(); return; } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_crossSection(const std::string &file, unsigned int nbr, VectorScalar &lambda, VectorScalar &sigma) { std::string line; std::ifstream sig_f(file); getline(sig_f,line); while(!sig_f.eof()) { Scalar wv,sigt,sigbr; sig_f >> wv >> sigt; for(unsigned int i = 0; i < nbr; i++)sig_f >> sigbr; lambda.push_back(wv/10.);//A -> nm sigma.push_back(sigt*10.);//cm-2/A -> m-2/nm } sig_f.close(); return; } template<typename Scalar, typename VectorScalar = std::vector<Scalar> > void read_hv_flux(VectorScalar &lambda, VectorScalar &phy1AU, const std::string &file) { std::string line; std::ifstream flux_1AU(file); getline(flux_1AU,line); while(!flux_1AU.eof()) { Scalar wv,ir,dirr; flux_1AU >> wv >> ir >> dirr; if(!lambda.empty() && wv == lambda.back())continue; lambda.push_back(wv);//nm phy1AU.push_back(ir);//W/m2/nm } flux_1AU.close(); return; } template<typename Scalar> Scalar barometry(const Scalar &zmin, const Scalar &z, const Scalar &T, const Scalar &Mm, const Scalar &botdens) { return botdens * Antioch::ant_exp(-(z - zmin)/((Planet::Constants::Titan::radius<Scalar>() + z) * (Planet::Constants::Titan::radius<Scalar>() + zmin) * 1e3 * Antioch::Constants::Avogadro<Scalar>() * Planet::Constants::Universal::kb<Scalar>() * T / (Planet::Constants::Universal::G<Scalar>() * Planet::Constants::Titan::mass<Scalar>() * Mm)) ); } template<typename Scalar, typename VectorScalar, typename MatrixScalar> void calculate_densities(MatrixScalar &densities, const Scalar &tot_dens, const VectorScalar &molar_frac, const Scalar &zmin,const Scalar &zmax,const Scalar &zstep, const VectorScalar &T, const VectorScalar &mm) { unsigned int iz(0); Scalar Mm; Antioch::set_zero(Mm); for(unsigned int s = 0; s < molar_frac.size(); s++) { Mm += molar_frac[s] * mm[s]; } Mm *= 1e-3;//to kg densities.clear(); densities.resize(molar_frac.size()); for(Scalar z = zmin; z <= zmax; z += zstep) { for(unsigned int s = 0; s < molar_frac.size(); s++) { densities[s].push_back(molar_frac[s] * barometry(zmin,z,T[iz],Mm,tot_dens)); } iz++; } return; } template<typename Scalar, typename VectorScalar, typename MatrixScalar> void calculate_tau(MatrixScalar &opacity, const Planet::Chapman<Scalar> &chapman, const std::vector<VectorScalar*> &cs, const VectorScalar &lambda_ref, const MatrixScalar &sum_dens, const VectorScalar &molar_frac, const VectorScalar &mm, const VectorScalar &T, const Scalar &zmin, const Scalar &zmax, const Scalar &zstep) { Scalar Mm; Antioch::set_zero(Mm); for(unsigned int s = 0; s < molar_frac.size(); s++) { Mm += molar_frac[s] * mm[s]; } Mm *= 1e-3; //to kg opacity.resize(T.size()); Antioch::SigmaBinConverter<VectorScalar> bin_converter; unsigned int iz(0); for(Scalar z = zmin; z <= zmax; z += zstep) { Scalar g = Planet::Constants::g(Planet::Constants::Titan::radius<Scalar>(),z,Planet::Constants::Titan::mass<Scalar>()); Scalar H = Planet::Constants::Universal::kb<Scalar>() * T[iz] / (g * Mm ) * Antioch::Constants::Avogadro<Scalar>(); //to m-3 Scalar a = (Planet::Constants::Titan::radius<Scalar>() + z) / H; //to m opacity[iz].resize(lambda_ref.size(),0.L); for(unsigned int s = 0; s < sum_dens.size(); s++) { VectorScalar sigma_process; bin_converter.y_on_custom_grid(*(cs[2*s]),*(cs[2*s+1]),lambda_ref,sigma_process); for(unsigned int il = 0; il < lambda_ref.size(); il++) { opacity[iz][il] += sigma_process[il] * sum_dens[s][iz]; } } for(unsigned int il = 0; il < lambda_ref.size(); il++) { opacity[iz][il] *= chapman(a); } iz++; } } template <typename Scalar> int tester() { //description std::vector<std::string> neutrals; std::vector<std::string> ions; neutrals.push_back("N2"); neutrals.push_back("CH4"); //ionic system contains neutral system ions = neutrals; ions.push_back("N2+"); Scalar MN(14.008L), MC(12.011), MH(1.008L); Scalar MN2 = 2.L*MN , MCH4 = MC + 4.L*MH; std::vector<Scalar> Mm; Mm.push_back(MN2); Mm.push_back(MCH4); //densities std::vector<Scalar> molar_frac; molar_frac.push_back(0.96L); molar_frac.push_back(0.04L); molar_frac.push_back(0.L); Scalar dens_tot(1e12L); //hard sphere radius std::vector<Scalar> hard_sphere_radius; hard_sphere_radius.push_back(2.0675e-8L * 1e-2L); //N2 in cm -> m hard_sphere_radius.push_back(2.3482e-8L * 1e-2L); //CH4 in cm -> m //zenith angle Scalar chi(120); //photon flux std::vector<Scalar> lambda_hv,phy1AU; read_hv_flux<Scalar>(lambda_hv,phy1AU,"./input/hv_SSI.dat"); ////cross-section std::vector<Scalar> lambda_N2,sigma_N2; std::vector<Scalar> lambda_CH4, sigma_CH4; read_crossSection<Scalar>("./input/N2_hv_cross-sections.dat",3,lambda_N2,sigma_N2); read_crossSection<Scalar>("./input/CH4_hv_cross-sections.dat",9,lambda_CH4,sigma_CH4); //altitudes Scalar zmin(600.),zmax(1400.),zstep(10.); /************************ * first level ************************/ //altitude Planet::Altitude<Scalar,std::vector<Scalar> > altitude(zmin,zmax,zstep); //neutrals Antioch::ChemicalMixture<Scalar> neutral_species(neutrals); //ions Antioch::ChemicalMixture<Scalar> ionic_species(ions); //chapman Planet::Chapman<Scalar> chapman(chi); //binary diffusion //not needed /************************ * second level ************************/ //temperature std::vector<Scalar> T0,Tz; read_temperature<Scalar>(T0,Tz,"input/temperature.dat"); std::vector<Scalar> neutral_temperature; linear_interpolation(T0,Tz,altitude.altitudes(),neutral_temperature); Planet::AtmosphericTemperature<Scalar, std::vector<Scalar> > temperature(neutral_temperature, neutral_temperature, altitude); //photon opacity Planet::PhotonOpacity<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > tau(altitude,chapman); //reaction sets //not needed /************************ * third level ************************/ //atmospheric mixture Planet::AtmosphericMixture<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > composition(neutral_species, ionic_species, altitude, temperature); composition.init_composition(molar_frac,dens_tot); composition.set_hard_sphere_radius(hard_sphere_radius); composition.initialize(); //kinetics evaluators //not needed /************************ * fourth level ************************/ //photon evaluator Planet::PhotonEvaluator<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > photon(altitude,tau,composition); photon.add_cross_section(lambda_N2, sigma_N2, Antioch::Species::N2); photon.add_cross_section(lambda_CH4, sigma_CH4, Antioch::Species::CH4); photon.set_photon_flux_at_top(lambda_hv, phy1AU, Planet::Constants::Saturn::d_Sun<Scalar>()); photon.update_photon_flux(); //molecular diffusion //not needed //eddy diffusion //not needed /************************ * checks ************************/ molar_frac.pop_back();//get the ion outta here std::vector<std::vector<Scalar> > densities; std::vector<Scalar> mm; mm.push_back(MN2); mm.push_back(MCH4); calculate_densities(densities,dens_tot,molar_frac,zmin,zmax,zstep,neutral_temperature,mm); for(Scalar z = zmax-zstep; z >= zmin; z -= zstep) { unsigned int iz = altitude.altitudes_map().at(z); unsigned int jz = altitude.altitudes_map().at(z+zstep); for(unsigned int s = 0; s < densities.size(); s++) { densities[s][iz] += densities[s][jz]; } } std::vector<std::vector<Scalar> > opacity; std::vector<std::vector<Scalar>*> cs; cs.push_back(&lambda_N2); cs.push_back(&sigma_N2); cs.push_back(&lambda_CH4); cs.push_back(&sigma_CH4); calculate_tau(opacity,chapman,cs,lambda_hv, densities,molar_frac,mm, neutral_temperature, zmin,zmax,zstep); std::vector<std::vector<Scalar> > phy_theo; phy_theo.resize(altitude.altitudes().size()); for(unsigned int iz = 0; iz < altitude.altitudes().size(); iz++) { phy_theo[iz].resize(lambda_hv.size()); for(unsigned int il = 0; il < lambda_hv.size(); il++) { phy_theo[iz][il] = phy1AU[il] / (Planet::Constants::Saturn::d_Sun<Scalar>() * Planet::Constants::Saturn::d_Sun<Scalar>()) * Antioch::ant_exp(-opacity[iz][il]); } } int return_flag(0); for(unsigned int iz = 0; iz < altitude.altitudes().size(); iz++) { for(unsigned int il = 0; il < lambda_hv.size(); il++) { return_flag = return_flag || check_test(phy_theo[iz][il], photon.photon_flux()[iz].flux()[il], "phy at altitude and wavelength"); if(return_flag) { std::cout << altitude.altitudes()[iz] << " " << lambda_hv[il] << std::endl; return return_flag; } } } return return_flag; } int main() { return (tester<float>() || tester<double>() || tester<long double>()); } <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/angle_surface_manager.h" #include <iostream> #include <vector> #ifdef WINUWP #include <third_party/cppwinrt/generated/winrt/Windows.UI.Composition.h> #include <windows.ui.core.h> #endif #if defined(WINUWP) && defined(USECOREWINDOW) #include <winrt/Windows.UI.Core.h> #endif // Logs an EGL error to stderr. This automatically calls eglGetError() // and logs the error code. static void LogEglError(std::string message) { EGLint error = eglGetError(); std::cerr << "EGL: " << message << std::endl; std::cerr << "EGL: eglGetError returned " << error << std::endl; } namespace flutter { int AngleSurfaceManager::instance_count_ = 0; std::unique_ptr<AngleSurfaceManager> AngleSurfaceManager::Create() { std::unique_ptr<AngleSurfaceManager> manager; manager.reset(new AngleSurfaceManager()); if (!manager->initialize_succeeded_) { return nullptr; } return std::move(manager); } AngleSurfaceManager::AngleSurfaceManager() : egl_config_(nullptr), egl_display_(EGL_NO_DISPLAY), egl_context_(EGL_NO_CONTEXT) { initialize_succeeded_ = Initialize(); ++instance_count_; } AngleSurfaceManager::~AngleSurfaceManager() { CleanUp(); --instance_count_; } bool AngleSurfaceManager::InitializeEGL( PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT, const EGLint* config, bool should_log) { egl_display_ = egl_get_platform_display_EXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, config); if (egl_display_ == EGL_NO_DISPLAY) { if (should_log) { LogEglError("Failed to get a compatible EGLdisplay"); } return false; } if (eglInitialize(egl_display_, nullptr, nullptr) == EGL_FALSE) { if (should_log) { LogEglError("Failed to initialize EGL via ANGLE"); } return false; } return true; } bool AngleSurfaceManager::Initialize() { const EGLint config_attributes[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_NONE}; const EGLint display_context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; // These are preferred display attributes and request ANGLE's D3D11 // renderer. eglInitialize will only succeed with these attributes if the // hardware supports D3D11 Feature Level 10_0+. const EGLint d3d11_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will // enable ANGLE to automatically call the IDXGIDevice3::Trim method on // behalf of the application when it gets suspended. EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These are used to request ANGLE's D3D11 renderer, with D3D11 Feature // Level 9_3. const EGLint d3d11_fl_9_3_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These attributes request D3D11 WARP (software rendering fallback) in case // hardware-backed D3D11 is unavailable. const EGLint d3d11_warp_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These are used to request ANGLE's D3D9 renderer as a fallback if D3D11 // is not available. const EGLint d3d9_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE, EGL_TRUE, EGL_NONE, }; std::vector<const EGLint*> display_attributes_configs = { d3d11_display_attributes, d3d11_fl_9_3_display_attributes, d3d11_warp_display_attributes, d3d9_display_attributes, }; PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>( eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!egl_get_platform_display_EXT) { LogEglError("eglGetPlatformDisplayEXT not available"); return false; } // Attempt to initialize ANGLE's renderer in order of: D3D11, D3D11 Feature // Level 9_3, D3D11 WARP and finally D3D9. for (auto config : display_attributes_configs) { bool should_log = (config == display_attributes_configs.back()); if (InitializeEGL(egl_get_platform_display_EXT, config, should_log)) { break; } } EGLint numConfigs = 0; if ((eglChooseConfig(egl_display_, config_attributes, &egl_config_, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0)) { LogEglError("Failed to choose first context"); return false; } egl_context_ = eglCreateContext(egl_display_, egl_config_, EGL_NO_CONTEXT, display_context_attributes); if (egl_context_ == EGL_NO_CONTEXT) { LogEglError("Failed to create EGL context"); return false; } egl_resource_context_ = eglCreateContext( egl_display_, egl_config_, egl_context_, display_context_attributes); if (egl_resource_context_ == EGL_NO_CONTEXT) { LogEglError("Failed to create EGL resource context"); return false; } return true; } void AngleSurfaceManager::CleanUp() { EGLBoolean result = EGL_FALSE; if (egl_display_ != EGL_NO_DISPLAY && egl_context_ != EGL_NO_CONTEXT) { result = eglDestroyContext(egl_display_, egl_context_); egl_context_ = EGL_NO_CONTEXT; if (result == EGL_FALSE) { LogEglError("Failed to destroy context"); } } if (egl_display_ != EGL_NO_DISPLAY && egl_resource_context_ != EGL_NO_CONTEXT) { result = eglDestroyContext(egl_display_, egl_resource_context_); egl_resource_context_ = EGL_NO_CONTEXT; if (result == EGL_FALSE) { LogEglError("Failed to destroy resource context"); } } if (egl_display_ != EGL_NO_DISPLAY) { // Display is reused between instances so only terminate display // if destroying last instance if (instance_count_ == 1) { eglTerminate(egl_display_); } egl_display_ = EGL_NO_DISPLAY; } } bool AngleSurfaceManager::CreateSurface(WindowsRenderTarget* render_target, EGLint width, EGLint height) { if (!render_target || !initialize_succeeded_) { return false; } EGLSurface surface = EGL_NO_SURFACE; #ifdef WINUWP const EGLint surfaceAttributes[] = {EGL_NONE}; #else const EGLint surfaceAttributes[] = { EGL_FIXED_SIZE_ANGLE, EGL_TRUE, EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE}; #endif #ifdef WINUWP #ifdef USECOREWINDOW auto target = std::get<winrt::Windows::UI::Core::CoreWindow>(*render_target); #else auto target = std::get<winrt::Windows::UI::Composition::SpriteVisual>(*render_target); #endif surface = eglCreateWindowSurface( egl_display_, egl_config_, static_cast<EGLNativeWindowType>(winrt::get_abi(target)), surfaceAttributes); #else surface = eglCreateWindowSurface( egl_display_, egl_config_, static_cast<EGLNativeWindowType>(std::get<HWND>(*render_target)), surfaceAttributes); #endif if (surface == EGL_NO_SURFACE) { LogEglError("Surface creation failed."); } surface_width_ = width; surface_height_ = height; render_surface_ = surface; return true; } void AngleSurfaceManager::ResizeSurface(WindowsRenderTarget* render_target, EGLint width, EGLint height) { EGLint existing_width, existing_height; GetSurfaceDimensions(&existing_width, &existing_height); if (width != existing_width || height != existing_height) { surface_width_ = width; surface_height_ = height; // TODO(clarkezone) convert ifdef to use use final implementation of angle // resize API prototyped here // https://github.com/clarkezone/angle/tree/resizeswapchaintest to eliminate // unnecessary surface creation / desctruction by use ResizeSwapchain // https://github.com/flutter/flutter/issues/79427 #ifdef WINUWP // Resize render_surface_. Internaly this calls mSwapChain->ResizeBuffers // avoiding the need to destory and recreate the underlying SwapChain. eglPostSubBufferNV(egl_display_, render_surface_, 1, 1, width, height); #else ClearContext(); DestroySurface(); if (!CreateSurface(render_target, width, height)) { std::cerr << "AngleSurfaceManager::ResizeSurface failed to create surface" << std::endl; } #endif } } void AngleSurfaceManager::GetSurfaceDimensions(EGLint* width, EGLint* height) { if (render_surface_ == EGL_NO_SURFACE || !initialize_succeeded_) { *width = 0; *height = 0; return; } // Can't use eglQuerySurface here; Because we're not using // EGL_FIXED_SIZE_ANGLE flag anymore, Angle may resize the surface before // Flutter asks it to, which breaks resize redraw synchronization *width = surface_width_; *height = surface_height_; } void AngleSurfaceManager::DestroySurface() { if (egl_display_ != EGL_NO_DISPLAY && render_surface_ != EGL_NO_SURFACE) { eglDestroySurface(egl_display_, render_surface_); } render_surface_ = EGL_NO_SURFACE; } bool AngleSurfaceManager::MakeCurrent() { return (eglMakeCurrent(egl_display_, render_surface_, render_surface_, egl_context_) == EGL_TRUE); } bool AngleSurfaceManager::ClearContext() { return (eglMakeCurrent(egl_display_, nullptr, nullptr, egl_context_) == EGL_TRUE); } bool AngleSurfaceManager::MakeResourceCurrent() { return (eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_resource_context_) == EGL_TRUE); } EGLBoolean AngleSurfaceManager::SwapBuffers() { return (eglSwapBuffers(egl_display_, render_surface_)); } } // namespace flutter <commit_msg>Remove D3D9 fallback path (#29533)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/angle_surface_manager.h" #include <iostream> #include <vector> #ifdef WINUWP #include <third_party/cppwinrt/generated/winrt/Windows.UI.Composition.h> #include <windows.ui.core.h> #endif #if defined(WINUWP) && defined(USECOREWINDOW) #include <winrt/Windows.UI.Core.h> #endif // Logs an EGL error to stderr. This automatically calls eglGetError() // and logs the error code. static void LogEglError(std::string message) { EGLint error = eglGetError(); std::cerr << "EGL: " << message << std::endl; std::cerr << "EGL: eglGetError returned " << error << std::endl; } namespace flutter { int AngleSurfaceManager::instance_count_ = 0; std::unique_ptr<AngleSurfaceManager> AngleSurfaceManager::Create() { std::unique_ptr<AngleSurfaceManager> manager; manager.reset(new AngleSurfaceManager()); if (!manager->initialize_succeeded_) { return nullptr; } return std::move(manager); } AngleSurfaceManager::AngleSurfaceManager() : egl_config_(nullptr), egl_display_(EGL_NO_DISPLAY), egl_context_(EGL_NO_CONTEXT) { initialize_succeeded_ = Initialize(); ++instance_count_; } AngleSurfaceManager::~AngleSurfaceManager() { CleanUp(); --instance_count_; } bool AngleSurfaceManager::InitializeEGL( PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT, const EGLint* config, bool should_log) { egl_display_ = egl_get_platform_display_EXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, config); if (egl_display_ == EGL_NO_DISPLAY) { if (should_log) { LogEglError("Failed to get a compatible EGLdisplay"); } return false; } if (eglInitialize(egl_display_, nullptr, nullptr) == EGL_FALSE) { if (should_log) { LogEglError("Failed to initialize EGL via ANGLE"); } return false; } return true; } bool AngleSurfaceManager::Initialize() { const EGLint config_attributes[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_NONE}; const EGLint display_context_attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; // These are preferred display attributes and request ANGLE's D3D11 // renderer. eglInitialize will only succeed with these attributes if the // hardware supports D3D11 Feature Level 10_0+. const EGLint d3d11_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that will // enable ANGLE to automatically call the IDXGIDevice3::Trim method on // behalf of the application when it gets suspended. EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These are used to request ANGLE's D3D11 renderer, with D3D11 Feature // Level 9_3. const EGLint d3d11_fl_9_3_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; // These attributes request D3D11 WARP (software rendering fallback) in case // hardware-backed D3D11 is unavailable. const EGLint d3d11_warp_display_attributes[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE, EGL_NONE, }; std::vector<const EGLint*> display_attributes_configs = { d3d11_display_attributes, d3d11_fl_9_3_display_attributes, d3d11_warp_display_attributes, }; PFNEGLGETPLATFORMDISPLAYEXTPROC egl_get_platform_display_EXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>( eglGetProcAddress("eglGetPlatformDisplayEXT")); if (!egl_get_platform_display_EXT) { LogEglError("eglGetPlatformDisplayEXT not available"); return false; } // Attempt to initialize ANGLE's renderer in order of: D3D11, D3D11 Feature // Level 9_3 and finally D3D11 WARP. for (auto config : display_attributes_configs) { bool should_log = (config == display_attributes_configs.back()); if (InitializeEGL(egl_get_platform_display_EXT, config, should_log)) { break; } } EGLint numConfigs = 0; if ((eglChooseConfig(egl_display_, config_attributes, &egl_config_, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0)) { LogEglError("Failed to choose first context"); return false; } egl_context_ = eglCreateContext(egl_display_, egl_config_, EGL_NO_CONTEXT, display_context_attributes); if (egl_context_ == EGL_NO_CONTEXT) { LogEglError("Failed to create EGL context"); return false; } egl_resource_context_ = eglCreateContext( egl_display_, egl_config_, egl_context_, display_context_attributes); if (egl_resource_context_ == EGL_NO_CONTEXT) { LogEglError("Failed to create EGL resource context"); return false; } return true; } void AngleSurfaceManager::CleanUp() { EGLBoolean result = EGL_FALSE; if (egl_display_ != EGL_NO_DISPLAY && egl_context_ != EGL_NO_CONTEXT) { result = eglDestroyContext(egl_display_, egl_context_); egl_context_ = EGL_NO_CONTEXT; if (result == EGL_FALSE) { LogEglError("Failed to destroy context"); } } if (egl_display_ != EGL_NO_DISPLAY && egl_resource_context_ != EGL_NO_CONTEXT) { result = eglDestroyContext(egl_display_, egl_resource_context_); egl_resource_context_ = EGL_NO_CONTEXT; if (result == EGL_FALSE) { LogEglError("Failed to destroy resource context"); } } if (egl_display_ != EGL_NO_DISPLAY) { // Display is reused between instances so only terminate display // if destroying last instance if (instance_count_ == 1) { eglTerminate(egl_display_); } egl_display_ = EGL_NO_DISPLAY; } } bool AngleSurfaceManager::CreateSurface(WindowsRenderTarget* render_target, EGLint width, EGLint height) { if (!render_target || !initialize_succeeded_) { return false; } EGLSurface surface = EGL_NO_SURFACE; #ifdef WINUWP const EGLint surfaceAttributes[] = {EGL_NONE}; #else const EGLint surfaceAttributes[] = { EGL_FIXED_SIZE_ANGLE, EGL_TRUE, EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE}; #endif #ifdef WINUWP #ifdef USECOREWINDOW auto target = std::get<winrt::Windows::UI::Core::CoreWindow>(*render_target); #else auto target = std::get<winrt::Windows::UI::Composition::SpriteVisual>(*render_target); #endif surface = eglCreateWindowSurface( egl_display_, egl_config_, static_cast<EGLNativeWindowType>(winrt::get_abi(target)), surfaceAttributes); #else surface = eglCreateWindowSurface( egl_display_, egl_config_, static_cast<EGLNativeWindowType>(std::get<HWND>(*render_target)), surfaceAttributes); #endif if (surface == EGL_NO_SURFACE) { LogEglError("Surface creation failed."); } surface_width_ = width; surface_height_ = height; render_surface_ = surface; return true; } void AngleSurfaceManager::ResizeSurface(WindowsRenderTarget* render_target, EGLint width, EGLint height) { EGLint existing_width, existing_height; GetSurfaceDimensions(&existing_width, &existing_height); if (width != existing_width || height != existing_height) { surface_width_ = width; surface_height_ = height; // TODO(clarkezone) convert ifdef to use use final implementation of angle // resize API prototyped here // https://github.com/clarkezone/angle/tree/resizeswapchaintest to eliminate // unnecessary surface creation / desctruction by use ResizeSwapchain // https://github.com/flutter/flutter/issues/79427 #ifdef WINUWP // Resize render_surface_. Internaly this calls mSwapChain->ResizeBuffers // avoiding the need to destory and recreate the underlying SwapChain. eglPostSubBufferNV(egl_display_, render_surface_, 1, 1, width, height); #else ClearContext(); DestroySurface(); if (!CreateSurface(render_target, width, height)) { std::cerr << "AngleSurfaceManager::ResizeSurface failed to create surface" << std::endl; } #endif } } void AngleSurfaceManager::GetSurfaceDimensions(EGLint* width, EGLint* height) { if (render_surface_ == EGL_NO_SURFACE || !initialize_succeeded_) { *width = 0; *height = 0; return; } // Can't use eglQuerySurface here; Because we're not using // EGL_FIXED_SIZE_ANGLE flag anymore, Angle may resize the surface before // Flutter asks it to, which breaks resize redraw synchronization *width = surface_width_; *height = surface_height_; } void AngleSurfaceManager::DestroySurface() { if (egl_display_ != EGL_NO_DISPLAY && render_surface_ != EGL_NO_SURFACE) { eglDestroySurface(egl_display_, render_surface_); } render_surface_ = EGL_NO_SURFACE; } bool AngleSurfaceManager::MakeCurrent() { return (eglMakeCurrent(egl_display_, render_surface_, render_surface_, egl_context_) == EGL_TRUE); } bool AngleSurfaceManager::ClearContext() { return (eglMakeCurrent(egl_display_, nullptr, nullptr, egl_context_) == EGL_TRUE); } bool AngleSurfaceManager::MakeResourceCurrent() { return (eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_resource_context_) == EGL_TRUE); } EGLBoolean AngleSurfaceManager::SwapBuffers() { return (eglSwapBuffers(egl_display_, render_surface_)); } } // namespace flutter <|endoftext|>
<commit_before>#include "enigma-queue.h" #include "hphp/runtime/vm/native-data.h" namespace HPHP { namespace Enigma { PlanInfo::PlanInfo(std::string const & cmd) : command(cmd) { determineParameterType(); } Array PlanInfo::mapParameters(Array const & params) { if (type == ParameterType::Named) { return mapNamedParameters(params); } else { return mapNumberedParameters(params); } } Array PlanInfo::mapNamedParameters(Array const & params) { if (parameterNameMap.size() != params.size()) { throw Exception(std::string("Parameter count mismatch; expected ") + std::to_string(parameterNameMap.size()) + " named parameters, got " + std::to_string(params.size())); } Array mapped; for (unsigned i = 0; i < parameterNameMap.size(); i++) { auto key = String(parameterNameMap[i]); auto value = params->nvGet(key.get()); if (value == nullptr) { throw EnigmaException(std::string("Missing bound parameter: ") + key.c_str()); } mapped.append(*reinterpret_cast<Variant const *>(value)); } return mapped; } Array PlanInfo::mapNumberedParameters(Array const & params) { if (parameterCount != params.size()) { throw Exception(std::string("Parameter count mismatch; expected ") + std::to_string(parameterCount) + " parameters, got " + std::to_string(params.size())); } Array mapped; for (unsigned i = 0; i < parameterCount; i++) { auto value = params->nvGet(i); if (value == nullptr) { throw Exception(std::string("Missing bound parameter: ") + std::to_string(i)); } mapped.append(*reinterpret_cast<Variant const *>(value)); } return mapped; } void PlanInfo::determineParameterType() { auto numbered = parseNumberedParameters(); auto named = parseNamedParameters(); if (std::get<1>(named).size() > 0 && std::get<1>(numbered) > 0) { throw Exception("Query contains both named and numbered parameters"); } if (std::get<1>(named).size() > 0) { type = ParameterType::Named; rewrittenCommand = std::move(std::get<0>(named)); parameterNameMap = std::move(std::get<1>(named)); } else { type = ParameterType::Numbered; rewrittenCommand = std::move(std::get<0>(numbered)); parameterCount = std::get<1>(numbered); } } bool PlanInfo::isValidPlaceholder(std::size_t pos) const { // Check if the preceding byte is in [0-9a-zA-Z \r\n\t] if ( pos != 0 && !isspace(command[pos - 1]) && !isalnum(command[pos - 1]) ) { return false; } // Check if the following byte is in [0-9a-zA-Z: \r\n\t] // Allow ":", as parameter typecasting is fairly common if ( pos < command.length() - 1 && !isspace(command[pos + 1]) && !isalnum(command[pos + 1]) && command[pos + 1] != ':' ) { return false; } return true; } bool PlanInfo::isValidNamedPlaceholder(std::size_t pos) const { // Check if the preceding byte is in [ \r\n\t] if ( pos != 0 && !isspace(command[pos - 1]) ) { return false; } // Check if the following byte is in [0-9a-zA-Z_] if ( pos < command.length() - 1 && !isalnum(command[pos + 1]) && command[pos + 1] != '_' ) { return false; } return true; } std::size_t PlanInfo::namedPlaceholderLength(std::size_t pos) const { if (!isValidNamedPlaceholder(pos)) { return 0; } auto i = pos + 1; for (; i < command.length() && (isalnum(command[i]) || command[i] == '_'); i++); return i - pos - 1; } std::tuple<std::string, unsigned> PlanInfo::parseNumberedParameters() const { unsigned numParams{0}; std::ostringstream rewritten; // Check if the placeholder is valid // (should only be preceded and followed by [0-9a-z] and whitespace) std::size_t pos{0}, lastWrittenPos{0}; for (;;) { pos = command.find('?', pos); if (pos == std::string::npos) { break; } rewritten.write(command.data() + lastWrittenPos, pos - lastWrittenPos); lastWrittenPos = pos + 1; if (isValidPlaceholder(pos++)) { rewritten << '$'; rewritten << (++numParams); } else { rewritten << '?'; } } rewritten.write(command.data() + lastWrittenPos, command.length() - lastWrittenPos); return std::make_tuple(rewritten.str(), numParams); } std::tuple<std::string, std::vector<std::string> > PlanInfo::parseNamedParameters() const { std::vector<std::string> params; std::unordered_map<std::string, unsigned> paramMap; std::ostringstream rewritten; std::size_t pos{0}, lastWrittenPos{0}; for (;;) { pos = command.find(':', pos); if (pos == std::string::npos) { break; } rewritten.write(command.data() + lastWrittenPos, pos - lastWrittenPos); lastWrittenPos = pos + 1; auto placeholderLength = namedPlaceholderLength(pos++); if (placeholderLength > 0) { std::string param = command.substr(pos, placeholderLength); auto paramIt = paramMap.find(param); if (paramIt != paramMap.end()) { rewritten << '$'; rewritten << paramIt->second; } else { params.push_back(param); paramMap.insert(std::make_pair(param, params.size())); rewritten << '$'; rewritten << params.size(); } pos += placeholderLength; lastWrittenPos += placeholderLength; } else { rewritten << ':'; } } rewritten.write(command.data() + lastWrittenPos, command.length() - lastWrittenPos); return std::make_tuple(rewritten.str(), std::move(params)); } PlanCache::CachedPlan::CachedPlan(std::string const & cmd) : planInfo(cmd) {} PlanCache::CachedPlan const * PlanCache::lookupPlan(std::string const & query) const { auto it = plans_.find(query); if (it != plans_.end()) { return it->second.get(); } else { return nullptr; } } PlanCache::CachedPlan const * PlanCache::assignPlan(std::string const & query) { auto name = generatePlanName(); return storePlan(query, name); } PlanCache::CachedPlan const * PlanCache::storePlan(std::string const & query, std::string const & statementName) { auto plan = p_CachedPlan(new CachedPlan(query)); auto planPtr = plan.get(); plan->statementName = statementName; plans_.insert(std::make_pair(query, std::move(plan))); return planPtr; } std::string PlanCache::generatePlanName() { return PlanNamePrefix + std::to_string(nextPlanId_++); } const StaticString s_PoolSize("pool_size"), s_QueueSize("queue_size"); Pool::Pool(Array const & connectionOpts, Array const & poolOpts) { if (poolOpts.exists(s_PoolSize)) { auto size = (unsigned)poolOpts[s_PoolSize].toInt32(); if (size < 1 || size > MaxPoolSize) { throwEnigmaException("Invalid pool size specified"); } poolSize_ = size; } if (poolOpts.exists(s_QueueSize)) { auto size = (unsigned)poolOpts[s_QueueSize].toInt32(); if (size < 1 || size > MaxQueueSize) { throwEnigmaException("Invalid queue size specified"); } maxQueueSize_ = size; } for (unsigned i = 0; i < poolSize_; i++) { addConnection(connectionOpts); } } Pool::~Pool() { } void Pool::addConnection(Array const & options) { auto connection = std::make_shared<Connection>(options); auto connectionId = nextConnectionIndex_++; connectionMap_.insert(std::make_pair(connectionId, connection)); auto planCache = p_PlanCache(new PlanCache()); planCaches_.insert(std::make_pair(connectionId, std::move(planCache))); idleConnections_.push_back(connectionId); } void Pool::removeConnection(unsigned connectionId) { auto prepareIt = preparing_.find(connectionId); if (prepareIt != preparing_.end()) { preparing_.erase(prepareIt); } auto pendingPrepareIt = pendingPrepare_.find(connectionId); if (pendingPrepareIt != pendingPrepare_.end()) { pendingPrepare_.erase(pendingPrepareIt); } planCaches_.erase(connectionId); connectionMap_.erase(connectionId); auto idleIt = std::find(idleConnections_.begin(), idleConnections_.end(), connectionId); if (idleIt != idleConnections_.end()) { idleConnections_.erase(idleIt); } } QueryAwait * Pool::enqueue(p_Query query) { if (queue_.size() >= maxQueueSize_) { // TODO improve error reporting throw Exception("Enigma queue size exceeded"); } Lock lock(mutex_); bool shouldExecute = queue_.empty() && !idleConnections_.empty(); ENIG_DEBUG("Pool::enqueue(): create QueryAwait"); auto event = new QueryAwait(std::move(query)); queue_.push(event); if (shouldExecute) { executeNext(); } return event; } unsigned Pool::assignConnectionId() { always_assert(!idleConnections_.empty()); // todo: random, RR selection auto index = rand() % idleConnections_.size(); unsigned connectionId = idleConnections_[index]; if (index < idleConnections_.size() - 1) { idleConnections_[index] = *idleConnections_.rbegin(); } idleConnections_.pop_back(); return connectionId; } void Pool::executeNext() { ENIG_DEBUG("Pool::executeNext"); always_assert(!queue_.empty()); auto connectionId = assignConnectionId(); auto connection = connectionMap_[connectionId]; auto query = queue_.front(); queue_.pop(); auto const & q = query->query(); /* * Check if the query is a candidate for automatic prepared statement generation * and if planning has already taken place for this query. */ if (q.flags() & Query::kCachePlan && q.type() == Query::Type::Parameterized) { auto plan = planCaches_[connectionId]->lookupPlan(q.command().c_str()); if (plan) { /* * Query was already prepared on this connection, use the * auto assigned statement handle. */ ENIG_DEBUG("Begin executing cached prepared stmt"); std::unique_ptr<Query> execQuery(new Query( Query::PreparedInit{}, plan->statementName, q.params())); query->swapQuery(std::move(execQuery)); } else { /* * Begin preparing the query and store the original query params * for later execution. */ ENIG_DEBUG("Begin preparing"); plan = planCaches_[connectionId]->assignPlan(q.command().c_str()); std::unique_ptr<Query> planQuery(new Query( Query::PrepareInit{}, plan->statementName, plan->planInfo.rewrittenCommand, plan->planInfo.parameterCount)); auto originalQuery = query->swapQuery(std::move(planQuery)); preparing_.insert(std::make_pair(connectionId, query)); pendingPrepare_.insert(std::make_pair(connectionId, std::move(originalQuery))); } } else { ENIG_DEBUG("Begin executing query"); } auto callback = [this, connectionId] { Lock lock(mutex_); this->queryCompleted(connectionId); }; query->assign(connection); query->begin(callback); } void Pool::queryCompleted(unsigned connectionId) { ENIG_DEBUG("Pool::queryCompleted"); idleConnections_.push_back(connectionId); if (!queue_.empty()) { executeNext(); } } const StaticString s_PoolInterface("PoolInterface"), s_PoolInterfaceNS("Enigma\\Pool"), s_QueryInterface("QueryInterface"), s_QueryInterfaceNS("Enigma\\Query"); Object PoolInterface::newInstance(sp_Pool p) { Object instance{Unit::lookupClass(s_PoolInterfaceNS.get())}; Native::data<PoolInterface>(instance) ->init(p); return instance; } PoolInterface::~PoolInterface() { sweep(); } void PoolInterface::init(sp_Pool p) { pool = p; } void PoolInterface::sweep() { pool.reset(); } Object HHVM_METHOD(PoolInterface, query, Object const & queryObj) { auto poolInterface = Native::data<PoolInterface>(this_); auto queryClass = Unit::lookupClass(s_QueryInterfaceNS.get()); if (!queryObj.instanceof(queryClass)) { SystemLib::throwInvalidArgumentExceptionObject( "Pool::query() expects a Query object as its parameter"); } auto queryData = Native::data<QueryInterface>(queryObj); try { PlanInfo planInfo(queryData->command().c_str()); auto bindableParams = planInfo.mapParameters(queryData->params()); auto query = new Query(Query::ParameterizedInit{}, planInfo.rewrittenCommand, bindableParams); query->setFlags(queryData->flags()); auto waitEvent = poolInterface->pool->enqueue(std::unique_ptr<Query>(query)); return Object{waitEvent->getWaitHandle()}; } catch (std::exception & e) { throwEnigmaException(e.what()); } } void QueryInterface::init(String const & command, Array const & params) { command_ = command; params_ = params; } void HHVM_METHOD(QueryInterface, __construct, String const & command, Array const & params) { auto query = Native::data<QueryInterface>(this_); query->init(command, params); } void HHVM_METHOD(QueryInterface, enablePlanCache, bool enabled) { auto query = Native::data<QueryInterface>(this_); auto flags = query->flags(); if (enabled) { query->setFlags(flags | Query::kCachePlan); } else { query->setFlags(flags & ~Query::kCachePlan); } } void HHVM_METHOD(QueryInterface, setBinary, bool enabled) { auto query = Native::data<QueryInterface>(this_); auto flags = query->flags(); if (enabled) { query->setFlags(flags | Query::kBinary); } else { query->setFlags(flags & ~Query::kBinary); } } void registerQueueClasses() { ENIGMA_NAMED_ME(PoolInterface, Pool, query); Native::registerNativeDataInfo<PoolInterface>(s_PoolInterface.get()); ENIGMA_NAMED_ME(QueryInterface, Query, __construct); ENIGMA_NAMED_ME(QueryInterface, Query, enablePlanCache); ENIGMA_NAMED_ME(QueryInterface, Query, setBinary); HHVM_RCC_INT(QueryInterfaceNS, CACHE_PLAN, Query::kCachePlan); HHVM_RCC_INT(QueryInterfaceNS, BINARY, Query::kBinary); Native::registerNativeDataInfo<QueryInterface>(s_QueryInterface.get()); } } }<commit_msg>Improve prepared placeholder detection<commit_after>#include "enigma-queue.h" #include "hphp/runtime/vm/native-data.h" namespace HPHP { namespace Enigma { PlanInfo::PlanInfo(std::string const & cmd) : command(cmd) { determineParameterType(); } Array PlanInfo::mapParameters(Array const & params) { if (type == ParameterType::Named) { return mapNamedParameters(params); } else { return mapNumberedParameters(params); } } Array PlanInfo::mapNamedParameters(Array const & params) { if (parameterNameMap.size() != params.size()) { throw Exception(std::string("Parameter count mismatch; expected ") + std::to_string(parameterNameMap.size()) + " named parameters, got " + std::to_string(params.size())); } Array mapped{Array::Create()}; for (unsigned i = 0; i < parameterNameMap.size(); i++) { auto key = String(parameterNameMap[i]); auto value = params->nvGet(key.get()); if (value == nullptr) { throw EnigmaException(std::string("Missing bound parameter: ") + key.c_str()); } mapped.append(*reinterpret_cast<Variant const *>(value)); } return mapped; } Array PlanInfo::mapNumberedParameters(Array const & params) { if (parameterCount != params.size()) { throw Exception(std::string("Parameter count mismatch; expected ") + std::to_string(parameterCount) + " parameters, got " + std::to_string(params.size())); } Array mapped{Array::Create()}; for (unsigned i = 0; i < parameterCount; i++) { auto value = params->nvGet(i); if (value == nullptr) { throw Exception(std::string("Missing bound parameter: ") + std::to_string(i)); } mapped.append(*reinterpret_cast<Variant const *>(value)); } return mapped; } void PlanInfo::determineParameterType() { auto numbered = parseNumberedParameters(); auto named = parseNamedParameters(); if (std::get<1>(named).size() > 0 && std::get<1>(numbered) > 0) { throw Exception("Query contains both named and numbered parameters"); } if (std::get<1>(named).size() > 0) { type = ParameterType::Named; rewrittenCommand = std::move(std::get<0>(named)); parameterNameMap = std::move(std::get<1>(named)); } else { type = ParameterType::Numbered; rewrittenCommand = std::move(std::get<0>(numbered)); parameterCount = std::get<1>(numbered); } } bool PlanInfo::isValidPlaceholder(std::size_t pos) const { // Check if the preceding byte is in [0-9a-zA-Z (\r\n\t] if ( pos != 0 && !isspace(command[pos - 1]) && !isalnum(command[pos - 1]) && command[pos - 1] != '(' && command[pos - 1] != ']' && command[pos - 1] != ',' ) { return false; } // Check if the following byte is in [0-9a-zA-Z:) \r\n\t] // Allow ":", as parameter typecasting is fairly common if ( pos < command.length() - 1 && !isspace(command[pos + 1]) && !isalnum(command[pos + 1]) && command[pos + 1] != ':' && command[pos + 1] != ')' && command[pos + 1] != ']' && command[pos + 1] != ',' ) { return false; } return true; } bool PlanInfo::isValidNamedPlaceholder(std::size_t pos) const { // Check if the preceding byte is in [ \r\n\t] if ( pos != 0 && !isspace(command[pos - 1]) && command[pos - 1] != '(' && command[pos - 1] != '[' && command[pos - 1] != ',' ) { return false; } // Check if the following byte is in [0-9a-zA-Z_] if ( pos < command.length() - 1 && !isalnum(command[pos + 1]) && command[pos + 1] != '_' ) { return false; } return true; } std::size_t PlanInfo::namedPlaceholderLength(std::size_t pos) const { if (!isValidNamedPlaceholder(pos)) { return 0; } auto i = pos + 1; for (; i < command.length() && (isalnum(command[i]) || command[i] == '_'); i++); return i - pos - 1; } std::tuple<std::string, unsigned> PlanInfo::parseNumberedParameters() const { unsigned numParams{0}; std::ostringstream rewritten; // Check if the placeholder is valid // (should only be preceded and followed by [0-9a-z] and whitespace) std::size_t pos{0}, lastWrittenPos{0}; for (;;) { pos = command.find('?', pos); if (pos == std::string::npos) { break; } rewritten.write(command.data() + lastWrittenPos, pos - lastWrittenPos); lastWrittenPos = pos + 1; if (isValidPlaceholder(pos++)) { rewritten << '$'; rewritten << (++numParams); } else { rewritten << '?'; } } rewritten.write(command.data() + lastWrittenPos, command.length() - lastWrittenPos); return std::make_tuple(rewritten.str(), numParams); } std::tuple<std::string, std::vector<std::string> > PlanInfo::parseNamedParameters() const { std::vector<std::string> params; std::unordered_map<std::string, unsigned> paramMap; std::ostringstream rewritten; std::size_t pos{0}, lastWrittenPos{0}; for (;;) { pos = command.find(':', pos); if (pos == std::string::npos) { break; } rewritten.write(command.data() + lastWrittenPos, pos - lastWrittenPos); lastWrittenPos = pos + 1; auto placeholderLength = namedPlaceholderLength(pos++); if (placeholderLength > 0) { std::string param = command.substr(pos, placeholderLength); auto paramIt = paramMap.find(param); if (paramIt != paramMap.end()) { rewritten << '$'; rewritten << paramIt->second; } else { params.push_back(param); paramMap.insert(std::make_pair(param, params.size())); rewritten << '$'; rewritten << params.size(); } pos += placeholderLength; lastWrittenPos += placeholderLength; } else { rewritten << ':'; } } rewritten.write(command.data() + lastWrittenPos, command.length() - lastWrittenPos); return std::make_tuple(rewritten.str(), std::move(params)); } PlanCache::CachedPlan::CachedPlan(std::string const & cmd) : planInfo(cmd) {} PlanCache::CachedPlan const * PlanCache::lookupPlan(std::string const & query) const { auto it = plans_.find(query); if (it != plans_.end()) { return it->second.get(); } else { return nullptr; } } PlanCache::CachedPlan const * PlanCache::assignPlan(std::string const & query) { auto name = generatePlanName(); return storePlan(query, name); } PlanCache::CachedPlan const * PlanCache::storePlan(std::string const & query, std::string const & statementName) { auto plan = p_CachedPlan(new CachedPlan(query)); auto planPtr = plan.get(); plan->statementName = statementName; plans_.insert(std::make_pair(query, std::move(plan))); return planPtr; } std::string PlanCache::generatePlanName() { return PlanNamePrefix + std::to_string(nextPlanId_++); } const StaticString s_PoolSize("pool_size"), s_QueueSize("queue_size"); Pool::Pool(Array const & connectionOpts, Array const & poolOpts) { if (poolOpts.exists(s_PoolSize)) { auto size = (unsigned)poolOpts[s_PoolSize].toInt32(); if (size < 1 || size > MaxPoolSize) { throwEnigmaException("Invalid pool size specified"); } poolSize_ = size; } if (poolOpts.exists(s_QueueSize)) { auto size = (unsigned)poolOpts[s_QueueSize].toInt32(); if (size < 1 || size > MaxQueueSize) { throwEnigmaException("Invalid queue size specified"); } maxQueueSize_ = size; } for (unsigned i = 0; i < poolSize_; i++) { addConnection(connectionOpts); } } Pool::~Pool() { } void Pool::addConnection(Array const & options) { auto connection = std::make_shared<Connection>(options); auto connectionId = nextConnectionIndex_++; connectionMap_.insert(std::make_pair(connectionId, connection)); auto planCache = p_PlanCache(new PlanCache()); planCaches_.insert(std::make_pair(connectionId, std::move(planCache))); idleConnections_.push_back(connectionId); } void Pool::removeConnection(unsigned connectionId) { auto prepareIt = preparing_.find(connectionId); if (prepareIt != preparing_.end()) { preparing_.erase(prepareIt); } auto pendingPrepareIt = pendingPrepare_.find(connectionId); if (pendingPrepareIt != pendingPrepare_.end()) { pendingPrepare_.erase(pendingPrepareIt); } planCaches_.erase(connectionId); connectionMap_.erase(connectionId); auto idleIt = std::find(idleConnections_.begin(), idleConnections_.end(), connectionId); if (idleIt != idleConnections_.end()) { idleConnections_.erase(idleIt); } } QueryAwait * Pool::enqueue(p_Query query) { if (queue_.size() >= maxQueueSize_) { // TODO improve error reporting throw Exception("Enigma queue size exceeded"); } Lock lock(mutex_); bool shouldExecute = queue_.empty() && !idleConnections_.empty(); ENIG_DEBUG("Pool::enqueue(): create QueryAwait"); auto event = new QueryAwait(std::move(query)); queue_.push(event); if (shouldExecute) { executeNext(); } return event; } unsigned Pool::assignConnectionId() { always_assert(!idleConnections_.empty()); // todo: random, RR selection auto index = rand() % idleConnections_.size(); unsigned connectionId = idleConnections_[index]; if (index < idleConnections_.size() - 1) { idleConnections_[index] = *idleConnections_.rbegin(); } idleConnections_.pop_back(); return connectionId; } void Pool::executeNext() { ENIG_DEBUG("Pool::executeNext"); always_assert(!queue_.empty()); auto connectionId = assignConnectionId(); auto connection = connectionMap_[connectionId]; auto query = queue_.front(); queue_.pop(); auto const & q = query->query(); /* * Check if the query is a candidate for automatic prepared statement generation * and if planning has already taken place for this query. */ if (q.flags() & Query::kCachePlan && q.type() == Query::Type::Parameterized) { auto plan = planCaches_[connectionId]->lookupPlan(q.command().c_str()); if (plan) { /* * Query was already prepared on this connection, use the * auto assigned statement handle. */ ENIG_DEBUG("Begin executing cached prepared stmt"); std::unique_ptr<Query> execQuery(new Query( Query::PreparedInit{}, plan->statementName, q.params())); query->swapQuery(std::move(execQuery)); } else { /* * Begin preparing the query and store the original query params * for later execution. */ ENIG_DEBUG("Begin preparing"); plan = planCaches_[connectionId]->assignPlan(q.command().c_str()); std::unique_ptr<Query> planQuery(new Query( Query::PrepareInit{}, plan->statementName, plan->planInfo.rewrittenCommand, plan->planInfo.parameterCount)); auto originalQuery = query->swapQuery(std::move(planQuery)); preparing_.insert(std::make_pair(connectionId, query)); pendingPrepare_.insert(std::make_pair(connectionId, std::move(originalQuery))); } } else { ENIG_DEBUG("Begin executing query"); } auto callback = [this, connectionId] { Lock lock(mutex_); this->queryCompleted(connectionId); }; query->assign(connection); query->begin(callback); } void Pool::queryCompleted(unsigned connectionId) { ENIG_DEBUG("Pool::queryCompleted"); idleConnections_.push_back(connectionId); if (!queue_.empty()) { executeNext(); } } const StaticString s_PoolInterface("PoolInterface"), s_PoolInterfaceNS("Enigma\\Pool"), s_QueryInterface("QueryInterface"), s_QueryInterfaceNS("Enigma\\Query"); Object PoolInterface::newInstance(sp_Pool p) { Object instance{Unit::lookupClass(s_PoolInterfaceNS.get())}; Native::data<PoolInterface>(instance) ->init(p); return instance; } PoolInterface::~PoolInterface() { sweep(); } void PoolInterface::init(sp_Pool p) { pool = p; } void PoolInterface::sweep() { pool.reset(); } Object HHVM_METHOD(PoolInterface, query, Object const & queryObj) { auto poolInterface = Native::data<PoolInterface>(this_); auto queryClass = Unit::lookupClass(s_QueryInterfaceNS.get()); if (!queryObj.instanceof(queryClass)) { SystemLib::throwInvalidArgumentExceptionObject( "Pool::query() expects a Query object as its parameter"); } auto queryData = Native::data<QueryInterface>(queryObj); try { PlanInfo planInfo(queryData->command().c_str()); auto bindableParams = planInfo.mapParameters(queryData->params()); auto query = new Query(Query::ParameterizedInit{}, planInfo.rewrittenCommand, bindableParams); query->setFlags(queryData->flags()); auto waitEvent = poolInterface->pool->enqueue(std::unique_ptr<Query>(query)); return Object{waitEvent->getWaitHandle()}; } catch (std::exception & e) { throwEnigmaException(e.what()); } } void QueryInterface::init(String const & command, Array const & params) { command_ = command; params_ = params; } void HHVM_METHOD(QueryInterface, __construct, String const & command, Array const & params) { auto query = Native::data<QueryInterface>(this_); query->init(command, params); } void HHVM_METHOD(QueryInterface, enablePlanCache, bool enabled) { auto query = Native::data<QueryInterface>(this_); auto flags = query->flags(); if (enabled) { query->setFlags(flags | Query::kCachePlan); } else { query->setFlags(flags & ~Query::kCachePlan); } } void HHVM_METHOD(QueryInterface, setBinary, bool enabled) { auto query = Native::data<QueryInterface>(this_); auto flags = query->flags(); if (enabled) { query->setFlags(flags | Query::kBinary); } else { query->setFlags(flags & ~Query::kBinary); } } void registerQueueClasses() { ENIGMA_NAMED_ME(PoolInterface, Pool, query); Native::registerNativeDataInfo<PoolInterface>(s_PoolInterface.get()); ENIGMA_NAMED_ME(QueryInterface, Query, __construct); ENIGMA_NAMED_ME(QueryInterface, Query, enablePlanCache); ENIGMA_NAMED_ME(QueryInterface, Query, setBinary); HHVM_RCC_INT(QueryInterfaceNS, CACHE_PLAN, Query::kCachePlan); HHVM_RCC_INT(QueryInterfaceNS, BINARY, Query::kBinary); Native::registerNativeDataInfo<QueryInterface>(s_QueryInterface.get()); } } } <|endoftext|>
<commit_before>#include "PairWiseClusterWriter.h" /** * Constructor * * @param char * m * The method used for similarity: sc, pc, mi * @param char * fp * The string used to prefix all files * @param int i * The job index. This will be added to all files. * @param int n * The number of samples. */ PairWiseClusterWriter::PairWiseClusterWriter(char * method, char * fileprefix, int id, int num_samples) { this->job_index = id; this->num_samples = num_samples; this->recovery_x = 0; this->recovery_y = 0; this->method = (char *) malloc(sizeof(char) * strlen(method) + 1); strcpy(this->method, method); this->fileprefix = (char *) malloc(sizeof(char) * strlen(fileprefix) + 1); strcpy(this->fileprefix, fileprefix); fps = (fstream **) malloc(sizeof(fstream *) * 102); // Open the files, find out what was the last coordinates used, then // set the position in each file to pick up where it left off. this->openOutFiles(); this->findLastPositions(); } /** * Destructor */ PairWiseClusterWriter::~PairWiseClusterWriter() { this->closeOutFiles(); free(fps); free(fileprefix); free(method); } /** * Opens and creates 102 files for storing the clusters with correlation values. * Each file stores a range of 1/100 Spearman correlation values. */ void PairWiseClusterWriter::openOutFiles() { char clusters_dir[50]; char nan_dir[50]; sprintf(clusters_dir, "./clusters-%s", method); sprintf(nan_dir, "%s/nan", clusters_dir); // Make sure the output directory exists. struct stat st = {0}; if (stat(clusters_dir, &st) == -1) { mkdir(clusters_dir, 0700); } // Open up 102 files, one each for 100 Spearman correlation value ranges. // and another for those without (e.g. 'nan'). int i = 0; char filename[1025]; char dirname[1025]; for (i = 0; i <= 100; i++) { sprintf(dirname, "%s/%03d", clusters_dir, i); if (stat(dirname, &st) == -1) { mkdir(dirname, 0700); } sprintf(filename, "%s/%03d/%s.clusters.%03d.%03d.txt", clusters_dir, i, fileprefix, i, job_index); fps[i] = new fstream; // fps[i]->open(filename, ios::out); fps[i]->open(filename, ios::in|ios::out|ios::ate); } if (stat(nan_dir, &st) == -1) { mkdir(nan_dir, 0700); } sprintf(filename, "%s/%s.clusters.nan.%03d.txt", nan_dir, fileprefix, job_index); fps[i] = new fstream; fps[i]->open(filename, ios::in|ios::out|ios::ate); } /** * finds the last complete line written to the file. * * This will contain the last x,y pair-wise coordinates performed within * this file. We can restart from that position. */ void PairWiseClusterWriter::findLastPositions() { // Holds the last x and y values that exist in each file before // the job terminated without completion. int last_x[102]; int last_y[102]; // The position in the file where the last_x and last_y are found. int last_seek[102]; // The maximum buffer size is the the number of samples plus the other // fields (estimate at 100b) * 10 (for 10 lines) unsigned int max_buffer = (num_samples + 100) * 10; for (int i = 0; i < 102; i++) { if (i == 96) { int j = 1; } int done = 0; unsigned int buffer_size = 0; char * buffer; unsigned int file_size = fps[i]->tellg(); // If we have no data in this file then there's nothing to check, just // set the position to 0. if (file_size == 0) { done = 1; last_x[i] = 0; last_y[i] = 0; last_seek[i] = 0; } while(!done) { // If the buffer size is zero then skip. if (buffer_size == 0) { buffer_size++; continue; } // If the buffer size reaches the max then we can't recover. So just quit. if (buffer_size > max_buffer) { done = 1; last_x[i] = 0; last_y[i] = 0; last_seek[i] = 0; } // Seek backwards from the end of the file fps[i]->seekg(file_size - buffer_size); buffer = (char *) malloc(sizeof(char) * buffer_size); fps[i]->getline(buffer, buffer_size); if (buffer_size == 6) { if (strcmp(buffer, "#Done") == 0) { done = 1; // Set last_x and last_y to -1 to indicate the file is completed last_x[i] = -1; last_y[i] = -1; break; } } // Check the line if we have reached a new line (strlen(buffer) == 0) then // process the previous line, or if the file only has one line or we've // reached the beginning process the current line. if (buffer_size > 1 && (strlen(buffer) == 0 || buffer_size == file_size)) { // If we are at the beginning of the file then process this line. if (buffer_size == file_size) { fps[i]->seekg(file_size - buffer_size); } // If we are at the end of the next line then process the previous line. else { fps[i]->seekg(file_size - (buffer_size - 1)); } fps[i]->getline(buffer, buffer_size); // Get the values from this line. int x, y, cluster_num, num_clusters, cluster_samples, num_missing; float cv; char samples[num_samples]; int n = sscanf(buffer, "%d\t%d\t%d\t%d\t%d\t%d\t%f\t%s", &x, &y, &cluster_num, &num_clusters, &cluster_samples, &num_missing, &cv, (char *) &samples); // If the correct number of fields was read from the file and the // correct number of samples is present then this is a good line. We // will store the x and y coordinates for this file as well // as the seek position for this file. if (n == 8 && strlen(samples) == (unsigned int) num_samples) { done = 1; last_x[i] = x; last_y[i] = y; // To calculate the seek position we subtract the line size from // the buffer size but because the buffer size is one larger we // must subtract 1. Add 1 to the buffer length to account for the // missing \n. if (buffer_size == file_size) { last_seek[i] = file_size - (buffer_size - (strlen(buffer) + 1)); } else { last_seek[i] = file_size - ((buffer_size - 1) - (strlen(buffer) + 1)); } } } free(buffer); // Increment the buffer size. buffer_size++; } } // Find the largest completed x and y coordinates. The x-coordinate takes // precedence, or in other words, we only consider larger values of y if // x is also bigger or the same. for (int i = 0 ; i < 102; i++) { if (recovery_x <= last_x[i]) { recovery_x = last_x[i]; if (recovery_y < last_y[i]) { recovery_y = last_y[i]; } } } // Now iterate through the files one more time and move the file pointer // to the proper place. If the last_x and last_y is the same as the // recovery_x and the recovery_y then we want to move the file pointer to // the first occurance of this coordinate (there may be more than one if // there are multiple clusters). for (int i = 0; i < 102; i++) { // If the last x is not the same as the recovery_x then this set the // file pointer to the last good read line. if (last_x[i] < recovery_x) { fps[i]->seekp(last_seek[i]); continue; } // Here the last_x is the same as the recovery_y, but if the last y is // not same as the recover_y then set the file pointer to the last // good read line. if (last_y[i] < recovery_y) { fps[i]->seekp(last_seek[i]); continue; } // If we're here it's because the last_x and last_y are the same as the // recovery_x and recovery_y. We want to backup the file pointer if there // are more than one cluster for these coordinates. This way the // pair-wise comparision can be re-run without having duplicates in the // file. int done = 0; unsigned int buffer_size = 0; char * buffer; unsigned int file_size; // Get the file size. fps[i]->seekg(0, ios_base::end); file_size = fps[i]->tellg(); // Set the file pointer to that of the last good read line. This should // be the recovery_x and recovery_y coordinate result line. buffer_size = file_size - last_seek[i]; // Read the file backwards to look for the proper line. while(!done) { // If the buffer size is zero then skip. if (buffer_size == 0) { buffer_size++; continue; } // Seek backwards from the end of the file fps[i]->seekg(file_size - buffer_size); buffer = (char *) malloc(sizeof(char) * buffer_size); fps[i]->getline(buffer, buffer_size); // Check the line if we have reached a new line (strlen(buffer) == 0) then // process the previous line, or if the file only has one line or we've // reached the beginning process the current line. if (buffer_size > 1 && (strlen(buffer) == 0 || buffer_size == file_size)) { // If we are at the beginning of the file then process this line. if (buffer_size == file_size) { fps[i]->seekg(file_size - buffer_size); } // If we are at the end of the next line then process the previous line. else { fps[i]->seekg(file_size - (buffer_size - 1)); } fps[i]->getline(buffer, buffer_size); // Get the values from this line. int x, y, cluster_num, num_clusters, cluster_samples, num_missing; float cv; char samples[num_samples]; int n = sscanf(buffer, "%d\t%d\t%d\t%d\t%d\t%d\t%f\t%s", &x, &y, &cluster_num, &num_clusters, &cluster_samples, &num_missing, &cv, (char *) &samples); // If the correct number of fields was read from the file and the // correct number of samples is present then this is a good line. If the // x and y coordinates are not the same then we are done and we can // set the file position. if (n == 8 && strlen(samples) == (unsigned int) num_samples) { if (x != recovery_x || y != recovery_y) { done = 1; if (buffer_size == file_size) { last_seek[i] = file_size - (buffer_size - (strlen(buffer) + 1)); } else { last_seek[i] = file_size - ((buffer_size - 1) - (strlen(buffer) + 1)); } } } } free(buffer); // Increment the buffer size. buffer_size++; } fps[i]->seekp(last_seek[i]); } // Add a comment to each file to indicate where we restarted for (int i = 0; i < 102; i++) { (*fps[i]) << "#Restarted" << endl; } } /** * Closes the 102 files that were opened. */ void PairWiseClusterWriter::closeOutFiles() { int i = 0; for (i = 0; i <= 101; i++) { (*fps[i]) << "#Done" << endl; fps[i]->flush(); fps[i]->close(); } free(fps); } /** * Adds a line to the clustering file. * * The clustering file is used by KINC during pair-wise correlation analysis * to restrict which samples are used. The file is tab delimited. * The format of the file is tab delimited with the following columns: * * 1) gene 1 name * 2) gene 2 name * 3) cluster name. A 0 indicates no clustering was performed. * 4) a string of 0 and 1s indicating which samples to include when * performing pair-wise comparisons. * * @param SampleCluster pws */ void PairWiseClusterWriter::writeClusters(PairWiseClusterList *pwcl, int gene1, int gene2) { // The file pointer of the file to write to. fstream *fp; PairWiseCluster * curr = pwcl->head; while (curr != NULL) { // Determine which file to write the output into double score = curr->pwsim->getScore(); if (!curr->pwsim || isnan(score)) { fp = fps[101]; } else { float i1 = score * 100.0; float i2 = fabs(i1); int i3 = (int) i2; fp = fps[i3]; } (*fp) << gene1 + 1 << "\t" << gene2 + 1 << "\t" << curr->index << "\t" << pwcl->num_clusters << "\t" << curr->cluster_size << "\t" << curr->num_missing << "\t"; if (curr->pwsim) { (*fp) << score << "\t"; } else { (*fp) << NAN << "\t"; } for (int i = 0; i < curr->pwset->n_orig; i++) { (*fp) << curr->cluster_samples[i]; } (*fp) << endl; curr = curr->neighbor; fp->flush(); } } <commit_msg>Minor fixes<commit_after>#include "PairWiseClusterWriter.h" /** * Constructor * * @param char * m * The method used for similarity: sc, pc, mi * @param char * fp * The string used to prefix all files * @param int i * The job index. This will be added to all files. * @param int n * The number of samples. */ PairWiseClusterWriter::PairWiseClusterWriter(char * method, char * fileprefix, int id, int num_samples) { this->job_index = id; this->num_samples = num_samples; this->recovery_x = 0; this->recovery_y = 0; this->method = (char *) malloc(sizeof(char) * strlen(method) + 1); strcpy(this->method, method); this->fileprefix = (char *) malloc(sizeof(char) * strlen(fileprefix) + 1); strcpy(this->fileprefix, fileprefix); fps = (fstream **) malloc(sizeof(fstream *) * 102); // Open the files, find out what was the last coordinates used, then // set the position in each file to pick up where it left off. this->openOutFiles(); this->findLastPositions(); } /** * Destructor */ PairWiseClusterWriter::~PairWiseClusterWriter() { this->closeOutFiles(); free(fps); free(fileprefix); free(method); } // TODO: need a function to make sure the result directory is empty or that // the same number of job files are present. /** * Opens and creates 102 files for storing the clusters with correlation values. * Each file stores a range of 1/100 Spearman correlation values. */ void PairWiseClusterWriter::openOutFiles() { char clusters_dir[50]; char nan_dir[50]; sprintf(clusters_dir, "./clusters-%s", method); sprintf(nan_dir, "%s/nan", clusters_dir); // Make sure the output directory exists. struct stat st = {0}; if (stat(clusters_dir, &st) == -1) { mkdir(clusters_dir, 0700); } // Open up 102 files, one each for 100 Spearman/Pearson correlation value // ranges, and another for those without (e.g. 'nan'). int i = 0; char filename[1025]; char dirname[1025]; for (i = 0; i <= 100; i++) { sprintf(dirname, "%s/%03d", clusters_dir, i); if (stat(dirname, &st) == -1) { mkdir(dirname, 0700); } sprintf(filename, "%s/%03d/%s.clusters.%03d.%03d.txt", clusters_dir, i, fileprefix, i, job_index); fps[i] = new fstream; fps[i]->open(filename, ios::in|ios::out|ios::ate); } if (stat(nan_dir, &st) == -1) { mkdir(nan_dir, 0700); } sprintf(filename, "%s/%s.clusters.nan.%03d.txt", nan_dir, fileprefix, job_index); fps[i] = new fstream; fps[i]->open(filename, ios::in|ios::out|ios::ate); } /** * finds the last complete line written to the file. * * This will contain the last x,y pair-wise coordinates performed within * this file. We can restart from that position. */ void PairWiseClusterWriter::findLastPositions() { // Holds the last x and y values that exist in each file before // the job terminated without completion. int last_x[102]; int last_y[102]; // The position in the file where the last_x and last_y are found. int last_seek[102]; // The maximum buffer size is the the number of samples plus the other // fields (estimate at 100b) * 10 (for 10 lines) unsigned int max_buffer = (num_samples + 100) * 10; for (int i = 0; i < 102; i++) { int done = 0; unsigned int buffer_size = 0; char * buffer; unsigned int file_size = fps[i]->tellg(); // If we have no data in this file then there's nothing to check, just // set the position to 0. if (file_size == 0) { done = 1; last_x[i] = 0; last_y[i] = 0; last_seek[i] = 0; } while(!done) { // If the buffer size is zero then skip. if (buffer_size == 0) { buffer_size++; continue; } // If the buffer size reaches the max then we can't recover. So just quit. if (buffer_size > max_buffer) { done = 1; last_x[i] = 0; last_y[i] = 0; last_seek[i] = 0; } // Seek backwards from the end of the file fps[i]->seekg(file_size - buffer_size); buffer = (char *) malloc(sizeof(char) * buffer_size); fps[i]->getline(buffer, buffer_size); if (buffer_size == 6) { if (strcmp(buffer, "#Done") == 0) { done = 1; // Set last_x and last_y to -1 to indicate the file is completed last_x[i] = -1; last_y[i] = -1; break; } } // Check the line if we have reached a new line (strlen(buffer) == 0) then // process the previous line, or if the file only has one line or we've // reached the beginning process the current line. if (buffer_size > 1 && (strlen(buffer) == 0 || buffer_size == file_size)) { // If we are at the beginning of the file then process this line. if (buffer_size == file_size) { fps[i]->seekg(file_size - buffer_size); } // If we are at the end of the next line then process the previous line. else { fps[i]->seekg(file_size - (buffer_size - 1)); } fps[i]->getline(buffer, buffer_size); // Get the values from this line. int x, y, cluster_num, num_clusters, cluster_samples, num_missing; float cv; char samples[num_samples]; int n = sscanf(buffer, "%d\t%d\t%d\t%d\t%d\t%d\t%f\t%s", &x, &y, &cluster_num, &num_clusters, &cluster_samples, &num_missing, &cv, (char *) &samples); // If the correct number of fields was read from the file and the // correct number of samples is present then this is a good line. We // will store the x and y coordinates for this file as well // as the seek position for this file. if (n == 8 && strlen(samples) == (unsigned int) num_samples) { done = 1; last_x[i] = x; last_y[i] = y; // To calculate the seek position we subtract the line size from // the buffer size but because the buffer size is one larger we // must subtract 1. Add 1 to the buffer length to account for the // missing \n. if (buffer_size == file_size) { last_seek[i] = file_size - (buffer_size - (strlen(buffer) + 1)); } else { last_seek[i] = file_size - ((buffer_size - 1) - (strlen(buffer) + 1)); } } } free(buffer); // Increment the buffer size. buffer_size++; } } // Find the largest completed x and y coordinates. The x-coordinate takes // precedence, or in other words, we only consider larger values of y if // x is also bigger or the same. for (int i = 0 ; i < 102; i++) { if (recovery_x <= last_x[i]) { recovery_x = last_x[i]; if (recovery_y < last_y[i]) { recovery_y = last_y[i]; } } } // Now iterate through the files one more time and move the file pointer // to the proper place. If the last_x and last_y is the same as the // recovery_x and the recovery_y then we want to move the file pointer to // the first occurance of this coordinate (there may be more than one if // there are multiple clusters). for (int i = 0; i < 102; i++) { // If the last x is not the same as the recovery_x then this set the // file pointer to the last good read line. if (last_x[i] < recovery_x) { fps[i]->seekp(last_seek[i]); continue; } // Here the last_x is the same as the recovery_y, but if the last y is // not same as the recover_y then set the file pointer to the last // good read line. if (last_y[i] < recovery_y) { fps[i]->seekp(last_seek[i]); continue; } // If we're here it's because the last_x and last_y are the same as the // recovery_x and recovery_y. We want to backup the file pointer if there // are more than one cluster for these coordinates. This way the // pair-wise comparison can be re-run without having duplicates in the // file. int done = 0; unsigned int buffer_size = 0; char * buffer; unsigned int file_size; // Get the file size. fps[i]->seekg(0, ios_base::end); file_size = fps[i]->tellg(); // Set the file pointer to that of the last good read line. This should // be the recovery_x and recovery_y coordinate result line. buffer_size = file_size - last_seek[i]; // Read the file backwards to look for the proper line. while(!done) { // If the buffer size is zero then skip. if (buffer_size == 0) { buffer_size++; continue; } // Seek backwards from the end of the file fps[i]->seekg(file_size - buffer_size); buffer = (char *) malloc(sizeof(char) * buffer_size); fps[i]->getline(buffer, buffer_size); // Check the line if we have reached a new line (strlen(buffer) == 0) then // process the previous line, or if the file only has one line or we've // reached the beginning process the current line. if (buffer_size > 1 && (strlen(buffer) == 0 || buffer_size == file_size)) { // If we are at the beginning of the file then process this line. if (buffer_size == file_size) { fps[i]->seekg(file_size - buffer_size); } // If we are at the end of the next line then process the previous line. else { fps[i]->seekg(file_size - (buffer_size - 1)); } fps[i]->getline(buffer, buffer_size); // Get the values from this line. int x, y, cluster_num, num_clusters, cluster_samples, num_missing; float cv; char samples[num_samples]; int n = sscanf(buffer, "%d\t%d\t%d\t%d\t%d\t%d\t%f\t%s", &x, &y, &cluster_num, &num_clusters, &cluster_samples, &num_missing, &cv, (char *) &samples); // If the correct number of fields was read from the file and the // correct number of samples is present then this is a good line. If the // x and y coordinates are not the same then we are done and we can // set the file position. if (n == 8 && strlen(samples) == (unsigned int) num_samples) { if (x != recovery_x || y != recovery_y) { done = 1; if (buffer_size == file_size) { last_seek[i] = file_size - (buffer_size - (strlen(buffer) + 1)); } else { last_seek[i] = file_size - ((buffer_size - 1) - (strlen(buffer) + 1)); } } } } free(buffer); // Increment the buffer size. buffer_size++; } fps[i]->seekp(last_seek[i]); } // Add a comment to each file to indicate where we restarted for (int i = 0; i < 102; i++) { (*fps[i]) << "#Restarted" << endl; } } /** * Closes the 102 files that were opened. */ void PairWiseClusterWriter::closeOutFiles() { int i = 0; for (i = 0; i <= 101; i++) { (*fps[i]) << "#Done" << endl; fps[i]->flush(); fps[i]->close(); } free(fps); } /** * Adds a line to the clustering file. * * The clustering file is used by KINC during pair-wise correlation analysis * to restrict which samples are used. The file is tab delimited. * The format of the file is tab delimited with the following columns: * * 1) gene 1 name * 2) gene 2 name * 3) cluster name. A 0 indicates no clustering was performed. * 4) a string of 0 and 1s indicating which samples to include when * performing pair-wise comparisons. * * @param SampleCluster pws */ void PairWiseClusterWriter::writeClusters(PairWiseClusterList *pwcl, int gene1, int gene2) { // The file pointer of the file to write to. fstream *fp; PairWiseCluster * curr = pwcl->head; while (curr != NULL) { // Determine which file to write the output into double score = curr->pwsim->getScore(); if (!curr->pwsim || isnan(score)) { fp = fps[101]; } else { float i1 = score * 100.0; float i2 = fabs(i1); int i3 = (int) i2; fp = fps[i3]; } (*fp) << gene1 + 1 << "\t" << gene2 + 1 << "\t" << curr->index << "\t" << pwcl->num_clusters << "\t" << curr->cluster_size << "\t" << curr->num_missing << "\t"; if (curr->pwsim) { (*fp) << score << "\t"; } else { (*fp) << NAN << "\t"; } for (int i = 0; i < curr->pwset->n_orig; i++) { (*fp) << curr->cluster_samples[i]; } (*fp) << endl; curr = curr->neighbor; fp->flush(); } } <|endoftext|>
<commit_before>#include <BALL/VIEW/PLUGIN/modularWidgetPluginHandler.h> #include <BALL/PLUGIN/BALLPlugin.h> #include <BALL/VIEW/PLUGIN/modularWidgetPlugin.h> #include <BALL/VIEW/KERNEL/mainControl.h> namespace BALL { namespace VIEW { ModularWidgetPluginHandler::ModularWidgetPluginHandler(MainControl* parent) { main_control_ = parent; } bool ModularWidgetPluginHandler::canHandle(BALLPlugin* plugin) const { return qobject_cast<ModularWidgetPlugin*>(plugin) != 0; } bool ModularWidgetPluginHandler::specificSetup_(BALLPlugin* plugin) { ModularWidgetPlugin* ptr = qobject_cast<ModularWidgetPlugin*>(plugin); // let the plugin create its widget modular_widget_ = ptr->createModularWidget(main_control_); // and initialize it modular_widget_->initializeWidget(*main_control_); return plugin->activate(); } bool ModularWidgetPluginHandler::specificShutdown_(BALLPlugin* plugin) { ModularWidgetPlugin* ptr = qobject_cast<ModularWidgetPlugin*>(plugin); // finalize the widget modular_widget_->finalizeWidget(*main_control_); return plugin->deactivate(); } } } <commit_msg>ModularWidgetPluginHandler: take care of registration and deletion<commit_after>#include <BALL/VIEW/PLUGIN/modularWidgetPluginHandler.h> #include <BALL/PLUGIN/BALLPlugin.h> #include <BALL/VIEW/PLUGIN/modularWidgetPlugin.h> #include <BALL/VIEW/KERNEL/mainControl.h> namespace BALL { namespace VIEW { ModularWidgetPluginHandler::ModularWidgetPluginHandler(MainControl* parent) { main_control_ = parent; } bool ModularWidgetPluginHandler::canHandle(BALLPlugin* plugin) const { return qobject_cast<ModularWidgetPlugin*>(plugin) != 0; } bool ModularWidgetPluginHandler::specificSetup_(BALLPlugin* plugin) { ModularWidgetPlugin* ptr = qobject_cast<ModularWidgetPlugin*>(plugin); // let the plugin create its widget modular_widget_ = ptr->createModularWidget(main_control_); modular_widget_->registerWidget(modular_widget_); // and initialize it modular_widget_->initializeWidget(*main_control_); return plugin->activate(); } bool ModularWidgetPluginHandler::specificShutdown_(BALLPlugin* plugin) { // finalize the widget modular_widget_->finalizeWidget(*main_control_); delete(modular_widget_); return plugin->deactivate(); } } } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * CompressPNG.cpp * * Created on: Jun 10, 2019 * Author: William F Godoy godoywf@ornl.gov */ #include "CompressPNG.h" #include <cstring> // std::memset extern "C" { #include <png.h> } #include "adios2/helper/adiosFunctions.h" namespace adios2 { namespace core { namespace compress { const std::map<std::string, uint32_t> CompressPNG::m_ColorTypes = { {"PNG_COLOR_TYPE_GRAY", PNG_COLOR_TYPE_GRAY}, {"PNG_COLOR_TYPE_PALETTE", PNG_COLOR_TYPE_PALETTE}, {"PNG_COLOR_TYPE_RGB", PNG_COLOR_TYPE_RGB}, {"PNG_COLOR_TYPE_RGB_ALPHA", PNG_COLOR_TYPE_RGB_ALPHA}, {"PNG_COLOR_TYPE_GRAY_ALPHA", PNG_COLOR_TYPE_GRAY_ALPHA}, {"PNG_COLOR_TYPE_RGBA", PNG_COLOR_TYPE_RGBA}, {"PNG_COLOR_TYPE_GA", PNG_COLOR_TYPE_GA}}; const std::map<std::string, std::set<uint32_t>> CompressPNG::m_BitDepths = { {"PNG_COLOR_TYPE_GRAY", {1, 2, 4, 8, 16}}, {"PNG_COLOR_TYPE_PALETTE", {1, 2, 4, 8}}, {"PNG_COLOR_TYPE_RGB", {8, 16}}, {"PNG_COLOR_TYPE_RGB_ALPHA", {8, 16}}, {"PNG_COLOR_TYPE_GRAY_ALPHA", {8, 16}}, {"PNG_COLOR_TYPE_RGBA", {8, 16}}, {"PNG_COLOR_TYPE_GA", {8, 16}}}; // PUBLIC CompressPNG::CompressPNG(const Params &parameters) : Operator("png", parameters) { } size_t CompressPNG::Compress(const void *dataIn, const Dims &dimensions, const size_t elementSize, DataType /*type*/, void *bufferOut, const Params &parameters, Params &info) { auto lf_Write = [](png_structp png_ptr, png_bytep data, png_size_t length) { DestInfo *pDestInfo = reinterpret_cast<DestInfo *>(png_get_io_ptr(png_ptr)); std::memcpy(pDestInfo->BufferOut + pDestInfo->Offset, data, length); pDestInfo->Offset += length; }; const std::size_t ndims = dimensions.size(); if (ndims != 3 && ndims != 2) { throw std::invalid_argument( "ERROR: image number of dimensions " + std::to_string(ndims) + " is invalid, must be 2 {height,width*bytes_per_pixel} or 3" " {height,width,bytes_per_pixel]} , in call to ADIOS2 PNG " " compression\n"); } // defaults int compressionLevel = 1; int colorType = PNG_COLOR_TYPE_RGBA; int bitDepth = 8; std::string colorTypeStr = "PNG_COLOR_TYPE_RGBA"; for (const auto &itParameter : parameters) { const std::string key = itParameter.first; const std::string value = itParameter.second; if (key == "compression_level") { compressionLevel = static_cast<int>(helper::StringTo<int32_t>( value, "when setting PNG level parameter\n")); if (compressionLevel < 1 || compressionLevel > 9) { throw std::invalid_argument( "ERROR: compression_level must be an " "integer between 1 (less " "compression, less memory) and 9 " "(more compression, more memory) inclusive, in call to " "ADIOS2 PNG Compress\n"); } } else if (key == "color_type") { auto itColorType = m_ColorTypes.find(value); if (itColorType == m_ColorTypes.end()) { throw std::invalid_argument( "ERROR: invalid color_type, see PNG_COLOR_TYPE_* for " "available types, in call to ADIOS2 PNG Compress\n"); } colorTypeStr = itColorType->first; colorType = itColorType->second; } else if (key == "bit_depth") { bitDepth = static_cast<int>(helper::StringTo<int32_t>( value, "when setting PNG bit_depth parameter\n")); } } if (m_BitDepths.at(colorTypeStr).count(static_cast<int32_t>(bitDepth)) == 0) { throw std::invalid_argument( "ERROR: bit_depth " + std::to_string(bitDepth) + " and color_type " + colorTypeStr + " combination is not allowed by libpng, in call to ADIOS2 PNG " "compression\n"); } png_structp pngWrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); png_infop pngInfo = png_create_info_struct(pngWrite); const uint32_t bytesPerPixel = ndims == 3 ? static_cast<uint32_t>(dimensions[2]) : elementSize; const uint32_t width = static_cast<uint32_t>(dimensions[1]); const uint32_t height = static_cast<uint32_t>(dimensions[0]); png_set_IHDR(pngWrite, pngInfo, width, height, bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if (setjmp(png_jmpbuf(pngWrite))) { throw std::invalid_argument( "ERROR: libpng detected an error in ADIOS2 PNG Compress\n"); } png_set_compression_level(pngWrite, compressionLevel); // set the rows std::vector<uint8_t *> rows(height); for (size_t r = 0; r < height; ++r) { rows[r] = reinterpret_cast<uint8_t *>(const_cast<void *>(dataIn)) + r * width * bytesPerPixel; } png_set_rows(pngWrite, pngInfo, rows.data()); DestInfo destInfo; destInfo.BufferOut = reinterpret_cast<char *>(bufferOut); destInfo.Offset = 0; png_set_write_fn(pngWrite, &destInfo, lf_Write, nullptr); png_write_png(pngWrite, pngInfo, PNG_TRANSFORM_IDENTITY, nullptr); png_write_end(pngWrite, pngInfo); // const size_t compressedSize = png_get_compression_buffer_size(pngWrite); png_destroy_write_struct(&pngWrite, &pngInfo); return destInfo.Offset; } size_t CompressPNG::Decompress(const void *bufferIn, const size_t sizeIn, void *dataOut, const DataType type, const Dims &blockStart, const Dims &blockCount, const Params &parameters, Params &info) { png_image image; std::memset(&image, 0, sizeof(image)); image.version = PNG_IMAGE_VERSION; int result = png_image_begin_read_from_memory(&image, bufferIn, sizeIn); if (result == 0) { throw std::runtime_error( "ERROR: png_image_begin_read_from_memory failed in call " "to ADIOS2 PNG Decompress\n"); } // TODO might be needed from parameters? result = png_image_finish_read(&image, nullptr, dataOut, 0, nullptr); if (result == 0) { throw std::runtime_error( "ERROR: png_image_finish_read_from_memory failed in call " "to ADIOS2 PNG Decompress\n"); } return sizeOut; } bool CompressPNG::IsDataTypeValid(const DataType type) const { return true; } void CompressPNG::CheckStatus(const int status, const std::string hint) const {} } // end namespace compress } // end namespace core } // end namespace adios2 <commit_msg>fix more errors<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * CompressPNG.cpp * * Created on: Jun 10, 2019 * Author: William F Godoy godoywf@ornl.gov */ #include "CompressPNG.h" #include <cstring> // std::memset extern "C" { #include <png.h> } #include "adios2/helper/adiosFunctions.h" namespace adios2 { namespace core { namespace compress { const std::map<std::string, uint32_t> CompressPNG::m_ColorTypes = { {"PNG_COLOR_TYPE_GRAY", PNG_COLOR_TYPE_GRAY}, {"PNG_COLOR_TYPE_PALETTE", PNG_COLOR_TYPE_PALETTE}, {"PNG_COLOR_TYPE_RGB", PNG_COLOR_TYPE_RGB}, {"PNG_COLOR_TYPE_RGB_ALPHA", PNG_COLOR_TYPE_RGB_ALPHA}, {"PNG_COLOR_TYPE_GRAY_ALPHA", PNG_COLOR_TYPE_GRAY_ALPHA}, {"PNG_COLOR_TYPE_RGBA", PNG_COLOR_TYPE_RGBA}, {"PNG_COLOR_TYPE_GA", PNG_COLOR_TYPE_GA}}; const std::map<std::string, std::set<uint32_t>> CompressPNG::m_BitDepths = { {"PNG_COLOR_TYPE_GRAY", {1, 2, 4, 8, 16}}, {"PNG_COLOR_TYPE_PALETTE", {1, 2, 4, 8}}, {"PNG_COLOR_TYPE_RGB", {8, 16}}, {"PNG_COLOR_TYPE_RGB_ALPHA", {8, 16}}, {"PNG_COLOR_TYPE_GRAY_ALPHA", {8, 16}}, {"PNG_COLOR_TYPE_RGBA", {8, 16}}, {"PNG_COLOR_TYPE_GA", {8, 16}}}; // PUBLIC CompressPNG::CompressPNG(const Params &parameters) : Operator("png", parameters) { } size_t CompressPNG::Compress(const void *dataIn, const Dims &dimensions, const size_t elementSize, DataType /*type*/, void *bufferOut, const Params &parameters, Params &info) { auto lf_Write = [](png_structp png_ptr, png_bytep data, png_size_t length) { DestInfo *pDestInfo = reinterpret_cast<DestInfo *>(png_get_io_ptr(png_ptr)); std::memcpy(pDestInfo->BufferOut + pDestInfo->Offset, data, length); pDestInfo->Offset += length; }; const std::size_t ndims = dimensions.size(); if (ndims != 3 && ndims != 2) { throw std::invalid_argument( "ERROR: image number of dimensions " + std::to_string(ndims) + " is invalid, must be 2 {height,width*bytes_per_pixel} or 3" " {height,width,bytes_per_pixel]} , in call to ADIOS2 PNG " " compression\n"); } // defaults int compressionLevel = 1; int colorType = PNG_COLOR_TYPE_RGBA; int bitDepth = 8; std::string colorTypeStr = "PNG_COLOR_TYPE_RGBA"; for (const auto &itParameter : parameters) { const std::string key = itParameter.first; const std::string value = itParameter.second; if (key == "compression_level") { compressionLevel = static_cast<int>(helper::StringTo<int32_t>( value, "when setting PNG level parameter\n")); if (compressionLevel < 1 || compressionLevel > 9) { throw std::invalid_argument( "ERROR: compression_level must be an " "integer between 1 (less " "compression, less memory) and 9 " "(more compression, more memory) inclusive, in call to " "ADIOS2 PNG Compress\n"); } } else if (key == "color_type") { auto itColorType = m_ColorTypes.find(value); if (itColorType == m_ColorTypes.end()) { throw std::invalid_argument( "ERROR: invalid color_type, see PNG_COLOR_TYPE_* for " "available types, in call to ADIOS2 PNG Compress\n"); } colorTypeStr = itColorType->first; colorType = itColorType->second; } else if (key == "bit_depth") { bitDepth = static_cast<int>(helper::StringTo<int32_t>( value, "when setting PNG bit_depth parameter\n")); } } if (m_BitDepths.at(colorTypeStr).count(static_cast<int32_t>(bitDepth)) == 0) { throw std::invalid_argument( "ERROR: bit_depth " + std::to_string(bitDepth) + " and color_type " + colorTypeStr + " combination is not allowed by libpng, in call to ADIOS2 PNG " "compression\n"); } png_structp pngWrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); png_infop pngInfo = png_create_info_struct(pngWrite); const uint32_t bytesPerPixel = ndims == 3 ? static_cast<uint32_t>(dimensions[2]) : elementSize; const uint32_t width = static_cast<uint32_t>(dimensions[1]); const uint32_t height = static_cast<uint32_t>(dimensions[0]); png_set_IHDR(pngWrite, pngInfo, width, height, bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if (setjmp(png_jmpbuf(pngWrite))) { throw std::invalid_argument( "ERROR: libpng detected an error in ADIOS2 PNG Compress\n"); } png_set_compression_level(pngWrite, compressionLevel); // set the rows std::vector<uint8_t *> rows(height); for (size_t r = 0; r < height; ++r) { rows[r] = reinterpret_cast<uint8_t *>(const_cast<void *>(dataIn)) + r * width * bytesPerPixel; } png_set_rows(pngWrite, pngInfo, rows.data()); DestInfo destInfo; destInfo.BufferOut = reinterpret_cast<char *>(bufferOut); destInfo.Offset = 0; png_set_write_fn(pngWrite, &destInfo, lf_Write, nullptr); png_write_png(pngWrite, pngInfo, PNG_TRANSFORM_IDENTITY, nullptr); png_write_end(pngWrite, pngInfo); // const size_t compressedSize = png_get_compression_buffer_size(pngWrite); png_destroy_write_struct(&pngWrite, &pngInfo); return destInfo.Offset; } size_t CompressPNG::Decompress(const void *bufferIn, const size_t sizeIn, void *dataOut, const DataType type, const Dims &blockStart, const Dims &blockCount, const Params &parameters, Params &info) { const size_t sizeOut = std::accumulate(blockCount.begin(), blockCount.end(), helper::GetDataTypeSize(type), std::multiplies<size_t>()); png_image image; std::memset(&image, 0, sizeof(image)); image.version = PNG_IMAGE_VERSION; int result = png_image_begin_read_from_memory(&image, bufferIn, sizeIn); if (result == 0) { throw std::runtime_error( "ERROR: png_image_begin_read_from_memory failed in call " "to ADIOS2 PNG Decompress\n"); } // TODO might be needed from parameters? result = png_image_finish_read(&image, nullptr, dataOut, 0, nullptr); if (result == 0) { throw std::runtime_error( "ERROR: png_image_finish_read_from_memory failed in call " "to ADIOS2 PNG Decompress\n"); } return sizeOut; } bool CompressPNG::IsDataTypeValid(const DataType type) const { return true; } void CompressPNG::CheckStatus(const int status, const std::string hint) const {} } // end namespace compress } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>// =================================================================== // // Copyright (C) 2016 Kimura Ryo // // // // This Source Code Form is subject to the terms of the Mozilla Public // // License, v. 2.0. If a copy of the MPL was not distributed with this // // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // =================================================================== // #include <libbsdf/Brdf/SpecularCoordinatesRandomSampleSet.h> using namespace lb; void SpecularCoordinatesRandomSampleSet::setupBrdf(SpecularCoordinatesBrdf* brdf, float weight0, float weight1, float weight2, float weight3) { for (int inThIndex = 0; inThIndex < brdf->getNumInTheta(); ++inThIndex) { for (int inPhIndex = 0; inPhIndex < brdf->getNumInPhi(); ++inPhIndex) { for (int spThIndex = 0; spThIndex < brdf->getNumSpecTheta(); ++spThIndex) { RandomSampleSet::AngleList angles; SampleMap::iterator it; float w3; #pragma omp parallel for private(angles, it, w3) for (int spPhIndex = 0; spPhIndex < brdf->getNumSpecPhi(); ++spPhIndex) { angles.resize(4); angles.at(0) = brdf->getInTheta(inThIndex); angles.at(1) = brdf->getInPhi(inPhIndex); angles.at(2) = brdf->getSpecTheta(spThIndex); angles.at(3) = brdf->getSpecPhi(spPhIndex); it = sampleMap_.find(angles); if (it != sampleMap_.end()) { brdf->setSpectrum(inThIndex, inPhIndex, spThIndex, spPhIndex, it->second); } else { // Modify a weight coefficient. w3 = weight3 * hermiteInterpolation3(1.0f, 1.0f / weight3, brdf->getSpecTheta(spThIndex) / PI_2_F); Spectrum sp = estimateSpectrum<SpecularCoordinateSystem>(angles, weight0, weight1, weight2, w3); brdf->setSpectrum(inThIndex, inPhIndex, spThIndex, spPhIndex, sp); } } }}} brdf->getSampleSet()->updateAngleAttributes(); } <commit_msg>Fixed the bug of a variable for OpenMP<commit_after>// =================================================================== // // Copyright (C) 2016-2017 Kimura Ryo // // // // This Source Code Form is subject to the terms of the Mozilla Public // // License, v. 2.0. If a copy of the MPL was not distributed with this // // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // =================================================================== // #include <libbsdf/Brdf/SpecularCoordinatesRandomSampleSet.h> using namespace lb; void SpecularCoordinatesRandomSampleSet::setupBrdf(SpecularCoordinatesBrdf* brdf, float weight0, float weight1, float weight2, float weight3) { for (int inThIndex = 0; inThIndex < brdf->getNumInTheta(); ++inThIndex) { for (int inPhIndex = 0; inPhIndex < brdf->getNumInPhi(); ++inPhIndex) { for (int spThIndex = 0; spThIndex < brdf->getNumSpecTheta(); ++spThIndex) { RandomSampleSet::AngleList angles; SampleMap::iterator it; float w3; Spectrum sp; #pragma omp parallel for private(angles, it, w3, sp) for (int spPhIndex = 0; spPhIndex < brdf->getNumSpecPhi(); ++spPhIndex) { angles.resize(4); angles.at(0) = brdf->getInTheta(inThIndex); angles.at(1) = brdf->getInPhi(inPhIndex); angles.at(2) = brdf->getSpecTheta(spThIndex); angles.at(3) = brdf->getSpecPhi(spPhIndex); it = sampleMap_.find(angles); if (it != sampleMap_.end()) { brdf->setSpectrum(inThIndex, inPhIndex, spThIndex, spPhIndex, it->second); } else { // Modify a weight coefficient. w3 = weight3 * hermiteInterpolation3(1.0f, 1.0f / weight3, brdf->getSpecTheta(spThIndex) / PI_2_F); sp = estimateSpectrum<SpecularCoordinateSystem>(angles, weight0, weight1, weight2, w3); brdf->setSpectrum(inThIndex, inPhIndex, spThIndex, spPhIndex, sp); } } }}} brdf->getSampleSet()->updateAngleAttributes(); } <|endoftext|>
<commit_before>/* // $Id$ // Fennel is a library of data storage and processing components. // Copyright (C) 2005-2007 The Eigenbase Project // Copyright (C) 2005-2007 Disruptive Tech // Copyright (C) 2005-2007 LucidEra, Inc. // Portions Copyright (C) 1999-2007 John V. Sichi // // 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 approved by The Eigenbase Project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "fennel/common/CommonPreamble.h" #include "fennel/device/FileDevice.h" #include "fennel/device/RandomAccessRequest.h" #include "fennel/common/SysCallExcn.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <sstream> #ifdef __MINGW32__ #include <windows.h> #endif FENNEL_BEGIN_CPPFILE("$Id$"); FileDevice::FileDevice( std::string filenameInit,DeviceMode openMode,FileSize initialSize) { filename = filenameInit; mode = openMode; #ifdef __MINGW32__ DWORD fdwCreate = mode.create ? CREATE_ALWAYS : OPEN_EXISTING; DWORD fdwFlags = FILE_FLAG_OVERLAPPED; DWORD fdwAccess = GENERIC_READ; if (!mode.readOnly) { fdwAccess |= GENERIC_WRITE; } if (mode.direct) { fdwFlags |= FILE_FLAG_NO_BUFFERING; } if (mode.sequential) { fdwFlags |= FILE_FLAG_SEQUENTIAL_SCAN; } else { fdwFlags |= FILE_FLAG_RANDOM_ACCESS; } if (mode.temporary) { fdwFlags |= FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE; } else { fdwFlags |= FILE_ATTRIBUTE_NORMAL; } // REVIEW: I used FILE_SHARE_ so that recovery tests could reopen a // log file for read while it was still open for write by the original // txn. Should probably fix the tests instead, in case allowing sharing // could hinder performance. handle = reinterpret_cast<int>( CreateFile( filename.c_str(), fdwAccess, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, fdwCreate, fdwFlags, NULL)); if (!isOpen()) { std::ostringstream oss; oss << "Failed to open file " << filename; throw SysCallExcn(oss.str()); } DWORD cbHigh = 0; DWORD cbLow = GetFileSize(HANDLE(handle),&cbHigh); if (cbLow == INVALID_FILE_SIZE) { std::ostringstream oss; oss << "Failed to get size for file " << filename; throw SysCallExcn(oss.str()); } LARGE_INTEGER cbLarge; cbLarge.LowPart = cbLow; cbLarge.HighPart = cbHigh; cbFile = cbLarge.QuadPart; if (mode.create && initialSize > 0) { setSizeInBytes(initialSize); } #else int access = O_LARGEFILE; int permission = S_IRUSR; if (mode.readOnly) { access |= O_RDONLY; } else { access |= O_RDWR; permission |= S_IWUSR; } if (mode.create) { access |= O_CREAT | O_TRUNC; } if (mode.direct) { access |= O_SYNC; // NOTE: We don't actually set O_DIRECT here, because on Linux // that results in EINVAL errors from pwrite. Instead, // O_DIRECT is set from AioLinuxScheduler, because it is required // for libaio. } handle = ::open(filename.c_str(), access, permission); if (!isOpen()) { std::ostringstream oss; oss << "Failed to open file " << filename; throw SysCallExcn(oss.str()); } if (flock(handle, LOCK_SH|LOCK_NB) < 0) { throw SysCallExcn("File lock failed"); } cbFile = ::lseek(handle,0,SEEK_END); // Preallocate the file if we're creating the file, and an initial size // is specified. if (mode.create && initialSize > 0) { int rc = posix_fallocate(handle, 0, initialSize); if (rc) { throw SysCallExcn("File allocation failed", rc); } cbFile = initialSize; } #endif } FileDevice::~FileDevice() { if (isOpen()) { close(); } } void FileDevice::close() { assert(isOpen()); #ifdef __MINGW32__ CloseHandle(HANDLE(handle)); #else ::close(handle); if (mode.temporary) { ::unlink(filename.c_str()); } #endif handle = -1; } void FileDevice::flush() { if (mode.readOnly) { return; } #ifdef __MINGW32__ if (!FlushFileBuffers(HANDLE(handle))) { throw SysCallExcn("Flush failed"); } #else if (::fdatasync(handle)) { throw SysCallExcn("Flush failed"); } #endif } void FileDevice::setSizeInBytes(FileSize cbFileNew) { #ifdef __MINGW32__ LARGE_INTEGER cbLarge; cbLarge.QuadPart = cbFileNew; if (!SetFilePointerEx(HANDLE(handle),cbLarge,NULL,FILE_BEGIN)) { throw SysCallExcn("Resize file failed: SetFilePointer"); } if (!SetEndOfFile(HANDLE(handle))) { throw SysCallExcn("Resize file failed: SetEndOfFile"); } #else if(::ftruncate(handle,cbFileNew)){ throw SysCallExcn("Resize file failed"); } #endif cbFile = cbFileNew; } void FileDevice::transfer(RandomAccessRequest const &request) { FileSize cbActual; assert(request.bindingList.size() == 1); #ifdef __MINGW32__ LARGE_INTEGER largeInt; RandomAccessRequestBinding &binding = request.bindingList.front(); largeInt.QuadPart = request.cbOffset; binding.Offset = largeInt.LowPart; binding.OffsetHigh = largeInt.HighPart; DWORD dwActual = 0; BOOL bCompleted; if (request.type == RandomAccessRequest::READ) { bCompleted = ReadFile( HANDLE(handle), request.bindingList.front().getBuffer(), request.cbTransfer, &dwActual, &binding); } else { bCompleted = WriteFile( HANDLE(handle), request.bindingList.front().getBuffer(), request.cbTransfer, &dwActual, &binding); } if (!bCompleted) { if (GetLastError() == ERROR_IO_PENDING) { if (!GetOverlappedResult( HANDLE(handle), &binding, &dwActual, TRUE)) { dwActual = 0; } } else { dwActual = 0; } } cbActual = dwActual; #elif defined(__CYGWIN__) StrictMutexGuard guard(mutex); ::lseek(handle, request.cbOffset, SEEK_SET); if (request.type == RandomAccessRequest::READ) { cbActual = ::read( handle, request.bindingList.front().getBuffer(), request.cbTransfer); } else { cbActual = ::write( handle, request.bindingList.front().getBuffer(), request.cbTransfer); } guard.unlock(); #else if (request.type == RandomAccessRequest::READ) { cbActual = ::pread( handle, request.bindingList.front().getBuffer(), request.cbTransfer, request.cbOffset); } else { cbActual = ::pwrite( handle, request.bindingList.front().getBuffer(), request.cbTransfer, request.cbOffset); } #endif request.bindingList.front().notifyTransferCompletion( cbActual == request.cbTransfer); } FENNEL_END_CPPFILE("$Id$"); // End FileDevice.cpp <commit_msg>FENNEL: review comment regarding O_DIRECT+pwrite combination<commit_after>/* // $Id$ // Fennel is a library of data storage and processing components. // Copyright (C) 2005-2007 The Eigenbase Project // Copyright (C) 2005-2007 Disruptive Tech // Copyright (C) 2005-2007 LucidEra, Inc. // Portions Copyright (C) 1999-2007 John V. Sichi // // 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 approved by The Eigenbase Project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "fennel/common/CommonPreamble.h" #include "fennel/device/FileDevice.h" #include "fennel/device/RandomAccessRequest.h" #include "fennel/common/SysCallExcn.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <sstream> #ifdef __MINGW32__ #include <windows.h> #endif FENNEL_BEGIN_CPPFILE("$Id$"); FileDevice::FileDevice( std::string filenameInit,DeviceMode openMode,FileSize initialSize) { filename = filenameInit; mode = openMode; #ifdef __MINGW32__ DWORD fdwCreate = mode.create ? CREATE_ALWAYS : OPEN_EXISTING; DWORD fdwFlags = FILE_FLAG_OVERLAPPED; DWORD fdwAccess = GENERIC_READ; if (!mode.readOnly) { fdwAccess |= GENERIC_WRITE; } if (mode.direct) { fdwFlags |= FILE_FLAG_NO_BUFFERING; } if (mode.sequential) { fdwFlags |= FILE_FLAG_SEQUENTIAL_SCAN; } else { fdwFlags |= FILE_FLAG_RANDOM_ACCESS; } if (mode.temporary) { fdwFlags |= FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE; } else { fdwFlags |= FILE_ATTRIBUTE_NORMAL; } // REVIEW: I used FILE_SHARE_ so that recovery tests could reopen a // log file for read while it was still open for write by the original // txn. Should probably fix the tests instead, in case allowing sharing // could hinder performance. handle = reinterpret_cast<int>( CreateFile( filename.c_str(), fdwAccess, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, fdwCreate, fdwFlags, NULL)); if (!isOpen()) { std::ostringstream oss; oss << "Failed to open file " << filename; throw SysCallExcn(oss.str()); } DWORD cbHigh = 0; DWORD cbLow = GetFileSize(HANDLE(handle),&cbHigh); if (cbLow == INVALID_FILE_SIZE) { std::ostringstream oss; oss << "Failed to get size for file " << filename; throw SysCallExcn(oss.str()); } LARGE_INTEGER cbLarge; cbLarge.LowPart = cbLow; cbLarge.HighPart = cbHigh; cbFile = cbLarge.QuadPart; if (mode.create && initialSize > 0) { setSizeInBytes(initialSize); } #else int access = O_LARGEFILE; int permission = S_IRUSR; if (mode.readOnly) { access |= O_RDONLY; } else { access |= O_RDWR; permission |= S_IWUSR; } if (mode.create) { access |= O_CREAT | O_TRUNC; } if (mode.direct) { // REVIEW jvs 4-Dec-2008: Comment below used to be true, but probably // only on 2.4 kernels. 2.6 kernels seem to be happy with // O_DIRECT+pwrite. // (http://lkml.indiana.edu/hypermail/linux/kernel/0511.2/1758.html). // So we can probably clean this up now. access |= O_SYNC; // NOTE: We don't actually set O_DIRECT here, because on Linux // that results in EINVAL errors from pwrite. Instead, // O_DIRECT is set from AioLinuxScheduler, because it is required // for libaio. } handle = ::open(filename.c_str(), access, permission); if (!isOpen()) { std::ostringstream oss; oss << "Failed to open file " << filename; throw SysCallExcn(oss.str()); } if (flock(handle, LOCK_SH|LOCK_NB) < 0) { throw SysCallExcn("File lock failed"); } cbFile = ::lseek(handle,0,SEEK_END); // Preallocate the file if we're creating the file, and an initial size // is specified. if (mode.create && initialSize > 0) { int rc = posix_fallocate(handle, 0, initialSize); if (rc) { throw SysCallExcn("File allocation failed", rc); } cbFile = initialSize; } #endif } FileDevice::~FileDevice() { if (isOpen()) { close(); } } void FileDevice::close() { assert(isOpen()); #ifdef __MINGW32__ CloseHandle(HANDLE(handle)); #else ::close(handle); if (mode.temporary) { ::unlink(filename.c_str()); } #endif handle = -1; } void FileDevice::flush() { if (mode.readOnly) { return; } #ifdef __MINGW32__ if (!FlushFileBuffers(HANDLE(handle))) { throw SysCallExcn("Flush failed"); } #else if (::fdatasync(handle)) { throw SysCallExcn("Flush failed"); } #endif } void FileDevice::setSizeInBytes(FileSize cbFileNew) { #ifdef __MINGW32__ LARGE_INTEGER cbLarge; cbLarge.QuadPart = cbFileNew; if (!SetFilePointerEx(HANDLE(handle),cbLarge,NULL,FILE_BEGIN)) { throw SysCallExcn("Resize file failed: SetFilePointer"); } if (!SetEndOfFile(HANDLE(handle))) { throw SysCallExcn("Resize file failed: SetEndOfFile"); } #else if(::ftruncate(handle,cbFileNew)){ throw SysCallExcn("Resize file failed"); } #endif cbFile = cbFileNew; } void FileDevice::transfer(RandomAccessRequest const &request) { FileSize cbActual; assert(request.bindingList.size() == 1); #ifdef __MINGW32__ LARGE_INTEGER largeInt; RandomAccessRequestBinding &binding = request.bindingList.front(); largeInt.QuadPart = request.cbOffset; binding.Offset = largeInt.LowPart; binding.OffsetHigh = largeInt.HighPart; DWORD dwActual = 0; BOOL bCompleted; if (request.type == RandomAccessRequest::READ) { bCompleted = ReadFile( HANDLE(handle), request.bindingList.front().getBuffer(), request.cbTransfer, &dwActual, &binding); } else { bCompleted = WriteFile( HANDLE(handle), request.bindingList.front().getBuffer(), request.cbTransfer, &dwActual, &binding); } if (!bCompleted) { if (GetLastError() == ERROR_IO_PENDING) { if (!GetOverlappedResult( HANDLE(handle), &binding, &dwActual, TRUE)) { dwActual = 0; } } else { dwActual = 0; } } cbActual = dwActual; #elif defined(__CYGWIN__) StrictMutexGuard guard(mutex); ::lseek(handle, request.cbOffset, SEEK_SET); if (request.type == RandomAccessRequest::READ) { cbActual = ::read( handle, request.bindingList.front().getBuffer(), request.cbTransfer); } else { cbActual = ::write( handle, request.bindingList.front().getBuffer(), request.cbTransfer); } guard.unlock(); #else if (request.type == RandomAccessRequest::READ) { cbActual = ::pread( handle, request.bindingList.front().getBuffer(), request.cbTransfer, request.cbOffset); } else { cbActual = ::pwrite( handle, request.bindingList.front().getBuffer(), request.cbTransfer, request.cbOffset); } #endif request.bindingList.front().notifyTransferCompletion( cbActual == request.cbTransfer); } FENNEL_END_CPPFILE("$Id$"); // End FileDevice.cpp <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: asyncmodaldialog.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-11-07 14:48:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBACCESS_ASYNCMODALDIALOG_HXX #include "asyncmodaldialog.hxx" #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif /** === end UNO includes === **/ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef TOOLS_DIAGNOSE_EX_H #include <tools/diagnose_ex.h> #endif //........................................................................ namespace dbaui { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::ui::dialogs::XExecutableDialog; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::uno::Exception; /** === end UNO using === **/ //==================================================================== //= AsyncDialogExecutor //==================================================================== class DialogExecutor_Impl { Reference< XExecutableDialog > m_xDialog; public: DialogExecutor_Impl( const Reference< XExecutableDialog >& _rxDialog ) :m_xDialog( _rxDialog ) { } void execute() { Application::PostUserEvent( LINK( this, DialogExecutor_Impl, onExecute ) ); } protected: ~DialogExecutor_Impl() { } private: DECL_LINK( onExecute, void* ); }; //-------------------------------------------------------------------- IMPL_LINK( DialogExecutor_Impl, onExecute, void*, /* _notInterestedIn */ ) { try { m_xDialog->execute(); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } delete this; return 0L; } //==================================================================== //= AsyncDialogExecutor //==================================================================== //-------------------------------------------------------------------- void AsyncDialogExecutor::executeModalDialogAsync( const Reference< XExecutableDialog >& _rxDialog ) { if ( !_rxDialog.is() ) throw IllegalArgumentException(); DialogExecutor_Impl* pExecutor = new DialogExecutor_Impl( _rxDialog ); pExecutor->execute(); // will delete itself } //........................................................................ } // namespace dbaui //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.3.226); FILE MERGED 2008/03/31 13:27:54 rt 1.3.226.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: asyncmodaldialog.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBACCESS_ASYNCMODALDIALOG_HXX #include "asyncmodaldialog.hxx" #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif /** === end UNO includes === **/ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef TOOLS_DIAGNOSE_EX_H #include <tools/diagnose_ex.h> #endif //........................................................................ namespace dbaui { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::ui::dialogs::XExecutableDialog; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::uno::Exception; /** === end UNO using === **/ //==================================================================== //= AsyncDialogExecutor //==================================================================== class DialogExecutor_Impl { Reference< XExecutableDialog > m_xDialog; public: DialogExecutor_Impl( const Reference< XExecutableDialog >& _rxDialog ) :m_xDialog( _rxDialog ) { } void execute() { Application::PostUserEvent( LINK( this, DialogExecutor_Impl, onExecute ) ); } protected: ~DialogExecutor_Impl() { } private: DECL_LINK( onExecute, void* ); }; //-------------------------------------------------------------------- IMPL_LINK( DialogExecutor_Impl, onExecute, void*, /* _notInterestedIn */ ) { try { m_xDialog->execute(); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } delete this; return 0L; } //==================================================================== //= AsyncDialogExecutor //==================================================================== //-------------------------------------------------------------------- void AsyncDialogExecutor::executeModalDialogAsync( const Reference< XExecutableDialog >& _rxDialog ) { if ( !_rxDialog.is() ) throw IllegalArgumentException(); DialogExecutor_Impl* pExecutor = new DialogExecutor_Impl( _rxDialog ); pExecutor->execute(); // will delete itself } //........................................................................ } // namespace dbaui //........................................................................ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved. // // Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), // its affiliates and/or its licensors. // // 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 Image Engine Design nor the names of any // other contributors to this software 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 "IECoreMaya/FromMayaSkinClusterConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/Exception.h" #include "IECore/SmoothSkinningData.h" #include "IECore/CompoundParameter.h" #include "maya/MFnSkinCluster.h" #include "maya/MFnDagNode.h" #include "maya/MFnDependencyNode.h" #include "maya/MFnMatrixData.h" #include "maya/MDoubleArray.h" #include "maya/MDagPath.h" #include "maya/MDagPathArray.h" #include "maya/MObjectArray.h" #include "maya/MItGeometry.h" #include "maya/MPlug.h" using namespace IECoreMaya; using namespace std; IE_CORE_DEFINERUNTIMETYPED( FromMayaSkinClusterConverter ); static const MFn::Type fromTypes[] = { MFn::kSkinClusterFilter, MFn::kInvalid }; static const IECore::TypeId toTypes[] = { IECore::SmoothSkinningData::staticTypeId(), IECore::InvalidTypeId }; FromMayaObjectConverter::FromMayaObjectConverterDescription<FromMayaSkinClusterConverter> FromMayaSkinClusterConverter::m_description( fromTypes, toTypes ); FromMayaSkinClusterConverter::FromMayaSkinClusterConverter( const MObject &object ) : FromMayaObjectConverter( "Converts data on skinCluster nodes.into SmoothSkinningData", object ) { IECore::IntParameter::PresetsContainer influenceNamePresets; influenceNamePresets.push_back( IECore::IntParameter::Preset( "Partial", Partial ) ); influenceNamePresets.push_back( IECore::IntParameter::Preset( "Full", Full ) ); m_influenceNameParameter = new IECore::IntParameter( "influenceName", "Will the influence names contain the partial or full dag path.", Partial, Partial, Full, influenceNamePresets, true ); parameters()->addParameter( m_influenceNameParameter ); } IECore::IntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() { return m_influenceNameParameter; } IECore::ConstIntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() const { return m_influenceNameParameter; } IECore::ObjectPtr FromMayaSkinClusterConverter::doConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const { MStatus stat; // our data storage objects IECore::StringVectorDataPtr influenceNamesData = new IECore::StringVectorData(); IECore::M44fVectorDataPtr influencePoseData = new IECore::M44fVectorData(); IECore::IntVectorDataPtr pointIndexOffsetsData = new IECore::IntVectorData(); IECore::IntVectorDataPtr pointInfluenceCountsData = new IECore::IntVectorData(); IECore::IntVectorDataPtr pointInfluenceIndicesData = new IECore::IntVectorData(); IECore::FloatVectorDataPtr pointInfluenceWeightsData = new IECore::FloatVectorData(); // get a skin cluster fn MFnSkinCluster skinClusterFn(object); MDagPathArray influencePaths; skinClusterFn.influenceObjects(influencePaths); // get the influence names int influencesCount = influencePaths.length(); influenceNamesData->writable().reserve( influencesCount ); InfluenceName in = (InfluenceName)m_influenceNameParameter->getNumericValue(); switch( in ) { case Partial : { for (int i=0; i < influencesCount; i++) { influenceNamesData->writable().push_back( influencePaths[i].partialPathName(&stat).asChar() ); } break; } case Full : { for (int i=0; i < influencesCount; i++) { influenceNamesData->writable().push_back( influencePaths[i].fullPathName(&stat).asChar() ); } break; } } // extract bind pose MFnDependencyNode skinClusterNodeFn( object ); MPlug bindPreMatrixArrayPlug = skinClusterNodeFn.findPlug( "bindPreMatrix", true, &stat ); if ( int( bindPreMatrixArrayPlug .numElements() ) != influencesCount ) { throw IECore::Exception( "FromMayaSkinClusterConverter: number of elements in the skinCluster.bindPreMatrix" "array plug does not match the number of influences" ); } for (int i=0; i < influencesCount; i++) { MPlug bindPreMatrixElementPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( skinClusterFn.indexForInfluenceObject( influencePaths[i], NULL ), &stat); MObject matObj; bindPreMatrixElementPlug.getValue( matObj ); MFnMatrixData matFn( matObj, &stat ); MMatrix mat = matFn.matrix(); Imath::M44f cmat = IECore::convert<Imath::M44f>( mat ); influencePoseData->writable().push_back( cmat ); } // extract the skinning information // get the first input geometry to the skin cluster // TODO: if needed, extend this to retrieve more than one output geometry MObjectArray outputGeoObjs; stat = skinClusterFn.getOutputGeometry( outputGeoObjs ); if (! stat) { throw IECore::Exception( "FromMayaSkinClusterConverter: skinCluster node does not have any output geometry!" ); } // get the dag path to the first object MFnDagNode dagFn( outputGeoObjs[0] ); MDagPath geoPath; dagFn.getPath( geoPath ); // generate a geo iterator for the components MItGeometry geoIt( outputGeoObjs[0] ); int currentOffset = 0; // loop through all the points of the geometry to extract their bind information for ( ; !geoIt.isDone(); geoIt.next() ) { MObject pointObj = geoIt.currentItem( &stat ); MDoubleArray weights; unsigned int weightsCount; skinClusterFn.getWeights( geoPath, pointObj, weights, weightsCount ); int pointInfluencesCount = 0; for ( int influenceId = 0; influenceId < int( weightsCount ); influenceId++ ) { // ignore zero weights, we are generating a compressed (non-sparse) representation of the weights if ( weights[influenceId] != 0.0 ) { pointInfluencesCount++; pointInfluenceWeightsData->writable().push_back( float( weights[influenceId] ) ); pointInfluenceIndicesData->writable().push_back( influenceId ); } } pointIndexOffsetsData->writable().push_back( currentOffset ); pointInfluenceCountsData->writable().push_back( pointInfluencesCount ); currentOffset += pointInfluencesCount; } // put all our results in a smooth skinning data object return new IECore::SmoothSkinningData( influenceNamesData, influencePoseData, pointIndexOffsetsData, pointInfluenceCountsData, pointInfluenceIndicesData, pointInfluenceWeightsData ); } <commit_msg>fixing indentation<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved. // // Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), // its affiliates and/or its licensors. // // 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 Image Engine Design nor the names of any // other contributors to this software 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 "IECoreMaya/FromMayaSkinClusterConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/Exception.h" #include "IECore/SmoothSkinningData.h" #include "IECore/CompoundParameter.h" #include "maya/MFnSkinCluster.h" #include "maya/MFnDagNode.h" #include "maya/MFnDependencyNode.h" #include "maya/MFnMatrixData.h" #include "maya/MDoubleArray.h" #include "maya/MDagPath.h" #include "maya/MDagPathArray.h" #include "maya/MObjectArray.h" #include "maya/MItGeometry.h" #include "maya/MPlug.h" using namespace IECoreMaya; using namespace std; IE_CORE_DEFINERUNTIMETYPED( FromMayaSkinClusterConverter ); static const MFn::Type fromTypes[] = { MFn::kSkinClusterFilter, MFn::kInvalid }; static const IECore::TypeId toTypes[] = { IECore::SmoothSkinningData::staticTypeId(), IECore::InvalidTypeId }; FromMayaObjectConverter::FromMayaObjectConverterDescription<FromMayaSkinClusterConverter> FromMayaSkinClusterConverter::m_description( fromTypes, toTypes ); FromMayaSkinClusterConverter::FromMayaSkinClusterConverter( const MObject &object ) : FromMayaObjectConverter( "Converts data on skinCluster nodes.into SmoothSkinningData", object ) { IECore::IntParameter::PresetsContainer influenceNamePresets; influenceNamePresets.push_back( IECore::IntParameter::Preset( "Partial", Partial ) ); influenceNamePresets.push_back( IECore::IntParameter::Preset( "Full", Full ) ); m_influenceNameParameter = new IECore::IntParameter( "influenceName", "Will the influence names contain the partial or full dag path.", Partial, Partial, Full, influenceNamePresets, true ); parameters()->addParameter( m_influenceNameParameter ); } IECore::IntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() { return m_influenceNameParameter; } IECore::ConstIntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() const { return m_influenceNameParameter; } IECore::ObjectPtr FromMayaSkinClusterConverter::doConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const { MStatus stat; // our data storage objects IECore::StringVectorDataPtr influenceNamesData = new IECore::StringVectorData(); IECore::M44fVectorDataPtr influencePoseData = new IECore::M44fVectorData(); IECore::IntVectorDataPtr pointIndexOffsetsData = new IECore::IntVectorData(); IECore::IntVectorDataPtr pointInfluenceCountsData = new IECore::IntVectorData(); IECore::IntVectorDataPtr pointInfluenceIndicesData = new IECore::IntVectorData(); IECore::FloatVectorDataPtr pointInfluenceWeightsData = new IECore::FloatVectorData(); // get a skin cluster fn MFnSkinCluster skinClusterFn(object); MDagPathArray influencePaths; skinClusterFn.influenceObjects(influencePaths); // get the influence names int influencesCount = influencePaths.length(); influenceNamesData->writable().reserve( influencesCount ); InfluenceName in = (InfluenceName)m_influenceNameParameter->getNumericValue(); switch( in ) { case Partial : { for (int i=0; i < influencesCount; i++) { influenceNamesData->writable().push_back( influencePaths[i].partialPathName(&stat).asChar() ); } break; } case Full : { for (int i=0; i < influencesCount; i++) { influenceNamesData->writable().push_back( influencePaths[i].fullPathName(&stat).asChar() ); } break; } } // extract bind pose MFnDependencyNode skinClusterNodeFn( object ); MPlug bindPreMatrixArrayPlug = skinClusterNodeFn.findPlug( "bindPreMatrix", true, &stat ); if ( int( bindPreMatrixArrayPlug .numElements() ) != influencesCount ) { throw IECore::Exception( "FromMayaSkinClusterConverter: number of elements in the skinCluster.bindPreMatrix" "array plug does not match the number of influences" ); } for (int i=0; i < influencesCount; i++) { MPlug bindPreMatrixElementPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( skinClusterFn.indexForInfluenceObject( influencePaths[i], NULL ), &stat); MObject matObj; bindPreMatrixElementPlug.getValue( matObj ); MFnMatrixData matFn( matObj, &stat ); MMatrix mat = matFn.matrix(); Imath::M44f cmat = IECore::convert<Imath::M44f>( mat ); influencePoseData->writable().push_back( cmat ); } // extract the skinning information // get the first input geometry to the skin cluster // TODO: if needed, extend this to retrieve more than one output geometry MObjectArray outputGeoObjs; stat = skinClusterFn.getOutputGeometry( outputGeoObjs ); if (! stat) { throw IECore::Exception( "FromMayaSkinClusterConverter: skinCluster node does not have any output geometry!" ); } // get the dag path to the first object MFnDagNode dagFn( outputGeoObjs[0] ); MDagPath geoPath; dagFn.getPath( geoPath ); // generate a geo iterator for the components MItGeometry geoIt( outputGeoObjs[0] ); int currentOffset = 0; // loop through all the points of the geometry to extract their bind information for ( ; !geoIt.isDone(); geoIt.next() ) { MObject pointObj = geoIt.currentItem( &stat ); MDoubleArray weights; unsigned int weightsCount; skinClusterFn.getWeights( geoPath, pointObj, weights, weightsCount ); int pointInfluencesCount = 0; for ( int influenceId = 0; influenceId < int( weightsCount ); influenceId++ ) { // ignore zero weights, we are generating a compressed (non-sparse) representation of the weights if ( weights[influenceId] != 0.0 ) { pointInfluencesCount++; pointInfluenceWeightsData->writable().push_back( float( weights[influenceId] ) ); pointInfluenceIndicesData->writable().push_back( influenceId ); } } pointIndexOffsetsData->writable().push_back( currentOffset ); pointInfluenceCountsData->writable().push_back( pointInfluencesCount ); currentOffset += pointInfluencesCount; } // put all our results in a smooth skinning data object return new IECore::SmoothSkinningData( influenceNamesData, influencePoseData, pointIndexOffsetsData, pointInfluenceCountsData, pointInfluenceIndicesData, pointInfluenceWeightsData ); } <|endoftext|>
<commit_before>#include "Arduino.h" #include "Owly.h" #include "libs/PubSubClient/PubSubClient.h" #include "libs/PubSubClient/PubSubClient.cpp" #include "Client.h" PubSubClient _pubsubclient(); Owly::Owly(const char *inputuser_username, const char *inputuser_password, Client& client) { this->_inputuser_username = inputuser_username; this->_inputuser_password = inputuser_password; this->_clientid = inputuser_username; // TODO Should be changed to a random string. _pubsubclient.setClient(client); _pubsubclient.setServer("mqtt.owly.uk", 1883); } void Owly::Publish(char* topic, int int_payload) { char payload[10]; sprintf(payload, "%d", int_payload); _pubsubclient.publish(topic, payload); } void Owly::Publish(char* topic, char* payload) { _pubsubclient.publish(topic, payload); } boolean Owly::Connect() { return _pubsubclient.connect(this->_clientid, this->_inputuser_username, this->_inputuser_password); } void Owly::Loop() { _pubsubclient.loop(); }<commit_msg>Auto reconnect<commit_after>#include "Arduino.h" #include "Owly.h" #include "libs/PubSubClient/PubSubClient.h" #include "libs/PubSubClient/PubSubClient.cpp" #include "Client.h" PubSubClient _pubsubclient(); Owly::Owly(const char *inputuser_username, const char *inputuser_password, Client& client) { this->_inputuser_username = inputuser_username; this->_inputuser_password = inputuser_password; this->_clientid = inputuser_username; // TODO Should be changed to a random string. _pubsubclient.setClient(client); _pubsubclient.setServer("mqtt.owly.uk", 1883); } void Owly::Publish(char* topic, int int_payload) { char payload[10]; sprintf(payload, "%d", int_payload); _pubsubclient.publish(topic, payload); } void Owly::Publish(char* topic, char* payload) { _pubsubclient.publish(topic, payload); } boolean Owly::Connect() { return _pubsubclient.connect(this->_clientid, this->_inputuser_username, this->_inputuser_password); } void Owly::Loop() { if (!_pubsubclient.connected()) { _pubsubclient.connect(this->_clientid, this->_inputuser_username, this->_inputuser_password); } _pubsubclient.loop(); }<|endoftext|>
<commit_before>#include "State.h" using namespace std; //constructor State::State() { gameover = 0; turn = 0; bug.open("./debug.txt"); }; //deconstructor State::~State() { bug.close(); }; //sets the state up void State::setup() { grid = vector<vector<Square> >(rows, vector<Square>(cols, Square())); }; //resets all non-water squares to land and clears the bots ant vector void State::reset() { myAnts.clear(); enemyAnts.clear(); myHills.clear(); enemyHills.clear(); food.clear(); for(int row=0; row<rows; row++) for(int col=0; col<cols; col++) if(!grid[row][col].isWater) grid[row][col].reset(); }; //outputs move information to the engine void State::makeMove(const Location &loc, int direction) { cout << "o " << loc.row << " " << loc.col << " " << CDIRECTIONS[direction] << endl; Location nLoc = getLocation(loc, direction); grid[nLoc.row][nLoc.col].ant = grid[loc.row][loc.col].ant; grid[loc.row][loc.col].ant = -1; }; uint State::manhattanDistance(const Location& loc1, const Location& loc2) const { int d1 = abs(loc1.row-loc2.row); int d2 = abs(loc1.col-loc2.col); int dr = min(d1, rows-d1); int dc = min(d2, cols-d2); return dr + dc; } //returns the euclidean distance between two locations with the edges wrapped double State::distance(const Location &loc1, const Location &loc2) const { int d1 = abs(loc1.row-loc2.row), d2 = abs(loc1.col-loc2.col), dr = min(d1, rows-d1), dc = min(d2, cols-d2); return sqrt(dr*dr + dc*dc); }; //returns the new location from moving in a given direction with the edges wrapped Location State::getLocation(const Location &loc, int direction) const { return Location( (loc.row + DIRECTIONS[direction][0] + rows) % rows, (loc.col + DIRECTIONS[direction][1] + cols) % cols ); }; /* This function will update update the lastSeen value for any squares currently visible by one of your live ants. BE VERY CAREFUL IF YOU ARE GOING TO TRY AND MAKE THIS FUNCTION MORE EFFICIENT, THE OBVIOUS WAY OF TRYING TO IMPROVE IT BREAKS USING THE EUCLIDEAN METRIC, FOR A CORRECT MORE EFFICIENT IMPLEMENTATION, TAKE A LOOK AT THE GET_VISION FUNCTION IN ANTS.PY ON THE CONTESTS GITHUB PAGE. */ void State::updateVisionInformation() { std::queue<Location> locQueue; Location sLoc, cLoc, nLoc; for(int a=0; a<(int) myAnts.size(); a++) { sLoc = myAnts[a]; locQueue.push(sLoc); std::vector<std::vector<bool> > visited(rows, std::vector<bool>(cols, 0)); grid[sLoc.row][sLoc.col].isVisible = 1; visited[sLoc.row][sLoc.col] = 1; while(!locQueue.empty()) { cLoc = locQueue.front(); locQueue.pop(); for(int d=0; d<TDIRECTIONS; d++) { nLoc = getLocation(cLoc, d); if(!visited[nLoc.row][nLoc.col] && distance(sLoc, nLoc) <= viewradius) { grid[nLoc.row][nLoc.col].isVisible = 1; locQueue.push(nLoc); } visited[nLoc.row][nLoc.col] = 1; } } } }; /* This is the output function for a state. It will add a char map representation of the state to the output stream passed to it. For example, you might call "cout << state << endl;" */ ostream& operator<<(ostream &os, const State &state) { for(int row=0; row<state.rows; row++) { for(int col=0; col<state.cols; col++) { if(state.grid[row][col].isWater) os << '%'; else if(state.grid[row][col].isFood) os << '*'; else if(state.grid[row][col].isHill) os << (char)('A' + state.grid[row][col].hillPlayer); else if(state.grid[row][col].ant >= 0) os << (char)('a' + state.grid[row][col].ant); else if(state.grid[row][col].isVisible) os << '.'; else os << '?'; } os << endl; } return os; }; //input function istream& operator>>(istream &is, State &state) { int row, col, player; string inputType, junk; //finds out which turn it is while(is >> inputType) { if(inputType == "end") { state.gameover = 1; break; } else if(inputType == "turn") { is >> state.turn; break; } else //unknown line getline(is, junk); } if(state.turn == 0) { //reads game parameters while(is >> inputType) { if(inputType == "loadtime") is >> state.loadtime; else if(inputType == "turntime") is >> state.turntime; else if(inputType == "rows") is >> state.rows; else if(inputType == "cols") is >> state.cols; else if(inputType == "turns") is >> state.turns; else if(inputType == "player_seed") is >> state.seed; else if(inputType == "viewradius2") { is >> state.viewradius; state.viewradius = sqrt(state.viewradius); } else if(inputType == "attackradius2") { is >> state.attackradius; state.attackradius = sqrt(state.attackradius); } else if(inputType == "spawnradius2") { is >> state.spawnradius; state.spawnradius = sqrt(state.spawnradius); } else if(inputType == "ready") //end of parameter input { state.timer.start(); break; } else //unknown line getline(is, junk); } } else { //reads information about the current turn while(is >> inputType) { if(inputType == "w") //water square { is >> row >> col; state.grid[row][col].isWater = 1; } else if(inputType == "f") //food square { is >> row >> col; state.grid[row][col].isFood = 1; state.food.push_back(Location(row, col)); } else if(inputType == "a") //live ant square { is >> row >> col >> player; state.grid[row][col].ant = player; if(player == 0) state.myAnts.push_back(Location(row, col)); else state.enemyAnts.push_back(Location(row, col)); } else if(inputType == "d") //dead ant square { is >> row >> col >> player; state.grid[row][col].deadAnts.push_back(player); } else if(inputType == "h") { is >> row >> col >> player; state.grid[row][col].isHill = 1; state.grid[row][col].hillPlayer = player; if(player == 0) state.myHills.push_back(Location(row, col)); else state.enemyHills.push_back(Location(row, col)); } else if(inputType == "players") //player information is >> state.noPlayers; else if(inputType == "scores") //score information { state.scores = vector<double>(state.noPlayers, 0.0); for(int p=0; p<state.noPlayers; p++) is >> state.scores[p]; } else if(inputType == "go") //end of turn input { if(state.gameover) is.setstate(std::ios::failbit); else state.timer.start(); break; } else //unknown line getline(is, junk); } } return is; }; <commit_msg>srand<commit_after>#include "State.h" #include <stdlib.h> using namespace std; //constructor State::State() { gameover = 0; turn = 0; bug.open("./debug.txt"); }; //deconstructor State::~State() { bug.close(); }; //sets the state up void State::setup() { grid = vector<vector<Square> >(rows, vector<Square>(cols, Square())); srand(seed); }; //resets all non-water squares to land and clears the bots ant vector void State::reset() { myAnts.clear(); enemyAnts.clear(); myHills.clear(); enemyHills.clear(); food.clear(); for(int row=0; row<rows; row++) for(int col=0; col<cols; col++) if(!grid[row][col].isWater) grid[row][col].reset(); }; //outputs move information to the engine void State::makeMove(const Location &loc, int direction) { cout << "o " << loc.row << " " << loc.col << " " << CDIRECTIONS[direction] << endl; Location nLoc = getLocation(loc, direction); grid[nLoc.row][nLoc.col].ant = grid[loc.row][loc.col].ant; grid[loc.row][loc.col].ant = -1; }; uint State::manhattanDistance(const Location& loc1, const Location& loc2) const { int d1 = abs(loc1.row-loc2.row); int d2 = abs(loc1.col-loc2.col); int dr = min(d1, rows-d1); int dc = min(d2, cols-d2); return dr + dc; } //returns the euclidean distance between two locations with the edges wrapped double State::distance(const Location &loc1, const Location &loc2) const { int d1 = abs(loc1.row-loc2.row), d2 = abs(loc1.col-loc2.col), dr = min(d1, rows-d1), dc = min(d2, cols-d2); return sqrt(dr*dr + dc*dc); }; //returns the new location from moving in a given direction with the edges wrapped Location State::getLocation(const Location &loc, int direction) const { return Location( (loc.row + DIRECTIONS[direction][0] + rows) % rows, (loc.col + DIRECTIONS[direction][1] + cols) % cols ); }; /* This function will update update the lastSeen value for any squares currently visible by one of your live ants. BE VERY CAREFUL IF YOU ARE GOING TO TRY AND MAKE THIS FUNCTION MORE EFFICIENT, THE OBVIOUS WAY OF TRYING TO IMPROVE IT BREAKS USING THE EUCLIDEAN METRIC, FOR A CORRECT MORE EFFICIENT IMPLEMENTATION, TAKE A LOOK AT THE GET_VISION FUNCTION IN ANTS.PY ON THE CONTESTS GITHUB PAGE. */ void State::updateVisionInformation() { std::queue<Location> locQueue; Location sLoc, cLoc, nLoc; for(int a=0; a<(int) myAnts.size(); a++) { sLoc = myAnts[a]; locQueue.push(sLoc); std::vector<std::vector<bool> > visited(rows, std::vector<bool>(cols, 0)); grid[sLoc.row][sLoc.col].isVisible = 1; visited[sLoc.row][sLoc.col] = 1; while(!locQueue.empty()) { cLoc = locQueue.front(); locQueue.pop(); for(int d=0; d<TDIRECTIONS; d++) { nLoc = getLocation(cLoc, d); if(!visited[nLoc.row][nLoc.col] && distance(sLoc, nLoc) <= viewradius) { grid[nLoc.row][nLoc.col].isVisible = 1; locQueue.push(nLoc); } visited[nLoc.row][nLoc.col] = 1; } } } }; /* This is the output function for a state. It will add a char map representation of the state to the output stream passed to it. For example, you might call "cout << state << endl;" */ ostream& operator<<(ostream &os, const State &state) { for(int row=0; row<state.rows; row++) { for(int col=0; col<state.cols; col++) { if(state.grid[row][col].isWater) os << '%'; else if(state.grid[row][col].isFood) os << '*'; else if(state.grid[row][col].isHill) os << (char)('A' + state.grid[row][col].hillPlayer); else if(state.grid[row][col].ant >= 0) os << (char)('a' + state.grid[row][col].ant); else if(state.grid[row][col].isVisible) os << '.'; else os << '?'; } os << endl; } return os; }; //input function istream& operator>>(istream &is, State &state) { int row, col, player; string inputType, junk; //finds out which turn it is while(is >> inputType) { if(inputType == "end") { state.gameover = 1; break; } else if(inputType == "turn") { is >> state.turn; break; } else //unknown line getline(is, junk); } if(state.turn == 0) { //reads game parameters while(is >> inputType) { if(inputType == "loadtime") is >> state.loadtime; else if(inputType == "turntime") is >> state.turntime; else if(inputType == "rows") is >> state.rows; else if(inputType == "cols") is >> state.cols; else if(inputType == "turns") is >> state.turns; else if(inputType == "player_seed") is >> state.seed; else if(inputType == "viewradius2") { is >> state.viewradius; state.viewradius = sqrt(state.viewradius); } else if(inputType == "attackradius2") { is >> state.attackradius; state.attackradius = sqrt(state.attackradius); } else if(inputType == "spawnradius2") { is >> state.spawnradius; state.spawnradius = sqrt(state.spawnradius); } else if(inputType == "ready") //end of parameter input { state.timer.start(); break; } else //unknown line getline(is, junk); } } else { //reads information about the current turn while(is >> inputType) { if(inputType == "w") //water square { is >> row >> col; state.grid[row][col].isWater = 1; } else if(inputType == "f") //food square { is >> row >> col; state.grid[row][col].isFood = 1; state.food.push_back(Location(row, col)); } else if(inputType == "a") //live ant square { is >> row >> col >> player; state.grid[row][col].ant = player; if(player == 0) state.myAnts.push_back(Location(row, col)); else state.enemyAnts.push_back(Location(row, col)); } else if(inputType == "d") //dead ant square { is >> row >> col >> player; state.grid[row][col].deadAnts.push_back(player); } else if(inputType == "h") { is >> row >> col >> player; state.grid[row][col].isHill = 1; state.grid[row][col].hillPlayer = player; if(player == 0) state.myHills.push_back(Location(row, col)); else state.enemyHills.push_back(Location(row, col)); } else if(inputType == "players") //player information is >> state.noPlayers; else if(inputType == "scores") //score information { state.scores = vector<double>(state.noPlayers, 0.0); for(int p=0; p<state.noPlayers; p++) is >> state.scores[p]; } else if(inputType == "go") //end of turn input { if(state.gameover) is.setstate(std::ios::failbit); else state.timer.start(); break; } else //unknown line getline(is, junk); } } return is; }; <|endoftext|>
<commit_before>/************************************************* * TILP.h - Library for linking TI calculators * * and Arduinos. * * Created by Christopher Mitchell, * * 2011-2014, all rights reserved. * *************************************************/ #include "Arduino.h" #include "TILP.h" // Constructor with default communication lines TILP::TILP() { tip_ = DEFAULT_TIP; ring_ = DEFAULT_RING; HardwareSerial = NULL; } // Constructor with custom communication lines. Fun // fact: You can use this and multiple TILP objects to // talk to multiple endpoints at the same time. TILP::TILP(int tip, int ring) { tip_ = tip; ring_ = ring; HardwareSerial = NULL; } // This should be called during the setup() function // to set the communication lines to their initial values void TILP::begin() { resetLines(); } // Determine whether debug printing is enabled void TILP::setVerbosity(bool verbose, HardwareSerial* serial) { serial_ = serial; } // Send an entire message from the Arduino to // the attached TI device, byte by byte int TILP::send(uint8_t* header, uint8_t* data, int datalength) { if (HardwareSerial) { serial_->print("Sending message type 0x"); serial_->print(header[1], HEX); serial_->print(" to endpoint 0x"); serial_->print(header[0], HEX); serial_->print(" length "); serial_->println(datalength); } // Send all of the bytes in the header for(int idx = 0; idx < 4; idx++) { int rval = sendByte(header[idx]); if (rval != 0) return rval; } // If no data, we're done if (datalength == 0) { return 0; } // These also indicate that there are // no data bytes to be sent if (header[1] == CTS || header[1] == VER || header[1] == ACK || header[1] == ERR || header[1] == RDY || header[1] == SCR || header[1] == KEY || header[1] == EOT) { return 0; } // Send all of the bytes in the data buffer uint16_t checksum = 0; for(int idx = 0; idx < datalength; idx++) { // Try to send this byte int rval = sendByte(data[idx]); if (rval != 0) return rval; checksum += data[idx]; } // Send the checksum int rval = sendByte(checksum & 0x00ff); if (rval != 0) return rval; rval = sendByte((checksum >> 8) & 0x00ff); return rval; } // Send a single byte from the Arduino to the attached // TI device, returning nonzero if a failure occurred. int TILP::sendByte(uint8_t byte) { long previousMillis = 0; // Send all of the bits in this byte for(int bit = 0; bit < 8; bit++) { // Wait for both lines to be high before sending the bit previousMillis = 0; while (digitalRead(ring_) == LOW || digitalRead(tip_) == LOW) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Pull one line low to indicate a new bit is going out bool bitval = (byte & 1); int line = (bitval)?ring_:tip_; pinMode(line, OUTPUT); digitalWrite(line, LOW); // Wait for peer to acknowledge by pulling opposite line low line = (bitval)?tip_:ring_; previousMillis = 0; while (digitalRead(line) == HIGH) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Wait for peer to indicate readiness by releasing that line resetLines(); previousMillis = 0; while (digitalRead(line) == LOW) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Rotate the next bit to send into the low bit of the byte byte >>= 1; } return 0; } // Returns 0 for a successfully-read message or non-zero // for failure. If return value is 0 and datalength is zero, // then the message is just a 4-byte message in the header // buffer. If the int TILP::get(uint8_t* header, uint8_t* data, int* datalength, int maxlength) { int rval; // Get the 4-byte header: sender, message, length for(int idx = 0; idx < 4; idx++) { rval = getByte(&header[idx]); if (rval) return rval; } // Check if this is a data-free message *datalength = (int)header[2] | ((int)header[3] << 8); if (*datalength == 0); return 0; if (*datalength > maxlength) return ERR_BUFFER_OVERFLOW; if (HardwareSerial) { serial_->print("Receiving message type 0x"); serial_->print(header[1], HEX); serial_->print(" from endpoint 0x"); serial_->print(header[0], HEX); serial_->print(" length "); serial_->println(*datalength); } // These also indicate that there are // no data bytes to be received if (header[1] == CTS || header[1] == VER || header[1] == ACK || header[1] == ERR || header[1] == RDY || header[1] == SCR || header[1] == KEY || header[1] == EOT) { return 0; } // Get the data bytes, if there are any. uint16_t checksum = 0; for(int idx = 0; idx < *datalength; idx++) { // Try to get all the bytes, or fail if any of the // individual byte reads fail rval = getByte(&data[idx]); if (rval != 0) return rval; // Update checksum checksum += data[idx]; } // Receive and check the checksum uint8_t recv_checksum[2]; for(int idx = 0; idx < 2; idx++) { rval = getByte(&recv_checksum[idx]); if (rval) return rval; } // Die on a bad checksum if (checksum != (uint8_t)(((int)recv_checksum[1] << 8) | (int)recv_checksum[0])) return ERR_BAD_CHECKSUM; return 0; } // Receive a single byte from the attached TI device, // returning nonzero if a failure occurred. int TILP::getByte(uint8_t* byte) { long previousMillis = 0; *byte = 0; // Pull down each bit and store it for (int bit = 0; bit < 8; bit++) { int linevals; previousMillis = 0; while ((linevals = (digitalRead(ring_) << 1 | digitalRead(tip_))) == 0x03) { if (previousMillis++ > GET_ENTER_TIMEOUT) { resetLines(); return ERR_READ_TIMEOUT; } } // Store the bit, then acknowledge it *byte = (*byte >> 1) | ((linevals == 0x01)?0x80:0x7f); int line = (linevals == 0x01)?tip_:ring_; pinMode(line, OUTPUT); digitalWrite(line, LOW); // Wait for the peer to indicate readiness line = (linevals == 0x01)?ring_:tip_; previousMillis = 0; while (digitalRead(line) == LOW) { //wait for the other one to go low if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_READ_TIMEOUT; } } digitalWrite(line,HIGH); resetLines(); } return 0; } void TILP::resetLines(void) { pinMode(ring_, INPUT); // set pin to input digitalWrite(ring_, HIGH); // turn on pullup resistors pinMode(tip_, INPUT); // set pin to input digitalWrite(tip_, HIGH); // turn on pullup resistors } <commit_msg>Fixed stupid mistakes<commit_after>/************************************************* * TILP.h - Library for linking TI calculators * * and Arduinos. * * Created by Christopher Mitchell, * * 2011-2014, all rights reserved. * *************************************************/ #include "Arduino.h" #include "TILP.h" // Constructor with default communication lines TILP::TILP() { tip_ = DEFAULT_TIP; ring_ = DEFAULT_RING; serial_ = NULL; } // Constructor with custom communication lines. Fun // fact: You can use this and multiple TILP objects to // talk to multiple endpoints at the same time. TILP::TILP(int tip, int ring) { tip_ = tip; ring_ = ring; serial_ = NULL; } // This should be called during the setup() function // to set the communication lines to their initial values void TILP::begin() { resetLines(); } // Determine whether debug printing is enabled void TILP::setVerbosity(bool verbose, HardwareSerial* serial) { if (verbose) { serial_ = serial; else { serial_ = NULL; } } // Send an entire message from the Arduino to // the attached TI device, byte by byte int TILP::send(uint8_t* header, uint8_t* data, int datalength) { if (serial_) { serial_->print("Sending message type 0x"); serial_->print(header[1], HEX); serial_->print(" to endpoint 0x"); serial_->print(header[0], HEX); serial_->print(" length "); serial_->println(datalength); } // Send all of the bytes in the header for(int idx = 0; idx < 4; idx++) { int rval = sendByte(header[idx]); if (rval != 0) return rval; } // If no data, we're done if (datalength == 0) { return 0; } // These also indicate that there are // no data bytes to be sent if (header[1] == CTS || header[1] == VER || header[1] == ACK || header[1] == ERR || header[1] == RDY || header[1] == SCR || header[1] == KEY || header[1] == EOT) { return 0; } // Send all of the bytes in the data buffer uint16_t checksum = 0; for(int idx = 0; idx < datalength; idx++) { // Try to send this byte int rval = sendByte(data[idx]); if (rval != 0) return rval; checksum += data[idx]; } // Send the checksum int rval = sendByte(checksum & 0x00ff); if (rval != 0) return rval; rval = sendByte((checksum >> 8) & 0x00ff); return rval; } // Send a single byte from the Arduino to the attached // TI device, returning nonzero if a failure occurred. int TILP::sendByte(uint8_t byte) { long previousMillis = 0; // Send all of the bits in this byte for(int bit = 0; bit < 8; bit++) { // Wait for both lines to be high before sending the bit previousMillis = 0; while (digitalRead(ring_) == LOW || digitalRead(tip_) == LOW) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Pull one line low to indicate a new bit is going out bool bitval = (byte & 1); int line = (bitval)?ring_:tip_; pinMode(line, OUTPUT); digitalWrite(line, LOW); // Wait for peer to acknowledge by pulling opposite line low line = (bitval)?tip_:ring_; previousMillis = 0; while (digitalRead(line) == HIGH) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Wait for peer to indicate readiness by releasing that line resetLines(); previousMillis = 0; while (digitalRead(line) == LOW) { if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_WRITE_TIMEOUT; } } // Rotate the next bit to send into the low bit of the byte byte >>= 1; } return 0; } // Returns 0 for a successfully-read message or non-zero // for failure. If return value is 0 and datalength is zero, // then the message is just a 4-byte message in the header // buffer. If the int TILP::get(uint8_t* header, uint8_t* data, int* datalength, int maxlength) { int rval; // Get the 4-byte header: sender, message, length for(int idx = 0; idx < 4; idx++) { rval = getByte(&header[idx]); if (rval) return rval; } // Check if this is a data-free message *datalength = (int)header[2] | ((int)header[3] << 8); if (*datalength == 0); return 0; if (*datalength > maxlength) return ERR_BUFFER_OVERFLOW; if (serial_) { serial_->print("Receiving message type 0x"); serial_->print(header[1], HEX); serial_->print(" from endpoint 0x"); serial_->print(header[0], HEX); serial_->print(" length "); serial_->println(*datalength); } // These also indicate that there are // no data bytes to be received if (header[1] == CTS || header[1] == VER || header[1] == ACK || header[1] == ERR || header[1] == RDY || header[1] == SCR || header[1] == KEY || header[1] == EOT) { return 0; } // Get the data bytes, if there are any. uint16_t checksum = 0; for(int idx = 0; idx < *datalength; idx++) { // Try to get all the bytes, or fail if any of the // individual byte reads fail rval = getByte(&data[idx]); if (rval != 0) return rval; // Update checksum checksum += data[idx]; } // Receive and check the checksum uint8_t recv_checksum[2]; for(int idx = 0; idx < 2; idx++) { rval = getByte(&recv_checksum[idx]); if (rval) return rval; } // Die on a bad checksum if (checksum != (uint8_t)(((int)recv_checksum[1] << 8) | (int)recv_checksum[0])) return ERR_BAD_CHECKSUM; return 0; } // Receive a single byte from the attached TI device, // returning nonzero if a failure occurred. int TILP::getByte(uint8_t* byte) { long previousMillis = 0; *byte = 0; // Pull down each bit and store it for (int bit = 0; bit < 8; bit++) { int linevals; previousMillis = 0; while ((linevals = (digitalRead(ring_) << 1 | digitalRead(tip_))) == 0x03) { if (previousMillis++ > GET_ENTER_TIMEOUT) { resetLines(); return ERR_READ_TIMEOUT; } } // Store the bit, then acknowledge it *byte = (*byte >> 1) | ((linevals == 0x01)?0x80:0x7f); int line = (linevals == 0x01)?tip_:ring_; pinMode(line, OUTPUT); digitalWrite(line, LOW); // Wait for the peer to indicate readiness line = (linevals == 0x01)?ring_:tip_; previousMillis = 0; while (digitalRead(line) == LOW) { //wait for the other one to go low if (previousMillis++ > TIMEOUT) { resetLines(); return ERR_READ_TIMEOUT; } } digitalWrite(line,HIGH); resetLines(); } return 0; } void TILP::resetLines(void) { pinMode(ring_, INPUT); // set pin to input digitalWrite(ring_, HIGH); // turn on pullup resistors pinMode(tip_, INPUT); // set pin to input digitalWrite(tip_, HIGH); // turn on pullup resistors } <|endoftext|>
<commit_before>// --*- Mode: C++; c-basic-offset: 8 -*-- #include <complex> #include "EigenLab.h" int main(int argc, const char * argv[]) { EigenLab::ParserXd parserXd; auto failXd = parserXd.test(); EigenLab::ParserXf parserXf; auto failXf = parserXf.test(); #if EIGEN_VERSION_AT_LEAST(3,2,0) EigenLab::ParserXi parserXi; auto failXi = parserXi.test(); #else int failXi = 0; #endif EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd; auto failXcd = parserXcd.test(); std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl; return (failXd || failXf || failXi || failXcd) ? -1 : 0; } <commit_msg>disable integer matrix tests<commit_after>// --*- Mode: C++; c-basic-offset:8; indent-tabs-mode:t; tab-width:8 -*-- #include <complex> #include "EigenLab.h" int main(int argc, const char * argv[]) { EigenLab::ParserXd parserXd; auto failXd = parserXd.test(); EigenLab::ParserXf parserXf; auto failXf = parserXf.test(); #if 0 && EIGEN_VERSION_AT_LEAST(3,2,0) EigenLab::ParserXi parserXi; auto failXi = parserXi.test(); #else int failXi = 0; #endif EigenLab::Parser<Eigen::Matrix<std::complex<double>,Eigen::Dynamic,Eigen::Dynamic > > parserXcd; auto failXcd = parserXcd.test(); std::cout << "Test summary, number of failures: Xd=" << failXd << " Xf=" << failXf << " Xi=" << failXi << " Xcd=" << failXcd << std::endl; return (failXd || failXf || failXi || failXcd) ? -1 : 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydescriptor.cxx,v $ * * $Revision: 1.32 $ * * last change: $Author: hr $ $Date: 2007-11-01 15:02:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_ #include "querydescriptor.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::cppu; //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OQueryDescriptor //========================================================================== DBG_NAME(OQueryDescriptor) //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor() :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition) :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); osl_incrementInterlockedCount(&m_refCount); OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !"); try { ::comphelper::copyProperties(_rxCommandDefinition,this); } catch(Exception&) { OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!"); } osl_decrementInterlockedCount(&m_refCount); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource) :OQueryDescriptor_Base(_rSource,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } // ----------------------------------------------------------------------------- OQueryDescriptor::~OQueryDescriptor() { DBG_DTOR(OQueryDescriptor,NULL); } // ----------------------------------------------------------------------------- IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings); IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings) //-------------------------------------------------------------------------- void OQueryDescriptor::registerProperties() { // the properties which OCommandBase supplies (it has no own registration, as it's not derived from // a OPropertyStateContainer) registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED, &m_sElementName, ::getCppuType(&m_sElementName)); registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND, &m_sCommand, ::getCppuType(&m_sCommand)); registerProperty(PROPERTY_USE_ESCAPE_PROCESSING, PROPERTY_ID_USE_ESCAPE_PROCESSING, PropertyAttribute::BOUND, &m_bEscapeProcessing, ::getBooleanCppuType()); registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND, &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName)); registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND, &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName)); registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND, &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName)); registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND, &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation)); } // ----------------------------------------------------------------------------- //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ) ; } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } // ----------------------------------------------------------------------------- DBG_NAME(OQueryDescriptor_Base); //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex& _rMutex,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); } //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rSource.m_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); m_sCommand = _rSource.m_sCommand; m_bEscapeProcessing = _rSource.m_bEscapeProcessing; m_sUpdateTableName = _rSource.m_sUpdateTableName; m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName; m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName; m_aLayoutInformation = _rSource.m_aLayoutInformation; } //-------------------------------------------------------------------------- OQueryDescriptor_Base::~OQueryDescriptor_Base() { m_pColumns->acquire(); m_pColumns->disposing(); delete m_pColumns; DBG_DTOR(OQueryDescriptor_Base,NULL); } // ----------------------------------------------------------------------------- sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException) { if (_rIdentifier.getLength() != 16) return 0; if (0 == rtl_compareMemory(getImplementationId().getConstArray(), _rIdentifier.getConstArray(), 16 ) ) return reinterpret_cast<sal_Int64>(this); return 0; } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base) //-------------------------------------------------------------------------- void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate ) { m_bColumnsOutOfDate = _bOutOfDate; if ( !m_bColumnsOutOfDate ) m_pColumns->setInitialized(); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn ) { m_pColumns->append( _rName, _pColumn ); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::clearColumns( ) { m_pColumns->clearColumns(); setColumnsOutOfDate(); } //-------------------------------------------------------------------------- Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException) { MutexGuard aGuard(m_rMutex); if ( isColumnsOutOfDate() ) { // clear the current columns clearColumns(); // do this before rebuildColumns. This prevents recursion, e.g. in the case where we // have queries with cyclic references: // foo := SELECT * FROM bar // bar := SELECT * FROM foo setColumnsOutOfDate( sal_False ); // rebuild them try { rebuildColumns(); } catch(...) { setColumnsOutOfDate( sal_True ); throw; } } return m_pColumns; } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName( ) throw(RuntimeException) { return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor"); } //-------------------------------------------------------------------------- sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(2); aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS; aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR; return aSupported; } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::disposeColumns() { m_pColumns->disposing(); } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ ) { // not interested in } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/) { // not interested in } // ----------------------------------------------------------------------------- Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor() { OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" ); return NULL; } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::rebuildColumns( ) { } // ----------------------------------------------------------------------------- // IRefreshableColumns void OQueryDescriptor_Base::refreshColumns() { MutexGuard aGuard( m_rMutex ); clearColumns(); rebuildColumns(); } //------------------------------------------------------------------------------ OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const { return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS dba24c (1.31.108); FILE MERGED 2007/10/29 22:44:05 fs 1.31.108.2: merging changes from CWS dba24b herein, to not wait for later resync 2007/09/12 09:09:37 fs 1.31.108.1: PROPERTY_(ID_)USE_ESCAPE_PROCESSING: removed the USE_ for consistency reasons<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydescriptor.cxx,v $ * * $Revision: 1.33 $ * * last change: $Author: ihi $ $Date: 2007-11-21 15:34:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_ #include "querydescriptor.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::cppu; //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OQueryDescriptor //========================================================================== DBG_NAME(OQueryDescriptor) //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor() :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition) :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); osl_incrementInterlockedCount(&m_refCount); OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !"); try { ::comphelper::copyProperties(_rxCommandDefinition,this); } catch(Exception&) { OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!"); } osl_decrementInterlockedCount(&m_refCount); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource) :OQueryDescriptor_Base(_rSource,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } // ----------------------------------------------------------------------------- OQueryDescriptor::~OQueryDescriptor() { DBG_DTOR(OQueryDescriptor,NULL); } // ----------------------------------------------------------------------------- IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings); IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings) //-------------------------------------------------------------------------- void OQueryDescriptor::registerProperties() { // the properties which OCommandBase supplies (it has no own registration, as it's not derived from // a OPropertyStateContainer) registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED, &m_sElementName, ::getCppuType(&m_sElementName)); registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND, &m_sCommand, ::getCppuType(&m_sCommand)); registerProperty(PROPERTY_ESCAPE_PROCESSING, PROPERTY_ID_ESCAPE_PROCESSING, PropertyAttribute::BOUND, &m_bEscapeProcessing, ::getBooleanCppuType()); registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND, &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName)); registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND, &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName)); registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND, &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName)); registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND, &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation)); } // ----------------------------------------------------------------------------- //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ) ; } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } // ----------------------------------------------------------------------------- DBG_NAME(OQueryDescriptor_Base); //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex& _rMutex,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); } //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rSource.m_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); m_sCommand = _rSource.m_sCommand; m_bEscapeProcessing = _rSource.m_bEscapeProcessing; m_sUpdateTableName = _rSource.m_sUpdateTableName; m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName; m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName; m_aLayoutInformation = _rSource.m_aLayoutInformation; } //-------------------------------------------------------------------------- OQueryDescriptor_Base::~OQueryDescriptor_Base() { m_pColumns->acquire(); m_pColumns->disposing(); delete m_pColumns; DBG_DTOR(OQueryDescriptor_Base,NULL); } // ----------------------------------------------------------------------------- sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException) { if (_rIdentifier.getLength() != 16) return 0; if (0 == rtl_compareMemory(getImplementationId().getConstArray(), _rIdentifier.getConstArray(), 16 ) ) return reinterpret_cast<sal_Int64>(this); return 0; } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base) //-------------------------------------------------------------------------- void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate ) { m_bColumnsOutOfDate = _bOutOfDate; if ( !m_bColumnsOutOfDate ) m_pColumns->setInitialized(); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn ) { m_pColumns->append( _rName, _pColumn ); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::clearColumns( ) { m_pColumns->clearColumns(); setColumnsOutOfDate(); } //-------------------------------------------------------------------------- Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException) { MutexGuard aGuard(m_rMutex); if ( isColumnsOutOfDate() ) { // clear the current columns clearColumns(); // do this before rebuildColumns. This prevents recursion, e.g. in the case where we // have queries with cyclic references: // foo := SELECT * FROM bar // bar := SELECT * FROM foo setColumnsOutOfDate( sal_False ); // rebuild them try { rebuildColumns(); } catch(...) { setColumnsOutOfDate( sal_True ); throw; } } return m_pColumns; } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName( ) throw(RuntimeException) { return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor"); } //-------------------------------------------------------------------------- sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(2); aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS; aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR; return aSupported; } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::disposeColumns() { m_pColumns->disposing(); } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ ) { // not interested in } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/) { // not interested in } // ----------------------------------------------------------------------------- Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor() { OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" ); return NULL; } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::rebuildColumns( ) { } // ----------------------------------------------------------------------------- // IRefreshableColumns void OQueryDescriptor_Base::refreshColumns() { MutexGuard aGuard( m_rMutex ); clearColumns(); rebuildColumns(); } //------------------------------------------------------------------------------ OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const { return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: queryview.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2005-09-23 12:44:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; DBG_NAME(OQueryView) // ------------------------------------------------------------------------- OQueryView::OQueryView(Window* _pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory) :OJoinDesignView(_pParent,_pController,_rFactory) { DBG_CTOR(OQueryView,NULL); } // ----------------------------------------------------------------------------- OQueryView::~OQueryView() { DBG_DTOR(OQueryView,NULL); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.7.178); FILE MERGED 2006/09/01 17:24:39 kaib 1.7.178.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: queryview.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:27:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif #ifndef _DBU_QRY_HRC_ #include "dbu_qry.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef DBAUI_QUERYCONTROLLER_HXX #include "querycontroller.hxx" #endif using namespace dbaui; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; DBG_NAME(OQueryView) // ------------------------------------------------------------------------- OQueryView::OQueryView(Window* _pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory) :OJoinDesignView(_pParent,_pController,_rFactory) { DBG_CTOR(OQueryView,NULL); } // ----------------------------------------------------------------------------- OQueryView::~OQueryView() { DBG_DTOR(OQueryView,NULL); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "symbols.h" #include <stdio.h> #include <unordered_map> #include <memory> #include <string> using namespace Symbols; using namespace std; int SymbolTable::last_sequence = 0; // TODO: For debugging shared_ptr<SymbolTable> Symbols::global_symbol_table = make_shared<SymbolTable>(); shared_ptr<SymbolTable> Symbols::current_symbol_table(Symbols::global_symbol_table); Object::Object(int i) : kind(SymbolInt), iVal(i), fVal(nullptr) { } Object::Object(string s) : kind(SymbolString), sVal(s), fVal(nullptr) { } Object::Object(FunctionAssignment* p, shared_ptr<SymbolTable> closure) : kind(SymbolProcedure), fVal(p), closure(closure) { } Type Object::GetKind() { return this->kind; } string Object::GetString() { return this->sVal; } int Object::GetInt() { return this->iVal; } FunctionAssignment* Object::GetProcedure() { return this->fVal; } SymbolTable::SymbolTable() : sequence(++last_sequence) { } SymbolTable::SymbolTable(SymbolTable* cloneFrom) : sequence(++last_sequence) { for(auto it : cloneFrom->symbols) { symbols[it.first] = it.second; } } shared_ptr<Object> SymbolTable::Get(string name) { auto iter = this->symbols.find(name); bool found = (iter != this->symbols.end()); if(found) { return iter->second; } else { fprintf(stderr,"error: reference to non-existent symbol '%s'\n", name.c_str()); exit(1); } } void SymbolTable::Set(string name, shared_ptr<Object> object) { this->symbols[name] = object; } SymbolTableStateGuard::SymbolTableStateGuard() { this->prev_symbol_table = Symbols::current_symbol_table; } SymbolTableStateGuard::~SymbolTableStateGuard() { Symbols::current_symbol_table = this->prev_symbol_table; } <commit_msg>Use copy constructor to clone SymbolTable map<commit_after>#include "symbols.h" #include <stdio.h> #include <unordered_map> #include <memory> #include <string> using namespace Symbols; using namespace std; int SymbolTable::last_sequence = 0; // TODO: For debugging shared_ptr<SymbolTable> Symbols::global_symbol_table = make_shared<SymbolTable>(); shared_ptr<SymbolTable> Symbols::current_symbol_table(Symbols::global_symbol_table); Object::Object(int i) : kind(SymbolInt), iVal(i), fVal(nullptr) { } Object::Object(string s) : kind(SymbolString), sVal(s), fVal(nullptr) { } Object::Object(FunctionAssignment* p, shared_ptr<SymbolTable> closure) : kind(SymbolProcedure), fVal(p), closure(closure) { } Type Object::GetKind() { return this->kind; } string Object::GetString() { return this->sVal; } int Object::GetInt() { return this->iVal; } FunctionAssignment* Object::GetProcedure() { return this->fVal; } SymbolTable::SymbolTable() : sequence(++last_sequence) { } SymbolTable::SymbolTable(SymbolTable* cloneFrom) : sequence(++last_sequence) { symbols = cloneFrom->symbols; /* TODO: Deleteme for(auto it : cloneFrom->symbols) { symbols[it.first] = it.second; } */ } shared_ptr<Object> SymbolTable::Get(string name) { auto iter = this->symbols.find(name); bool found = (iter != this->symbols.end()); if(found) { return iter->second; } else { fprintf(stderr,"error: reference to non-existent symbol '%s'\n", name.c_str()); exit(1); } } void SymbolTable::Set(string name, shared_ptr<Object> object) { this->symbols[name] = object; } SymbolTableStateGuard::SymbolTableStateGuard() { this->prev_symbol_table = Symbols::current_symbol_table; } SymbolTableStateGuard::~SymbolTableStateGuard() { Symbols::current_symbol_table = this->prev_symbol_table; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_version.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-11-06 14:54:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2006 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_VERSION_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_VERSION_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif namespace com { namespace sun { namespace star { namespace deployment { class XPackage; } } } } namespace rtl { class OUString; } namespace dp_misc { enum Order { LESS, EQUAL, GREATER }; Order compareVersions( ::rtl::OUString const & version1, ::rtl::OUString const & version2); Order comparePackageVersions( ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package1, ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package2); } #endif <commit_msg>INTEGRATION: CWS jl49 (1.2.8); FILE MERGED 2006/11/22 17:40:08 sb 1.2.8.2: #i70481# Introduced additional deploymentmisc shared library. 2006/11/16 14:36:49 sb 1.2.8.1: #i70481# Merged in rev. 1.3.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_version.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ihi $ $Date: 2006-12-20 14:27:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2006 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_VERSION_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_VERSION_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_MISC_API_HXX #include "dp_misc_api.hxx" #endif namespace com { namespace sun { namespace star { namespace deployment { class XPackage; } } } } namespace rtl { class OUString; } namespace dp_misc { enum Order { LESS, EQUAL, GREATER }; DESKTOP_DEPLOYMENTMISC_DLLPUBLIC Order compareVersions( ::rtl::OUString const & version1, ::rtl::OUString const & version2); DESKTOP_DEPLOYMENTMISC_DLLPUBLIC Order comparePackageVersions( ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package1, ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package2); } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #include <malloc.h> #include "halide_benchmark.h" #include "pipeline_cpu.h" #include "pipeline_hvx64.h" #include "pipeline_hvx128.h" #include "HalideRuntimeHexagonHost.h" #include "HalideBuffer.h" template <typename T> T clamp(T x, T min, T max) { if (x < min) x = min; if (x > max) x = max; return x; } int main(int argc, char **argv) { if (argc < 6) { printf("Usage: %s (cpu|hvx64) timing_iterations M N K\n", argv[0]); return 0; } int (*pipeline)(halide_buffer_t *, halide_buffer_t*, halide_buffer_t*); if (strcmp(argv[1], "cpu") == 0) { pipeline = pipeline_cpu; printf("Using CPU schedule\n"); } else if (strcmp(argv[1], "hvx64") == 0) { pipeline = pipeline_hvx64; printf("Using HVX 64 schedule\n"); } else if (strcmp(argv[1], "hvx128") == 0) { pipeline = pipeline_hvx128; printf("Using HVX 128 schedule\n"); } else { printf("Unknown schedule, valid schedules are cpu, hvx64, or hvx128\n"); return -1; } int iterations = atoi(argv[2]); const int M = atoi(argv[3]); const int N = atoi(argv[4]); const int K = atoi(argv[5]); // Hexagon's device_malloc implementation will also set the host // pointer if it is null, giving a zero copy buffer. Halide::Runtime::Buffer<uint8_t> mat_a(nullptr, N, M); Halide::Runtime::Buffer<uint8_t> mat_b(nullptr, K, N); Halide::Runtime::Buffer<uint32_t> mat_ab(nullptr, K, M); mat_a.device_malloc(halide_hexagon_device_interface()); mat_b.device_malloc(halide_hexagon_device_interface()); mat_ab.device_malloc(halide_hexagon_device_interface()); // Fill the input buffer with random data. mat_a.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); mat_b.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); // To avoid the cost of powering HVX on in each call of the // pipeline, power it on once now. Also, set Hexagon performance to turbo. halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_turbo); halide_hexagon_power_hvx_on(nullptr); printf("Running pipeline...\n"); double time = Halide::Tools::benchmark(iterations, 1, [&]() { int result = pipeline(mat_a, mat_b, mat_ab); if (result != 0) { printf("pipeline failed! %d\n", result); } }); printf("Done, time: %g s\n", time); // We're done with HVX, power it off, and reset the performance mode // to default to save power. halide_hexagon_power_hvx_off(nullptr); halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_default); // Validate that the algorithm did what we expect. mat_ab.for_each_element([&](int x, int y) { // This reference implementation is very slow, so only check a subset of the result. if ((y * N + x) % 100 != 0) { return; } uint32_t ab_xy = 0; for (int k = 0; k < K; k++) { ab_xy += static_cast<uint32_t>(mat_a(k, y))*static_cast<uint32_t>(mat_b(x, k)); } if (ab_xy != mat_ab(x, y)) { printf("Mismatch at %d %d: %d != %d\n", x, y, ab_xy, mat_ab(x, y)); abort(); } }); printf("Success!\n"); return 0; } <commit_msg>Copy output back to the host explicitly.<commit_after>#include <stdio.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #include <malloc.h> #include "halide_benchmark.h" #include "pipeline_cpu.h" #include "pipeline_hvx64.h" #include "pipeline_hvx128.h" #include "HalideRuntimeHexagonHost.h" #include "HalideBuffer.h" template <typename T> T clamp(T x, T min, T max) { if (x < min) x = min; if (x > max) x = max; return x; } int main(int argc, char **argv) { if (argc < 6) { printf("Usage: %s (cpu|hvx64) timing_iterations M N K\n", argv[0]); return 0; } int (*pipeline)(halide_buffer_t *, halide_buffer_t*, halide_buffer_t*); if (strcmp(argv[1], "cpu") == 0) { pipeline = pipeline_cpu; printf("Using CPU schedule\n"); } else if (strcmp(argv[1], "hvx64") == 0) { pipeline = pipeline_hvx64; printf("Using HVX 64 schedule\n"); } else if (strcmp(argv[1], "hvx128") == 0) { pipeline = pipeline_hvx128; printf("Using HVX 128 schedule\n"); } else { printf("Unknown schedule, valid schedules are cpu, hvx64, or hvx128\n"); return -1; } int iterations = atoi(argv[2]); const int M = atoi(argv[3]); const int N = atoi(argv[4]); const int K = atoi(argv[5]); // Hexagon's device_malloc implementation will also set the host // pointer if it is null, giving a zero copy buffer. Halide::Runtime::Buffer<uint8_t> mat_a(nullptr, N, M); Halide::Runtime::Buffer<uint8_t> mat_b(nullptr, K, N); Halide::Runtime::Buffer<uint32_t> mat_ab(nullptr, K, M); mat_a.device_malloc(halide_hexagon_device_interface()); mat_b.device_malloc(halide_hexagon_device_interface()); mat_ab.device_malloc(halide_hexagon_device_interface()); // Fill the input buffer with random data. mat_a.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); mat_b.for_each_value([&](uint8_t &x) { x = static_cast<uint8_t>(rand()); }); // To avoid the cost of powering HVX on in each call of the // pipeline, power it on once now. Also, set Hexagon performance to turbo. halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_turbo); halide_hexagon_power_hvx_on(nullptr); printf("Running pipeline...\n"); double time = Halide::Tools::benchmark(iterations, 1, [&]() { int result = pipeline(mat_a, mat_b, mat_ab); if (result != 0) { printf("pipeline failed! %d\n", result); } }); printf("Done, time: %g s\n", time); // We're done with HVX, power it off, and reset the performance mode // to default to save power. halide_hexagon_power_hvx_off(nullptr); halide_hexagon_set_performance_mode(nullptr, halide_hexagon_power_default); // Copy the output back to the host. If the buffer is zero-copy (as // it should be on a real device), this will be a no-op. mat_ab.copy_to_host(); // Validate that the algorithm did what we expect. mat_ab.for_each_element([&](int x, int y) { // This reference implementation is very slow, so only check a subset of the result. if ((y * N + x) % 100 != 0) { return; } uint32_t ab_xy = 0; for (int k = 0; k < K; k++) { ab_xy += static_cast<uint32_t>(mat_a(k, y))*static_cast<uint32_t>(mat_b(x, k)); } if (ab_xy != mat_ab(x, y)) { printf("Mismatch at %d %d: %d != %d\n", x, y, ab_xy, mat_ab(x, y)); abort(); } }); printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#include "config.h" #include "file_io_type_pel.hpp" #include "utils.hpp" #include "xyz/openbmc_project/Common/error.hpp" #include <stdint.h> #include <systemd/sd-bus.h> #include <unistd.h> #include <exception> #include <filesystem> #include <iostream> #include <sdbusplus/server.hpp> #include <vector> #include <xyz/openbmc_project/Logging/Entry/server.hpp> #include "libpldm/base.h" #include "oem/ibm/libpldm/file_io.h" namespace pldm { namespace responder { int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, uint64_t address) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); auto rc = transferFileData(fd, true, offset, length, address); return rc; } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed, PEL id = " << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::read(uint32_t offset, uint32_t& length, Response& response) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); off_t fileSize = lseek(fd, 0, SEEK_END); if (fileSize == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } if (offset >= fileSize) { std::cerr << "Offset exceeds file size, OFFSET=" << offset << " FILE_SIZE=" << fileSize << std::endl; return PLDM_DATA_OUT_OF_RANGE; } if (offset + length > fileSize) { length = fileSize - offset; } auto rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } size_t currSize = response.size(); response.resize(currSize + length); auto filePos = reinterpret_cast<char*>(response.data()); filePos += currSize; rc = ::read(fd, filePos, length); if (rc == -1) { std::cerr << "file read failed"; return PLDM_ERROR; } if (rc != length) { std::cerr << "mismatch between number of characters to read and " << "the length read, LENGTH=" << length << " COUNT=" << rc << std::endl; return PLDM_ERROR; } } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::writeFromMemory(uint32_t offset, uint32_t length, uint64_t address) { char tmpFile[] = "/tmp/pel.XXXXXX"; int fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } close(fd); fs::path path(tmpFile); auto rc = transferFileData(path, false, offset, length, address); if (rc == PLDM_SUCCESS) { rc = storePel(path.string()); } fs::remove(path); return rc; } int PelHandler::fileAck(uint8_t /*fileStatus*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "HostAck"); method.append(fileHandle); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "HostAck D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::storePel(std::string&& pelFileName) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "xyz.openbmc_project.Logging.Create"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); using namespace sdbusplus::xyz::openbmc_project::Logging::server; std::map<std::string, std::string> addlData{}; addlData.emplace("RAWPEL", std::move(pelFileName)); auto severity = sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage( sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level:: Error); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "Create"); method.append("xyz.openbmc_project.Host.Error.Event", severity, addlData); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "failed to make a d-bus call to PEL daemon, ERROR=" << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } } // namespace responder } // namespace pldm <commit_msg>oem-ibm: Get event log severity from PEL<commit_after>#include "config.h" #include "file_io_type_pel.hpp" #include "utils.hpp" #include "xyz/openbmc_project/Common/error.hpp" #include <stdint.h> #include <systemd/sd-bus.h> #include <unistd.h> #include <exception> #include <filesystem> #include <fstream> #include <iostream> #include <sdbusplus/server.hpp> #include <vector> #include <xyz/openbmc_project/Logging/Entry/server.hpp> #include "libpldm/base.h" #include "oem/ibm/libpldm/file_io.h" namespace pldm { namespace responder { using namespace sdbusplus::xyz::openbmc_project::Logging::server; namespace detail { /** * @brief Finds the Entry::Level value for the severity of the PEL * passed in. * * The severity byte is at offset 10 in the User Header section, * which is always after the 48 byte Private Header section. * * @param[in] pelFileName - The file containing the PEL * * @return Entry::Level - The severity value for the Entry */ Entry::Level getEntryLevelFromPEL(const std::string& pelFileName) { const std::map<uint8_t, Entry::Level> severityMap{ {0x00, Entry::Level::Informational}, // Informational event {0x10, Entry::Level::Warning}, // Recoverable error {0x20, Entry::Level::Warning}, // Predictive error {0x40, Entry::Level::Error}, // Unrecoverable error {0x50, Entry::Level::Error}, // Critical error {0x60, Entry::Level::Error}, // Error from a diagnostic test {0x70, Entry::Level::Warning} // Recoverable symptom }; const size_t severityOffset = 0x3A; size_t size = 0; if (fs::exists(pelFileName)) { size = fs::file_size(pelFileName); } if (size > severityOffset) { std::ifstream pel{pelFileName}; if (pel.good()) { pel.seekg(severityOffset); uint8_t sev; pel.read(reinterpret_cast<char*>(&sev), 1); // Get the type sev = sev & 0xF0; auto entry = severityMap.find(sev); if (entry != severityMap.end()) { return entry->second; } } else { std::cerr << "Unable to open PEL file " << pelFileName << "\n"; } } return Entry::Level::Error; } } // namespace detail int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, uint64_t address) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); auto rc = transferFileData(fd, true, offset, length, address); return rc; } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed, PEL id = " << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::read(uint32_t offset, uint32_t& length, Response& response) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); off_t fileSize = lseek(fd, 0, SEEK_END); if (fileSize == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } if (offset >= fileSize) { std::cerr << "Offset exceeds file size, OFFSET=" << offset << " FILE_SIZE=" << fileSize << std::endl; return PLDM_DATA_OUT_OF_RANGE; } if (offset + length > fileSize) { length = fileSize - offset; } auto rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } size_t currSize = response.size(); response.resize(currSize + length); auto filePos = reinterpret_cast<char*>(response.data()); filePos += currSize; rc = ::read(fd, filePos, length); if (rc == -1) { std::cerr << "file read failed"; return PLDM_ERROR; } if (rc != length) { std::cerr << "mismatch between number of characters to read and " << "the length read, LENGTH=" << length << " COUNT=" << rc << std::endl; return PLDM_ERROR; } } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::writeFromMemory(uint32_t offset, uint32_t length, uint64_t address) { char tmpFile[] = "/tmp/pel.XXXXXX"; int fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } close(fd); fs::path path(tmpFile); auto rc = transferFileData(path, false, offset, length, address); if (rc == PLDM_SUCCESS) { rc = storePel(path.string()); } fs::remove(path); return rc; } int PelHandler::fileAck(uint8_t /*fileStatus*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "HostAck"); method.append(fileHandle); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "HostAck D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::storePel(std::string&& pelFileName) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "xyz.openbmc_project.Logging.Create"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); using namespace sdbusplus::xyz::openbmc_project::Logging::server; std::map<std::string, std::string> addlData{}; auto severity = sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage( detail::getEntryLevelFromPEL(pelFileName)); addlData.emplace("RAWPEL", std::move(pelFileName)); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "Create"); method.append("xyz.openbmc_project.Host.Error.Event", severity, addlData); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "failed to make a d-bus call to PEL daemon, ERROR=" << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } } // namespace responder } // namespace pldm <|endoftext|>
<commit_before>/* * Target.cc * * Author: William Ma <https://github.com/williampma> * * Copyright (C) 2015 OpenCog Foundation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/random.h> #include <opencog/atoms/bind/PatternUtils.h> #include <opencog/atomutils/AtomUtils.h> #include "Target.h" using namespace opencog; /** * Constructor of Target. * * Only the TargetSet class can create a Target object. * * @param as the AtomSpace in which to store temporary information * @param h the original external Handle of the Target */ Target::Target(AtomSpace& as, const Handle& h) : _as(as) { _htarget_external = h; _htarget_internal = _as.add_atom(h); _selection_count = 0; _vars = get_free_vars_in_tree(h); // _varmap is a map that bases on the external space for (auto& hv : _vars) _varmap[hv] = UnorderedHandleSet(); } /** * Store a specific inference step for the Target into the AtomSpace. * * @param r the rule applied * @param premises the premises selected to be the rule's input */ void Target::store_step(const Rule& r, const HandleSeq& premises) { // XXX TODO think of a good structure for storing the inference step // XXX TODO if the rule was actually applied, store the change to the TV? _as.add_link(SET_LINK, _htarget_internal, _as.addNode(CONCEPT_NODE, r.get_name()), _as.addLink(LIST_LINK, premises)); } /** * Store new variable mappings. * * @param vm a VarMultimap object containing additional mappings */ void Target::store_varmap(VarMultimap& vm) { for (auto& p : vm) { if (_varmap.count(p.first) == 1) _varmap[p.first].insert(p.second.begin(), p.second.end()); } } /** * Store new variable mapping. * * @param vm a VarMap object containing additional mapping */ void Target::store_varmap(VarMap& vm) { for (auto& p : vm) { if (_varmap.count(p.first) == 1) _varmap[p.first].insert(p.second); } } /** * Count how many times a Rule was selected for the Target. * * This method follow the inference tree atom structure to find all usage. * * @param r the Rule to search * @return the number of times applied */ unsigned int Target::rule_count(const Rule& r) { Handle hname = _as.add_node(CONCEPT_NODE, r.get_name()); HandleSeq q = get_neighbors(_htarget_internal, false, true, SET_LINK, false); return std::count(q.begin(), q.end(), hname); } //================================================================== /** * Constructor. */ TargetSet::TargetSet() : _total_selection(0) { } /** * Destructor. */ TargetSet::~TargetSet() { } /** * Clear the TargetSet. */ void TargetSet::clear() { _history_space.clear(); _targets_map.clear(); } /** * Add a new Target into the set. * * @param h the atom to which the Target will be created */ void TargetSet::emplace(Handle& h) { if (_targets_map.count(h) == 1) return; _targets_map.insert(std::pair<Handle, Target>(h, Target(_history_space, h))); } /** * Get the size of the TargetSet. */ unsigned int TargetSet::size() { return _targets_map.size(); } /** * Select a Target from the set using some fitness criteria. * * Currently uses the selection count to apply weighted random selection. * * XXX TODO use criteria such as * - how many steps from the initial target * - how much was gained on this target the last time it was chosen * etc * * @return a reference to the selected Target */ Target& TargetSet::select() { HandleSeq handles; std::vector<unsigned int> weights; for (auto& p : _targets_map) { handles.push_back(p.first); // XXX TODO add more criteria to the weight calculation weights.push_back(_total_selection - p.second.get_selection_count() + 1); } // XXX use cogutil MT19937RandGen's intenal randomGen member possible? std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count()); std::discrete_distribution<int> distribution(weights.begin(), weights.end()); Target& t = _targets_map.at(handles[distribution(generator)]); t.increment_selection_count(); _total_selection++; return t; } /** * Get a specific Target. * * @param h the handle of the Target * @return a reference to the Target */ Target& TargetSet::get(Handle& h) { return _targets_map.at(h); } <commit_msg>Rename remaining addNode and addLink<commit_after>/* * Target.cc * * Author: William Ma <https://github.com/williampma> * * Copyright (C) 2015 OpenCog Foundation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/random.h> #include <opencog/atoms/bind/PatternUtils.h> #include <opencog/atomutils/AtomUtils.h> #include "Target.h" using namespace opencog; /** * Constructor of Target. * * Only the TargetSet class can create a Target object. * * @param as the AtomSpace in which to store temporary information * @param h the original external Handle of the Target */ Target::Target(AtomSpace& as, const Handle& h) : _as(as) { _htarget_external = h; _htarget_internal = _as.add_atom(h); _selection_count = 0; _vars = get_free_vars_in_tree(h); // _varmap is a map that bases on the external space for (auto& hv : _vars) _varmap[hv] = UnorderedHandleSet(); } /** * Store a specific inference step for the Target into the AtomSpace. * * @param r the rule applied * @param premises the premises selected to be the rule's input */ void Target::store_step(const Rule& r, const HandleSeq& premises) { // XXX TODO think of a good structure for storing the inference step // XXX TODO if the rule was actually applied, store the change to the TV? _as.add_link(SET_LINK, _htarget_internal, _as.add_node(CONCEPT_NODE, r.get_name()), _as.add_link(LIST_LINK, premises)); } /** * Store new variable mappings. * * @param vm a VarMultimap object containing additional mappings */ void Target::store_varmap(VarMultimap& vm) { for (auto& p : vm) { if (_varmap.count(p.first) == 1) _varmap[p.first].insert(p.second.begin(), p.second.end()); } } /** * Store new variable mapping. * * @param vm a VarMap object containing additional mapping */ void Target::store_varmap(VarMap& vm) { for (auto& p : vm) { if (_varmap.count(p.first) == 1) _varmap[p.first].insert(p.second); } } /** * Count how many times a Rule was selected for the Target. * * This method follow the inference tree atom structure to find all usage. * * @param r the Rule to search * @return the number of times applied */ unsigned int Target::rule_count(const Rule& r) { Handle hname = _as.add_node(CONCEPT_NODE, r.get_name()); HandleSeq q = get_neighbors(_htarget_internal, false, true, SET_LINK, false); return std::count(q.begin(), q.end(), hname); } //================================================================== /** * Constructor. */ TargetSet::TargetSet() : _total_selection(0) { } /** * Destructor. */ TargetSet::~TargetSet() { } /** * Clear the TargetSet. */ void TargetSet::clear() { _history_space.clear(); _targets_map.clear(); } /** * Add a new Target into the set. * * @param h the atom to which the Target will be created */ void TargetSet::emplace(Handle& h) { if (_targets_map.count(h) == 1) return; _targets_map.insert(std::pair<Handle, Target>(h, Target(_history_space, h))); } /** * Get the size of the TargetSet. */ unsigned int TargetSet::size() { return _targets_map.size(); } /** * Select a Target from the set using some fitness criteria. * * Currently uses the selection count to apply weighted random selection. * * XXX TODO use criteria such as * - how many steps from the initial target * - how much was gained on this target the last time it was chosen * etc * * @return a reference to the selected Target */ Target& TargetSet::select() { HandleSeq handles; std::vector<unsigned int> weights; for (auto& p : _targets_map) { handles.push_back(p.first); // XXX TODO add more criteria to the weight calculation weights.push_back(_total_selection - p.second.get_selection_count() + 1); } // XXX use cogutil MT19937RandGen's intenal randomGen member possible? std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count()); std::discrete_distribution<int> distribution(weights.begin(), weights.end()); Target& t = _targets_map.at(handles[distribution(generator)]); t.increment_selection_count(); _total_selection++; return t; } /** * Get a specific Target. * * @param h the handle of the Target * @return a reference to the Target */ Target& TargetSet::get(Handle& h) { return _targets_map.at(h); } <|endoftext|>
<commit_before>#include <iostream> using namespace std; #include "gtest/gtest.h" #include "BoardHelper.h" #include "MnistLoader.h" #include "BoardPng.h" #include "Timer.h" #include "NeuralNet.h" #include "AccuracyHelper.h" #include "stringhelper.h" #include "FileHelper.h" void loadMnist( string mnistDir, string setName, int *p_N, int *p_boardSize, float ****p_images, int **p_labels, float **p_expectedOutputs ) { int boardSize; int Nboards; int Nlabels; // images int ***boards = MnistLoader::loadImages( mnistDir, setName, &Nboards, &boardSize ); int *labels = MnistLoader::loadLabels( mnistDir, setName, &Nlabels ); if( Nboards != Nlabels ) { throw runtime_error("mismatch between number of boards, and number of labels " + toString(Nboards ) + " vs " + toString(Nlabels ) ); } cout << "loaded " << Nboards << " boards. " << endl; // MnistLoader::shuffle( boards, labels, Nboards, boardSize ); float ***boardsFloat = BoardsHelper::allocateBoardsFloats( Nboards, boardSize ); BoardsHelper::copyBoards( boardsFloat, boards, Nboards, boardSize ); BoardsHelper::deleteBoards( &boards, Nboards, boardSize ); *p_images = boardsFloat; *p_labels = labels; *p_boardSize = boardSize; *p_N = Nboards; // expected results *p_expectedOutputs = new float[10 * Nboards]; for( int n = 0; n < Nlabels; n++ ) { int thislabel = labels[n]; for( int i = 0; i < 10; i++ ) { (*p_expectedOutputs)[n*10+i] = -0.5; } (*p_expectedOutputs)[n*10+thislabel] = +0.5; } } void getStats( float ***boards, int N, int boardSize, float *p_mean, float *p_thismax ) { // get mean of the dataset int count = 0; float thismax = 0; float sum = 0; for( int n = 0; n < N; n++ ) { for( int i = 0; i < boardSize; i++ ) { for( int j = 0; j < boardSize; j++ ) { count++; sum += boards[n][i][j]; thismax = max( thismax, boards[n][i][j] ); } } } *p_mean = sum / count; *p_thismax = thismax; } void normalize( float ***boards, int N, int boardSize, double mean, double thismax ) { for( int n = 0; n < N; n++ ) { for( int i = 0; i < boardSize; i++ ) { for( int j = 0; j < boardSize; j++ ) { boards[n][i][j] = boards[n][i][j] / thismax - 0.1; } } } } class Config { public: string dataDir = "../data/mnist"; string trainSet = "train"; string testSet = "t10k"; int numTrain = 60000; int numTest = 10000; int batchSize = 128; int numEpochs = 2; float learningRate = 0.001f; int biased = 1; Config() { } }; void printAccuracy( string name, NeuralNet *net, float ***boards, int *labels, int batchSize, int N ) { if( N == 0 ) { return; } int testNumRight = 0; int numBatches = ( N + batchSize - 1 ) /batchSize; net->setBatchSize(batchSize); for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = N - batchStart; net->setBatchSize(thisBatchSize); } net->propagate( &(boards[batchStart][0][0]) ); float const*results = net->getResults(); int thisnumright = AccuracyHelper::calcNumRight( thisBatchSize, 10, &(labels[batchStart]), results ); // cout << name << " batch " << batch << ": numright " << thisnumright << "/" << batchSize << endl; testNumRight += thisnumright; } // cout << "boards interval: " << ( &(boards[1][0][0]) - &(boards[0][0][0])) << endl; // cout << "labels interval: " << ( &(labels[1]) - &(labels[0])) << endl; cout << name << " overall: " << testNumRight << "/" << N << endl; } void go(Config config) { Timer timer; int boardSize; float ***boardsFloat = 0; int *labels = 0; float *expectedOutputs = 0; float ***boardsTest = 0; int *labelsTest = 0; float *expectedOutputsTest = 0; int N; loadMnist( config.dataDir, config.trainSet, &N, &boardSize, &boardsFloat, &labels, &expectedOutputs ); int Ntest; loadMnist( config.dataDir, config.testSet, &Ntest, &boardSize, &boardsTest, &labelsTest, &expectedOutputsTest ); float mean; float thismax; // getStats( boardsFloat, config.numTrain, boardSize, &mean, &thismax ); mean = 33; thismax = 255; cout << " board stats mean " << mean << " max " << thismax << " boardSize " << boardSize << endl; normalize( boardsFloat, config.numTrain, boardSize, mean, thismax ); normalize( boardsTest, config.numTest, boardSize, mean, thismax ); timer.timeCheck("after load images"); int numToTrain = config.numTrain; const int batchSize = config.batchSize; NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(boardSize)->instance(); net->convolutionalMaker()->numFilters(10)->filterSize(boardSize)->tanh()->biased(config.biased)->insert(); net->squareLossMaker()->insert(); // if( FileHelper::exists("weights.dat" ) ){ // int fileSize; // unsigned char * data = FileHelper::readBinary( "weights.dat", &fileSize ); // cout << "read data from file " << fileSize << " bytes" << endl; // for( int i = 0; i < net->layers[1]->getWeightsSize(); i++ ) { // net->layers[1]->weights[i] = reinterpret_cast<float *>(data)[i]; // } // delete [] data; // data = FileHelper::readBinary( "biasweights.dat", &fileSize ); // cout << "read data from file " << fileSize << " bytes" << endl; // for( int i = 0; i < net->layers[1]->getBiasWeightsSize(); i++ ) { // dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights[i] = reinterpret_cast<float *>(data)[i]; // } // } // net->print(); cout << " numToTrain " << numToTrain << " batchsize " << batchSize << " learningrate " << config.learningRate << endl; net->setBatchSize(batchSize); for( int epoch = 0; epoch < config.numEpochs; epoch++ ) { float loss = net->epochMaker() ->learningRate(config.learningRate) ->batchSize(batchSize) ->numExamples(numToTrain) ->inputData(&(boardsFloat[0][0][0])) ->expectedOutputs(expectedOutputs) ->run(); cout << " loss L: " << loss << endl; int trainNumRight = 0; timer.timeCheck("after epoch"); // net->print(); printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain ); printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest ); timer.timeCheck("after tests"); } //float const*results = net->getResults( net->getNumLayers() - 1 ); timer.timeCheck("after learning"); printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest ); // printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain ); timer.timeCheck("after tests"); int numBatches = ( config.numTest + config.batchSize - 1 ) / config.batchSize; int totalNumber = 0; int totalNumRight = 0; net->setBatchSize( config.batchSize ); for( int batch = 0; batch < numBatches && config.numTest > 0; batch++ ) { int batchStart = batch * config.batchSize; int thisBatchSize = config.batchSize; if( batch == numBatches - 1 ) { thisBatchSize = config.numTest - batchStart; net->setBatchSize( thisBatchSize ); } net->propagate( &(boardsTest[batchStart][0][0]) ); float const*resultsTest = net->getResults(); totalNumber += thisBatchSize; totalNumRight += AccuracyHelper::calcNumRight( thisBatchSize, 10, &(labelsTest[batchStart]), resultsTest ); } if( totalNumber > 0 ) cout << "test accuracy : " << totalNumRight << "/" << totalNumber << endl; EXPECT_LT( 80, totalNumRight * 100 / totalNumber ); // if( config.numEpochs >= 10 ) { // FileHelper::writeBinary( "weights.dat", reinterpret_cast<unsigned char *>(net->layers[1]->weights), // net->layers[1]->getWeightsSize() * sizeof(float) ); // cout << "wrote weights to file " << endl; // FileHelper::writeBinary( "biasweights.dat", reinterpret_cast<unsigned char *>(dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights), // dynamic_cast<ConvolutionalLayer*>(net->layers[1])->getBiasWeightsSize() * sizeof(float) ); // } delete net; delete[] expectedOutputsTest; delete[] labelsTest; BoardsHelper::deleteBoards( &boardsTest, Ntest, boardSize ); delete[] expectedOutputs; delete[] labels; BoardsHelper::deleteBoards( &boardsFloat, N, boardSize ); } TEST( testmnistlearn_unit, main ) { Config config; go( config ); } <commit_msg>remove boardpng from testmnistlearning_unit<commit_after>#include <iostream> using namespace std; #include "gtest/gtest.h" #include "BoardHelper.h" #include "MnistLoader.h" // #include "BoardPng.h" #include "Timer.h" #include "NeuralNet.h" #include "AccuracyHelper.h" #include "stringhelper.h" #include "FileHelper.h" void loadMnist( string mnistDir, string setName, int *p_N, int *p_boardSize, float ****p_images, int **p_labels, float **p_expectedOutputs ) { int boardSize; int Nboards; int Nlabels; // images int ***boards = MnistLoader::loadImages( mnistDir, setName, &Nboards, &boardSize ); int *labels = MnistLoader::loadLabels( mnistDir, setName, &Nlabels ); if( Nboards != Nlabels ) { throw runtime_error("mismatch between number of boards, and number of labels " + toString(Nboards ) + " vs " + toString(Nlabels ) ); } cout << "loaded " << Nboards << " boards. " << endl; // MnistLoader::shuffle( boards, labels, Nboards, boardSize ); float ***boardsFloat = BoardsHelper::allocateBoardsFloats( Nboards, boardSize ); BoardsHelper::copyBoards( boardsFloat, boards, Nboards, boardSize ); BoardsHelper::deleteBoards( &boards, Nboards, boardSize ); *p_images = boardsFloat; *p_labels = labels; *p_boardSize = boardSize; *p_N = Nboards; // expected results *p_expectedOutputs = new float[10 * Nboards]; for( int n = 0; n < Nlabels; n++ ) { int thislabel = labels[n]; for( int i = 0; i < 10; i++ ) { (*p_expectedOutputs)[n*10+i] = -0.5; } (*p_expectedOutputs)[n*10+thislabel] = +0.5; } } void getStats( float ***boards, int N, int boardSize, float *p_mean, float *p_thismax ) { // get mean of the dataset int count = 0; float thismax = 0; float sum = 0; for( int n = 0; n < N; n++ ) { for( int i = 0; i < boardSize; i++ ) { for( int j = 0; j < boardSize; j++ ) { count++; sum += boards[n][i][j]; thismax = max( thismax, boards[n][i][j] ); } } } *p_mean = sum / count; *p_thismax = thismax; } void normalize( float ***boards, int N, int boardSize, double mean, double thismax ) { for( int n = 0; n < N; n++ ) { for( int i = 0; i < boardSize; i++ ) { for( int j = 0; j < boardSize; j++ ) { boards[n][i][j] = boards[n][i][j] / thismax - 0.1; } } } } class Config { public: string dataDir = "../data/mnist"; string trainSet = "train"; string testSet = "t10k"; int numTrain = 60000; int numTest = 10000; int batchSize = 128; int numEpochs = 2; float learningRate = 0.001f; int biased = 1; Config() { } }; void printAccuracy( string name, NeuralNet *net, float ***boards, int *labels, int batchSize, int N ) { if( N == 0 ) { return; } int testNumRight = 0; int numBatches = ( N + batchSize - 1 ) /batchSize; net->setBatchSize(batchSize); for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = N - batchStart; net->setBatchSize(thisBatchSize); } net->propagate( &(boards[batchStart][0][0]) ); float const*results = net->getResults(); int thisnumright = AccuracyHelper::calcNumRight( thisBatchSize, 10, &(labels[batchStart]), results ); // cout << name << " batch " << batch << ": numright " << thisnumright << "/" << batchSize << endl; testNumRight += thisnumright; } // cout << "boards interval: " << ( &(boards[1][0][0]) - &(boards[0][0][0])) << endl; // cout << "labels interval: " << ( &(labels[1]) - &(labels[0])) << endl; cout << name << " overall: " << testNumRight << "/" << N << endl; } void go(Config config) { Timer timer; int boardSize; float ***boardsFloat = 0; int *labels = 0; float *expectedOutputs = 0; float ***boardsTest = 0; int *labelsTest = 0; float *expectedOutputsTest = 0; int N; loadMnist( config.dataDir, config.trainSet, &N, &boardSize, &boardsFloat, &labels, &expectedOutputs ); int Ntest; loadMnist( config.dataDir, config.testSet, &Ntest, &boardSize, &boardsTest, &labelsTest, &expectedOutputsTest ); float mean; float thismax; // getStats( boardsFloat, config.numTrain, boardSize, &mean, &thismax ); mean = 33; thismax = 255; cout << " board stats mean " << mean << " max " << thismax << " boardSize " << boardSize << endl; normalize( boardsFloat, config.numTrain, boardSize, mean, thismax ); normalize( boardsTest, config.numTest, boardSize, mean, thismax ); timer.timeCheck("after load images"); int numToTrain = config.numTrain; const int batchSize = config.batchSize; NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(boardSize)->instance(); net->convolutionalMaker()->numFilters(10)->filterSize(boardSize)->tanh()->biased(config.biased)->insert(); net->squareLossMaker()->insert(); // if( FileHelper::exists("weights.dat" ) ){ // int fileSize; // unsigned char * data = FileHelper::readBinary( "weights.dat", &fileSize ); // cout << "read data from file " << fileSize << " bytes" << endl; // for( int i = 0; i < net->layers[1]->getWeightsSize(); i++ ) { // net->layers[1]->weights[i] = reinterpret_cast<float *>(data)[i]; // } // delete [] data; // data = FileHelper::readBinary( "biasweights.dat", &fileSize ); // cout << "read data from file " << fileSize << " bytes" << endl; // for( int i = 0; i < net->layers[1]->getBiasWeightsSize(); i++ ) { // dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights[i] = reinterpret_cast<float *>(data)[i]; // } // } // net->print(); cout << " numToTrain " << numToTrain << " batchsize " << batchSize << " learningrate " << config.learningRate << endl; net->setBatchSize(batchSize); for( int epoch = 0; epoch < config.numEpochs; epoch++ ) { float loss = net->epochMaker() ->learningRate(config.learningRate) ->batchSize(batchSize) ->numExamples(numToTrain) ->inputData(&(boardsFloat[0][0][0])) ->expectedOutputs(expectedOutputs) ->run(); cout << " loss L: " << loss << endl; int trainNumRight = 0; timer.timeCheck("after epoch"); // net->print(); printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain ); printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest ); timer.timeCheck("after tests"); } //float const*results = net->getResults( net->getNumLayers() - 1 ); timer.timeCheck("after learning"); printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest ); // printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain ); timer.timeCheck("after tests"); int numBatches = ( config.numTest + config.batchSize - 1 ) / config.batchSize; int totalNumber = 0; int totalNumRight = 0; net->setBatchSize( config.batchSize ); for( int batch = 0; batch < numBatches && config.numTest > 0; batch++ ) { int batchStart = batch * config.batchSize; int thisBatchSize = config.batchSize; if( batch == numBatches - 1 ) { thisBatchSize = config.numTest - batchStart; net->setBatchSize( thisBatchSize ); } net->propagate( &(boardsTest[batchStart][0][0]) ); float const*resultsTest = net->getResults(); totalNumber += thisBatchSize; totalNumRight += AccuracyHelper::calcNumRight( thisBatchSize, 10, &(labelsTest[batchStart]), resultsTest ); } if( totalNumber > 0 ) cout << "test accuracy : " << totalNumRight << "/" << totalNumber << endl; EXPECT_LT( 80, totalNumRight * 100 / totalNumber ); // if( config.numEpochs >= 10 ) { // FileHelper::writeBinary( "weights.dat", reinterpret_cast<unsigned char *>(net->layers[1]->weights), // net->layers[1]->getWeightsSize() * sizeof(float) ); // cout << "wrote weights to file " << endl; // FileHelper::writeBinary( "biasweights.dat", reinterpret_cast<unsigned char *>(dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights), // dynamic_cast<ConvolutionalLayer*>(net->layers[1])->getBiasWeightsSize() * sizeof(float) ); // } delete net; delete[] expectedOutputsTest; delete[] labelsTest; BoardsHelper::deleteBoards( &boardsTest, Ntest, boardSize ); delete[] expectedOutputs; delete[] labels; BoardsHelper::deleteBoards( &boardsFloat, N, boardSize ); } TEST( testmnistlearn_unit, main ) { Config config; go( config ); } <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__ #include <stan/agrad/partials_vari.hpp> #include <stan/math/error_handling.hpp> #include <stan/math.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/distributions/univariate/continuous/uniform.hpp> namespace stan { namespace prob { template<bool propto, typename T_y, typename T_loc, typename T_scale> typename return_type<T_y,T_loc,T_scale>::type von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) { static char const* const function = "stan::prob::von_mises_log(%1%)"; // check if any vectors are zero length if (!(stan::length(y) && stan::length(mu) && stan::length(kappa))) return 0.0; using stan::is_constant_struct; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_greater; using stan::math::check_nonnegative; using stan::math::check_consistent_sizes; using stan::math::value_of; // Result accumulator. double logp = 0.0; // Validate arguments. if (!check_finite(function, y, "Random variable", &logp)) return logp; if(!check_finite(function, mu, "Location paramter", &logp)) return logp; if(!check_finite(function, kappa, "Scale parameter", &logp)) return logp; if(!check_positive(function, kappa, "Scale parameter", &logp)) return logp; if(!check_consistent_sizes(function, y, mu, kappa, "Random variable", "Location parameter", "Scale parameter", &logp)) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_loc,T_scale>::value) return logp; // Determine constants. const bool y_const = is_constant_struct<T_y>::value; const bool mu_const = is_constant_struct<T_loc>::value; const bool kappa_const = is_constant_struct<T_scale>::value; // Determine which expensive computations to perform. const bool compute_bessel0 = include_summand<propto,T_scale>::value; const bool compute_bessel1 = !kappa_const; const double TWO_PI = 2.0 * stan::math::pi(); // Wrap scalars into vector views. VectorView<const T_y> y_vec(y); VectorView<const T_loc> mu_vec(mu); VectorView<const T_scale> kappa_vec(kappa); DoubleVectorView<true,is_vector<T_scale>::value> kappa_dbl(length(kappa)); DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_bessel0(length(kappa)); for (size_t i = 0; i < length(kappa); i++) { kappa_dbl[i] = value_of(kappa_vec[i]); if (include_summand<propto,T_scale>::value) log_bessel0[i] = log(boost::math::cyl_bessel_i(0, value_of(kappa_vec[i]))); } agrad::OperandsAndPartials<T_y, T_loc, T_scale> oap(y, mu, kappa); size_t N = max_size(y, mu, kappa); for (size_t n = 0; n < N; n++) { // Extract argument values. const double y_ = value_of(y_vec[n]); const double y_dbl = y_ - std::floor(y_ / TWO_PI) * TWO_PI; const double mu_dbl = value_of(mu_vec[n]); // Reusable values. double bessel0 = 0; if (compute_bessel0) bessel0 = boost::math::cyl_bessel_i(0, kappa_dbl[n]); double bessel1 = 0; if (compute_bessel1) bessel1 = boost::math::cyl_bessel_i(-1, kappa_dbl[n]); const double kappa_sin = kappa_dbl[n] * std::sin(mu_dbl - y_dbl); const double kappa_cos = kappa_dbl[n] * std::cos(mu_dbl - y_dbl); // Log probability. if (include_summand<propto>::value) logp -= LOG_TWO_PI; if (include_summand<propto,T_scale>::value) logp -= log_bessel0[n]; if (include_summand<propto,T_y,T_loc,T_scale>::value) logp += kappa_cos; // Gradient. if (!y_const) oap.d_x1[n] += kappa_sin; if (!mu_const) oap.d_x2[n] -= kappa_sin; if (!kappa_const) oap.d_x3[n] += kappa_cos / kappa_dbl[n] - bessel1 / bessel0; } return oap.to_var(logp); } template<typename T_y, typename T_loc, typename T_scale> inline typename return_type<T_y,T_loc,T_scale>::type von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) { return von_mises_log<false>(y, mu, kappa); } template <class RNG> inline double von_mises_rng(const double mu, const double kappa, RNG& rng) { using boost::variate_generator; using stan::prob::uniform_rng; static const char* function = "stan::prob::von_mises_rng(%1%)"; stan::math::check_finite(function,kappa,"inverse of variance"); stan::math::check_positive(function,kappa,"inverse of variance"); double r = 1 + pow((1 + 4 * kappa * kappa), 0.5); double rho = 0.5 * (r - pow(2 * r, 0.5)) / kappa; double delta = 0.5 * (1 + rho * rho) / rho; bool done = 0; double W; while (!done) { double Z = std::cos(stan::math::pi() * uniform_rng(0.0, 1.0, rng)); W = (1 + delta * Z) / (delta + Z); double Y = kappa * (delta - W); double U2 = uniform_rng(0.0, 1.0, rng); done = Y * (2 - Y) - U2 > 0; if(!done) done = log(Y / U2) + 1 - Y >= 0; } double U3 = uniform_rng(0.0, 1.0, rng) - 0.5; double sign = ((U3 > 0) - (U3 < 0)); return mu + sign * std::acos(W); } } } #endif <commit_msg>Update von_mises.hpp<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__ #include <stan/agrad/partials_vari.hpp> #include <stan/math/error_handling.hpp> #include <stan/math.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/distributions/univariate/continuous/uniform.hpp> namespace stan { namespace prob { template<bool propto, typename T_y, typename T_loc, typename T_scale> typename return_type<T_y,T_loc,T_scale>::type von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) { static char const* const function = "stan::prob::von_mises_log(%1%)"; // check if any vectors are zero length if (!(stan::length(y) && stan::length(mu) && stan::length(kappa))) return 0.0; using stan::is_constant_struct; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_greater; using stan::math::check_nonnegative; using stan::math::check_consistent_sizes; using stan::math::value_of; // Result accumulator. double logp = 0.0; // Validate arguments. if (!check_finite(function, y, "Random variable", &logp)) return logp; if(!check_finite(function, mu, "Location paramter", &logp)) return logp; if(!check_finite(function, kappa, "Scale parameter", &logp)) return logp; if(!check_positive(function, kappa, "Scale parameter", &logp)) return logp; if(!check_consistent_sizes(function, y, mu, kappa, "Random variable", "Location parameter", "Scale parameter", &logp)) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_y,T_loc,T_scale>::value) return logp; // Determine constants. const bool y_const = is_constant_struct<T_y>::value; const bool mu_const = is_constant_struct<T_loc>::value; const bool kappa_const = is_constant_struct<T_scale>::value; // Determine which expensive computations to perform. const bool compute_bessel0 = include_summand<propto,T_scale>::value; const bool compute_bessel1 = !kappa_const; const double TWO_PI = 2.0 * stan::math::pi(); // Wrap scalars into vector views. VectorView<const T_y> y_vec(y); VectorView<const T_loc> mu_vec(mu); VectorView<const T_scale> kappa_vec(kappa); DoubleVectorView<true,is_vector<T_scale>::value> kappa_dbl(length(kappa)); DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_bessel0(length(kappa)); for (size_t i = 0; i < length(kappa); i++) { kappa_dbl[i] = value_of(kappa_vec[i]); if (include_summand<propto,T_scale>::value) log_bessel0[i] = log(boost::math::cyl_bessel_i(0, value_of(kappa_vec[i]))); } agrad::OperandsAndPartials<T_y, T_loc, T_scale> oap(y, mu, kappa); size_t N = max_size(y, mu, kappa); for (size_t n = 0; n < N; n++) { // Extract argument values. const double y_ = value_of(y_vec[n]); const double y_dbl = y_ - std::floor(y_ / TWO_PI) * TWO_PI; const double mu_dbl = value_of(mu_vec[n]); // Reusable values. double bessel0 = 0; if (compute_bessel0) bessel0 = boost::math::cyl_bessel_i(0, kappa_dbl[n]); double bessel1 = 0; if (compute_bessel1) bessel1 = boost::math::cyl_bessel_i(-1, kappa_dbl[n]); const double kappa_sin = kappa_dbl[n] * std::sin(mu_dbl - y_dbl); const double kappa_cos = kappa_dbl[n] * std::cos(mu_dbl - y_dbl); // Log probability. if (include_summand<propto>::value) logp -= LOG_TWO_PI; if (include_summand<propto,T_scale>::value) logp -= log_bessel0[n]; if (include_summand<propto,T_y,T_loc,T_scale>::value) logp += kappa_cos; // Gradient. if (!y_const) oap.d_x1[n] += kappa_sin; if (!mu_const) oap.d_x2[n] -= kappa_sin; if (!kappa_const) oap.d_x3[n] += kappa_cos / kappa_dbl[n] - bessel1 / bessel0; } return oap.to_var(logp); } template<typename T_y, typename T_loc, typename T_scale> inline typename return_type<T_y,T_loc,T_scale>::type von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) { return von_mises_log<false>(y, mu, kappa); } template <class RNG> inline double von_mises_rng(const double mu, const double kappa, RNG& rng) { using boost::variate_generator; using stan::prob::uniform_rng; static const char* function = "stan::prob::von_mises_rng(%1%)"; stan::math::check_finite(function,kappa,"inverse of variance"); stan::math::check_positive(function,kappa,"inverse of variance"); double r = 1 + pow((1 + 4 * kappa * kappa), 0.5); double rho = 0.5 * (r - pow(2 * r, 0.5)) / kappa; double delta = 0.5 * (1 + rho * rho) / rho; bool done = 0; double W; while (!done) { double Z = std::cos(stan::math::pi() * uniform_rng(0.0, 1.0, rng)); W = (1 + delta * Z) / (delta + Z); double Y = kappa * (delta - W); double U2 = uniform_rng(0.0, 1.0, rng); done = Y * (2 - Y) - U2 > 0; if(!done) done = log(Y / U2) + 1 - Y >= 0; } double U3 = uniform_rng(0.0, 1.0, rng) - 0.5; double sign = ((U3 >= 0) - (U3 <= 0)); return mu + sign * std::acos(W); } } } #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <gmock/gmock.h> #include "TriggerDetector.h" using ::testing::Return; class ExampleTriggerDetector : public TriggerDetector { public: ExampleTriggerDetector(void) : TriggerDetector(NULL) { setTrigger(timeLimit, 2, &ExampleTriggerDetector::isProc1, &ExampleTriggerDetector::isProc2); } static int timeLimit; private: bool isProc1(void) { return true; } bool isProc2(void) { return true; } }; int ExampleTriggerDetector::timeLimit = 2; class TriggerDetectorTest : public testing::Test { public: ExampleTriggerDetector *object; protected: virtual void SetUp() { object = new ExampleTriggerDetector(); } }; TEST_F(TriggerDetectorTest, TestIsPosing) { ASSERT_FALSE(object->isPosing()); ASSERT_TRUE(object->isPosing()); ASSERT_FALSE(object->isPosing()); sleep(ExampleTriggerDetector::timeLimit - 1); ASSERT_TRUE(object->isPosing()); } TEST_F(TriggerDetectorTest, TestIsPosingError) { ASSERT_FALSE(object->isPosing()); ASSERT_FALSE(object->isPosing()); } TEST_F(TriggerDetectorTest, TestIsPosingErrorTimeLimit) { ASSERT_FALSE(object->isPosing()); sleep(ExampleTriggerDetector::timeLimit + 1); ASSERT_FALSE(object->isPosing()); } <commit_msg>small test fix<commit_after>#include <gtest/gtest.h> #include "TriggerDetector.h" #define TIMELIMIT 2 class ExampleTriggerDetector : public TriggerDetector { public: ExampleTriggerDetector(void) : TriggerDetector(NULL) { setTrigger(TIMELIMIT, 3, &ExampleTriggerDetector::isProc, &ExampleTriggerDetector::isProc, &ExampleTriggerDetector::isProc); } private: bool isProc(void) { return true; } }; class ExampleFailureTriggerDetector : public TriggerDetector { public: ExampleFailureTriggerDetector(void) : TriggerDetector(NULL) { setTrigger(TIMELIMIT, 2, &ExampleFailureTriggerDetector::isProc1, &ExampleFailureTriggerDetector::isProc2); } private: bool isProc1(void) { return true; } bool isProc2(void) { return false; } }; class TriggerDetectorTest : public testing::Test { public: ExampleTriggerDetector *object; ExampleFailureTriggerDetector *object2; protected: virtual void SetUp() { object = new ExampleTriggerDetector(); object2 = new ExampleFailureTriggerDetector(); } virtual void TearDown() { delete object; delete object2; } }; TEST_F(TriggerDetectorTest, TestIsPosing) { // 1週目 ASSERT_FALSE(object->isPosing()); ASSERT_FALSE(object->isPosing()); ASSERT_TRUE(object->isPosing()); // 2週目 ASSERT_FALSE(object->isPosing()); sleep(TIMELIMIT - 1); ASSERT_FALSE(object->isPosing()); ASSERT_TRUE(object->isPosing()); } TEST_F(TriggerDetectorTest, TestIsPosingError) { // 1週目 ASSERT_FALSE(object2->isPosing()); ASSERT_FALSE(object2->isPosing()); // 2週目 ASSERT_FALSE(object2->isPosing()); ASSERT_FALSE(object2->isPosing()); } TEST_F(TriggerDetectorTest, TestIsPosingErrorTimeLimit) { ASSERT_FALSE(object->isPosing()); ASSERT_FALSE(object->isPosing()); sleep(TIMELIMIT + 1); ASSERT_FALSE(object->isPosing()); } <|endoftext|>
<commit_before>/******************************************************************************* * test/construction_test.cpp * * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <gtest/gtest.h> #include "util/util.hpp" #include "benchmark/algorithm.hpp" #include "huffman/huff_codes.hpp" #include "huffman/huff_decode.hpp" #include "huffman/huff_level_sizes_builder.hpp" #include "util/alphabet_util.hpp" #include "util/common.hpp" #include "util/decode.hpp" #include "util/file_util.hpp" using in_internal = typename input_type<memory_mode2::internal, 1>::type; using in_external = typename input_type<memory_mode2::external, 1>::type; using out_internal = typename output_type<memory_mode2::internal>::type; using out_external = typename output_type<memory_mode2::external>::type; TEST(wavelet, no_alphabet_reduction) { auto& algo_list = algorithm_list<in_internal, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); wavelet_structure bvz = a->compute_bitvector(vec.data(), vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } }); } } } TEST(wavelet, no_alphabet_reduction_external_input) { auto& algo_list = algorithm_list<in_external, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); in_external vec_external; for(const auto symbol : vec) vec_external.push_back(symbol); wavelet_structure bvz = a->compute_bitvector(vec_external, vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } }); } } } TEST(wavelet, no_alphabet_reduction_external_output) { auto& algo_list = algorithm_list<in_internal, out_external>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); auto bvz = a->compute_bitvector(vec.data(), vec.size() , levels); if(vec.size() == 0) { ASSERT_EQ(bvz.levels(), uint64_t(0)) << "Failure (Algorithm): " << a->name(); } else { if (a->is_tree()) { auto decoded_s = decode_wt(bvz, vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz, bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } } }); } } } TEST(wavelet, no_alphabet_reduction_external_input_output) { auto& algo_list = algorithm_list<in_external, out_external>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); in_external vec_external; for(const auto symbol : vec) vec_external.push_back(symbol); auto bvz = a->compute_bitvector(vec_external, vec.size() , levels); if(vec.size() == 0) { ASSERT_EQ(bvz.levels(), uint64_t(0)) << "Failure (Algorithm): " << a->name(); } else { if (a->is_tree()) { auto decoded_s = decode_wt(bvz, vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz, bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } } }); } } } /* TODO: Broken due to levels == 0 corner case TEST(construction, wavelet_alphabet_reduction) { auto& algo_list = algorithm_list::get_algorithm_list(); for (const auto& a : algo_list) { if (a->word_width() == 1 && !a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); auto max_char = reduce_alphabet(vec); uint64_t levels = levels_for_max_char(max_char); wavelet_structure bvz = a->compute_bitvector(&vec, vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } }); } } } */ TEST(huffman_shaped_wavelet, alphabet_reduction) { auto& algo_list = algorithm_list<in_internal, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); auto max_char = reduce_alphabet(vec); uint64_t levels = levels_for_max_char(max_char); auto bvz = a->compute_bitvector(vec.data(), vec.size() , levels); histogram<uint8_t> hist { vec.data(), vec.size() }; level_sizes_builder<uint8_t> builder { std::move(hist) }; if (a->is_tree()) { const auto codes = canonical_huff_codes<uint8_t, true>(builder); auto decoded_s = decode_wt_huff(bvz.bvs(), codes); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } else { const auto codes = canonical_huff_codes<uint8_t, false>(builder); auto decoded_s = decode_wm_huff(bvz.bvs(), codes); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } }); } } } /******************************************************************************/ <commit_msg>Fix construction tests<commit_after>/******************************************************************************* * test/construction_test.cpp * * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <gtest/gtest.h> #include "util/util.hpp" #include "benchmark/algorithm.hpp" #include "huffman/huff_codes.hpp" #include "huffman/huff_decode.hpp" #include "huffman/huff_level_sizes_builder.hpp" #include "util/alphabet_util.hpp" #include "util/common.hpp" #include "util/decode.hpp" #include "util/file_util.hpp" using in_internal = typename input_type<memory_mode::internal, 1>::type; using in_external = typename input_type<memory_mode::external, 1>::type; using out_internal = typename output_type<memory_mode::internal>::type; using out_external = typename output_type<memory_mode::external>::type; TEST(wavelet, no_alphabet_reduction) { auto& algo_list = algorithm_list<in_internal, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); wavelet_structure bvz = a->compute_bitvector(vec.data(), vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } }); } } } TEST(wavelet, no_alphabet_reduction_external_input) { auto& algo_list = algorithm_list<in_external, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); in_external vec_external; for(const auto symbol : vec) vec_external.push_back(symbol); wavelet_structure bvz = a->compute_bitvector(vec_external, vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } }); } } } TEST(wavelet, no_alphabet_reduction_external_output) { auto& algo_list = algorithm_list<in_internal, out_external>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); auto bvz = a->compute_bitvector(vec.data(), vec.size() , levels); if(vec.size() == 0) { ASSERT_EQ(bvz.levels(), uint64_t(0)) << "Failure (Algorithm): " << a->name(); } else { if (a->is_tree()) { auto decoded_s = decode_wt(bvz, vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz, bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } } }); } } } TEST(wavelet, no_alphabet_reduction_external_input_output) { auto& algo_list = algorithm_list<in_external, out_external>::get_algorithm_list(); for (const auto& a : algo_list) { if (!a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); uint64_t levels = no_reduction_alphabet(vec); in_external vec_external; for(const auto symbol : vec) vec_external.push_back(symbol); auto bvz = a->compute_bitvector(vec_external, vec.size() , levels); if(vec.size() == 0) { ASSERT_EQ(bvz.levels(), uint64_t(0)) << "Failure (Algorithm): " << a->name(); } else { if (a->is_tree()) { auto decoded_s = decode_wt(bvz, vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz, bvz.zeros(), vec.size()); ASSERT_EQ(s, decoded_s) << "Failure (Algorithm): " << a->name(); } } }); } } } /* TODO: Broken due to levels == 0 corner case TEST(construction, wavelet_alphabet_reduction) { auto& algo_list = algorithm_list::get_algorithm_list(); for (const auto& a : algo_list) { if (a->word_width() == 1 && !a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); auto max_char = reduce_alphabet(vec); uint64_t levels = levels_for_max_char(max_char); wavelet_structure bvz = a->compute_bitvector(&vec, vec.size() , levels); if (a->is_tree()) { auto decoded_s = decode_wt(bvz.bvs(), vec.size()); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } else { auto decoded_s = decode_wm(bvz.bvs(), bvz.zeros(), vec.size()); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } }); } } } */ TEST(huffman_shaped_wavelet, alphabet_reduction) { auto& algo_list = algorithm_list<in_internal, out_internal>::get_algorithm_list(); for (const auto& a : algo_list) { if (a->is_huffman_shaped()) { a->print_info(); test::roundtrip_batch([&](const std::string& s){ auto vec = std::vector<uint8_t>(s.begin(), s.end()); auto max_char = reduce_alphabet(vec); uint64_t levels = levels_for_max_char(max_char); auto bvz = a->compute_bitvector(vec.data(), vec.size() , levels); histogram<uint8_t> hist { vec.data(), vec.size() }; level_sizes_builder<uint8_t> builder { std::move(hist) }; if (a->is_tree()) { const auto codes = canonical_huff_codes<uint8_t, true>(builder); auto decoded_s = decode_wt_huff(bvz.bvs(), codes); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } else { const auto codes = canonical_huff_codes<uint8_t, false>(builder); auto decoded_s = decode_wm_huff(bvz.bvs(), codes); auto decoded_vec = std::vector<uint8_t>(decoded_s.begin(), decoded_s.end()); ASSERT_EQ(vec, decoded_vec) << "Failure (Algorithm): " << a->name(); } }); } } } /******************************************************************************/ <|endoftext|>
<commit_before><commit_msg>Fix typo. The right button is pressed when MK_RBUTTON is set.<commit_after><|endoftext|>
<commit_before>#include "translatorbasictest.h" #include <QDebug> #include "../../xpiks-qt/Translation/translationmanager.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "signalwaiter.h" QString TranslatorBasicTest::testName() { return QLatin1String("TranslatorBasicTest"); } void TranslatorBasicTest::setup() { // BUMP } int TranslatorBasicTest::doTest() { auto *translationManager = m_CommandManager->getTranslationManager(); QUrl pathToDict = getFilePathForTest("dicts-for-tests/eng_fin.ifo"); bool success = translationManager->addDictionary(pathToDict); VERIFY(success, "Failed to add dictionary"); translationManager->setSelectedDictionaryIndex(0); SignalWaiter waiter; QObject::connect(translationManager, SIGNAL(shortTranslationChanged()), &waiter, SIGNAL(finished())); translationManager->setQuery("test"); if (!waiter.wait()) { VERIFY(false, "Timeout for waiting for translation"); } VERIFY(!translationManager->getFullTranslation().simplified().isEmpty(), "Full translation is empty"); VERIFY(!translationManager->getShortTranslation().simplified().isEmpty(), "Short translation is empty"); qInfo() << "Translation arrived" << translationManager->getFullTranslation(); return true; } <commit_msg>Fixed typo<commit_after>#include "translatorbasictest.h" #include <QDebug> #include "../../xpiks-qt/Translation/translationmanager.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "signalwaiter.h" QString TranslatorBasicTest::testName() { return QLatin1String("TranslatorBasicTest"); } void TranslatorBasicTest::setup() { // BUMP } int TranslatorBasicTest::doTest() { auto *translationManager = m_CommandManager->getTranslationManager(); QUrl pathToDict = getFilePathForTest("dicts-for-tests/eng_fin.ifo"); bool success = translationManager->addDictionary(pathToDict); VERIFY(success, "Failed to add dictionary"); translationManager->setSelectedDictionaryIndex(0); SignalWaiter waiter; QObject::connect(translationManager, SIGNAL(shortTranslationChanged()), &waiter, SIGNAL(finished())); translationManager->setQuery("test"); if (!waiter.wait()) { VERIFY(false, "Timeout for waiting for translation"); } VERIFY(!translationManager->getFullTranslation().simplified().isEmpty(), "Full translation is empty"); VERIFY(!translationManager->getShortTranslation().simplified().isEmpty(), "Short translation is empty"); qInfo() << "Translation arrived" << translationManager->getFullTranslation(); return 0; } <|endoftext|>
<commit_before>#include <map> #include <queue> #include <set> #include <string> #include <vector> #include "aim.hpp" // Algorithm to be tested using Position = std::pair<std::size_t, std::size_t>; class State { int num_revolvings_; Position pos_; std::vector<bool> state_; public: State(int num_revolving, Position const& pos, std::vector<bool> const& state) : num_revolvings_(num_revolving), pos_(pos), state_(state) {} State(State&&) = default; State(State const&) = default; State& operator=(State&&) = default; State& operator=(State const&) = default; bool operator<(State const& other) const { return num_revolvings_ > other.num_revolvings_; } auto iters() const { return num_revolvings_; } auto const& pos() const { return pos_; } auto const& state() const { return state_; } }; int turns(std::vector<std::string> const& map_) { auto map = map_; Position start_pt {}; // Scan the map for doors and their status std::vector<bool> initial_state;//true = horizontal std::map<Position, std::size_t> state_ids; for (std::size_t j {} ; j != map.size() ; ++j) { for (std::size_t i {} ; i != map[0].size() ; ++i) { if (map[j][i] != 'O') { if (map[j][i] == 'S') { start_pt = std::make_pair(i,j); } continue; } state_ids.emplace(std::make_pair(i,j), initial_state.size()); initial_state.emplace_back(map[j][i+1] == '-'); } } // Redraw the map next to doors for (auto const& p : state_ids) { auto const& pos = p.first; map[pos.second ][pos.first-1] = '-'; map[pos.second ][pos.first+1] = '-'; map[pos.second-1][ pos.first] = '|'; map[pos.second+1][ pos.first] = '|'; } // Iterate in the map std::set<std::pair<Position, std::vector<bool>>> already_seen; std::priority_queue<State> nexts; nexts.emplace(0, start_pt, std::move(initial_state)); while(! nexts.empty()) { auto st = std::move(nexts.top()); nexts.pop(); if (st.pos().second >= map.size()) { continue; } if (st.pos().first >= map[0].size()) { continue; } if (map[st.pos().second][st.pos().first] == 'E') { return st.iters(); } if (! already_seen.insert(std::make_pair(st.pos(), st.state())).second) { continue; } // move up if (st.pos().second >= 1) { char const& cell = map[st.pos().second -1][st.pos().first]; switch (cell) { case '-': { Position door { st.pos().first >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second -1) }; if (st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = false; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first, st.pos().second -1), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); } break; } case '|': { Position door { st.pos().first >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second -1) }; if (st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); } break; } case ' ': case 'E': nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); break; } } // move down if (st.pos().second +1 < map.size()) { char const& cell = map[st.pos().second +1][st.pos().first]; switch (cell) { case '-': { Position door { st.pos().first >= 1 && map[st.pos().second +1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second +1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = false; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first, st.pos().second +1), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); } break; } case '|': { Position door { st.pos().first >= 1 && map[st.pos().second +1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second +1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); } break; } case ' ': case 'E': nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); break; } } // move left if (st.pos().first >= 1) { char const& cell = map[st.pos().second][st.pos().first -1]; switch (cell) { case '-': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first -1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); } break; } case '|': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first -1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = true; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first -1, st.pos().second), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); } break; } case ' ': case 'E': nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); break; } } // move right if (st.pos().first +1 < map[0].size()) { char const& cell = map[st.pos().second][st.pos().first +1]; switch (cell) { case '-': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first +1] == 'O' ? std::make_pair(st.pos().first +1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); } break; } case '|': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first +1] == 'O' ? std::make_pair(st.pos().first +1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = true; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first +1, st.pos().second), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); } break; } case ' ': case 'E': nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); break; } } } return -1; } <commit_msg>[topcoder-revolvingdoors] Not able to walk on start pt<commit_after>#include <map> #include <queue> #include <set> #include <string> #include <vector> #include "aim.hpp" // Algorithm to be tested using Position = std::pair<std::size_t, std::size_t>; class State { int num_revolvings_; Position pos_; std::vector<bool> state_; public: State(int num_revolving, Position const& pos, std::vector<bool> const& state) : num_revolvings_(num_revolving), pos_(pos), state_(state) {} State(State&&) = default; State(State const&) = default; State& operator=(State&&) = default; State& operator=(State const&) = default; bool operator<(State const& other) const { return num_revolvings_ > other.num_revolvings_; } auto iters() const { return num_revolvings_; } auto const& pos() const { return pos_; } auto const& state() const { return state_; } }; int turns(std::vector<std::string> const& map_) { auto map = map_; Position start_pt {}; Position end_pt {}; // Scan the map for doors and their status std::vector<bool> initial_state;//true = horizontal std::map<Position, std::size_t> state_ids; for (std::size_t j {} ; j != map.size() ; ++j) { for (std::size_t i {} ; i != map[0].size() ; ++i) { if (map[j][i] != 'O') { if (map[j][i] == 'S') { start_pt = std::make_pair(i,j); } else if (map[j][i] == 'E') { end_pt = std::make_pair(i,j); } continue; } state_ids.emplace(std::make_pair(i,j), initial_state.size()); initial_state.emplace_back(map[j][i+1] == '-'); } } // Redraw the map next to doors map[start_pt.second][start_pt.first] = ' '; map[end_pt.second][end_pt.first] = ' '; for (auto const& p : state_ids) { auto const& pos = p.first; map[pos.second ][pos.first-1] = '-'; map[pos.second ][pos.first+1] = '-'; map[pos.second-1][ pos.first] = '|'; map[pos.second+1][ pos.first] = '|'; } // Iterate in the map std::set<std::pair<Position, std::vector<bool>>> already_seen; std::priority_queue<State> nexts; nexts.emplace(0, start_pt, std::move(initial_state)); while(! nexts.empty()) { auto st = std::move(nexts.top()); nexts.pop(); if (st.pos().second >= map.size()) { continue; } if (st.pos().first >= map[0].size()) { continue; } if (st.pos() == end_pt) { return st.iters(); } if (! already_seen.insert(std::make_pair(st.pos(), st.state())).second) { continue; } // move up if (st.pos().second >= 1) { char const& cell = map[st.pos().second -1][st.pos().first]; switch (cell) { case '-': { Position door { st.pos().first >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second -1) }; if (st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = false; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first, st.pos().second -1), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); } break; } case '|': { Position door { st.pos().first >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second -1) }; if (st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); } break; } case ' ': nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second -1), st.state()); break; } } // move down if (st.pos().second +1 < map.size()) { char const& cell = map[st.pos().second +1][st.pos().first]; switch (cell) { case '-': { Position door { st.pos().first >= 1 && map[st.pos().second +1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second +1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = false; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first, st.pos().second +1), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); } break; } case '|': { Position door { st.pos().first >= 1 && map[st.pos().second +1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second +1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); } break; } case ' ': nexts.emplace(st.iters(), std::make_pair(st.pos().first, st.pos().second +1), st.state()); break; } } // move left if (st.pos().first >= 1) { char const& cell = map[st.pos().second][st.pos().first -1]; switch (cell) { case '-': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first -1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); } break; } case '|': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first -1] == 'O' ? std::make_pair(st.pos().first -1, st.pos().second -1) : std::make_pair(st.pos().first -1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = true; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first -1, st.pos().second), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); } break; } case ' ': nexts.emplace(st.iters(), std::make_pair(st.pos().first -1, st.pos().second), st.state()); break; } } // move right if (st.pos().first +1 < map[0].size()) { char const& cell = map[st.pos().second][st.pos().first +1]; switch (cell) { case '-': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first +1] == 'O' ? std::make_pair(st.pos().first +1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is opened { nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); } break; } case '|': { Position door { st.pos().second >= 1 && map[st.pos().second -1][st.pos().first +1] == 'O' ? std::make_pair(st.pos().first +1, st.pos().second -1) : std::make_pair(st.pos().first +1, st.pos().second +1) }; if (! st.state()[state_ids[door]]) //door is closed { auto state = st.state(); state[state_ids[door]] = true; nexts.emplace(st.iters() +1, std::make_pair(st.pos().first +1, st.pos().second), st.state()); } else { nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); } break; } case ' ': nexts.emplace(st.iters(), std::make_pair(st.pos().first +1, st.pos().second), st.state()); break; } } } return -1; } <|endoftext|>
<commit_before>// $Id: exact_solution.C,v 1.10 2005-04-10 20:15:27 spetersen Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "exact_solution.h" #include "transient_system.h" #include "fe.h" #include "quadrature_gauss.h" #include "fe_interface.h" #include "elem.h" ExactSolution::ExactSolution(EquationSystems& es) : _exact_value (NULL), _exact_deriv (NULL), _equation_systems(es), _mesh(es.get_mesh()) { // Initialize the _errors data structure which holds all // the eventual values of the error. for (unsigned int sys=0; sys<_equation_systems.n_systems(); ++sys) { // Reference to the system const System& system = _equation_systems(sys); // The name of the system const std::string& sys_name = system.name(); // The SystemErrorMap to be inserted ExactSolution::SystemErrorMap sem; for (unsigned int var=0; var<system.n_vars(); ++var) { // The name of this variable const std::string& var_name = system.variable_name(var); sem[var_name] = std::make_pair(0., 0.); } _errors[sys_name] = sem; } } void ExactSolution::attach_exact_value (Number fptr(const Point& p, const Parameters& parameters, const std::string& sys_name, const std::string& unknown_name)) { assert (fptr != NULL); _exact_value = fptr; } void ExactSolution::attach_exact_deriv (Gradient fptr(const Point& p, const Parameters& parameters, const std::string& sys_name, const std::string& unknown_name)) { assert (fptr != NULL); _exact_deriv = fptr; } std::pair<Number, Number>& ExactSolution::_check_inputs(const std::string& sys_name, const std::string& unknown_name) { // Be sure that an exact_value function has been attached if (_exact_value == NULL) { std::cerr << "Cannot compute error, you must provide a " << "function which computes the exact solution." << std::endl; error(); } // Make sure the requested sys_name exists. std::map<std::string, SystemErrorMap>::iterator sys_iter = _errors.find(sys_name); if (sys_iter == _errors.end()) { std::cerr << "Sorry, couldn't find the requested system." << std::endl; error(); } // Make sure the requested unknown_name exists. SystemErrorMap::iterator var_iter = (*sys_iter).second.find(unknown_name); if (var_iter == (*sys_iter).second.end()) { std::cerr << "Sorry, couldn't find the requested variable." << std::endl; error(); } // Return a reference to the proper error entry return (*var_iter).second; } void ExactSolution::compute_error(const std::string& sys_name, const std::string& unknown_name) { // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); this->_compute_error(sys_name, unknown_name, error_pair); } Number ExactSolution::l2_error(const std::string& sys_name, const std::string& unknown_name) { // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); // Return the square root of the first component of the // computed error. return std::sqrt(error_pair.first); } Number ExactSolution::h1_error(const std::string& sys_name, const std::string& unknown_name) { // Check to be sure the user has supplied the exact derivative function if (_exact_deriv == NULL) { std::cerr << "Cannot compute H1 error, you must provide a " << "function which computes the gradient of the exact solution." << std::endl; error(); } // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); // Return the square root of the sum of the computed errors. return std::sqrt(error_pair.first + error_pair.second); } void ExactSolution::_compute_error(const std::string& sys_name, const std::string& unknown_name, std::pair<Number, Number>& error_pair) { // Get a reference to the system whose error is being computed. const System& computed_system = _equation_systems.get_system (sys_name); // Get a reference to the dofmap for that system const DofMap& computed_dof_map = computed_system.get_dof_map(); // Zero the error before summation error_pair.first = 0.; error_pair.second = 0.; // get the EquationSystems parameters const Parameters& parameters = this->_equation_systems.parameters; // Get the current time, in case the exact solution depends on it. // Steady systems of equations do not have a time parameter, so this // routine needs to take that into account. // FIXME!!! // const Real time = 0.;//_equation_systems.parameter("time"); // Construct finite element object const unsigned int var = computed_system.variable_number(unknown_name); const FEType fe_type = computed_dof_map.variable_type(var); AutoPtr<FEBase> fe(FEBase::build(_mesh.mesh_dimension(), fe_type)); // Construct Quadrature rule based on default quadrature order QGauss qrule (_mesh.mesh_dimension(), fe_type.default_quadrature_order()); // Attach quadrature rule to FE object fe->attach_quadrature_rule (&qrule); // The Jacobian*weight at the quadrature points. const std::vector<Real>& JxW = fe->get_JxW(); // The value of the shape functions at the quadrature points // i.e. phi(i) = phi_values[i][qp] const std::vector<std::vector<Real> >& phi_values = fe->get_phi(); // The value of the shape function gradients at the quadrature points const std::vector<std::vector<RealGradient> >& dphi_values = fe->get_dphi(); // The XYZ locations (in physical space) of the quadrature points const std::vector<Point>& q_point = fe->get_xyz(); // The global degree of freedom indices associated // with the local degrees of freedom. std::vector<unsigned int> dof_indices; // // Begin the loop over the elements // // const_active_local_elem_iterator el (_mesh.elements_begin()); // const const_active_local_elem_iterator end_el (_mesh.elements_end()); MeshBase::const_element_iterator el = _mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = _mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { // Store a pointer to the element we are currently // working on. This allows for nicer syntax later. const Elem* elem = *el; // reinitialize the element-specific data // for the current element fe->reinit (elem); // Get the local to global degree of freedom maps computed_dof_map.dof_indices (elem, dof_indices, var); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // The number of shape functions const unsigned int n_sf = FEInterface::n_shape_functions (_mesh.mesh_dimension(), fe_type, elem->type()); assert (n_sf == dof_indices.size()); // // Begin the loop over the Quadrature points. // for (unsigned int qp=0; qp<n_qp; qp++) { // Real u_h = 0.; // RealGradient grad_u_h; Number u_h = 0.; #ifndef USE_COMPLEX_NUMBERS RealGradient grad_u_h; #else // Gradient grad_u_h; RealGradient grad_u_h_re; RealGradient grad_u_h_im; #endif // Compute solution values at the current // quadrature point. This reqiures a sum // over all the shape functions evaluated // at the quadrature point. for (unsigned int i=0; i<n_sf; i++) { // Values from current solution. u_h += phi_values[i][qp]*computed_system.current_solution (dof_indices[i]); #ifndef USE_COMPLEX_NUMBERS grad_u_h += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]); #else grad_u_h_re += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real(); grad_u_h_im += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag(); #endif } #ifdef USE_COMPLEX_NUMBERS Gradient grad_u_h (grad_u_h_re, grad_u_h_im); #endif // Compute the value of the error at this quadrature point // const Real val_error = (u_h - _exact_value(q_point[qp], const Number val_error = (u_h - _exact_value(q_point[qp], parameters, sys_name, unknown_name)); // Compute the value of the error in the gradient at this quadrature point // RealGradient grad_error; Gradient grad_error; if (_exact_deriv != NULL) { grad_error = (grad_u_h - _exact_deriv(q_point[qp], parameters, sys_name, unknown_name)); } // Add the squares of the error to each contribution error_pair.first += JxW[qp]*(val_error*val_error); error_pair.second += JxW[qp]*(grad_error*grad_error); } // end qp loop } // end element loop #ifdef HAVE_MPI if (libMesh::n_processors() > 1) { #ifndef USE_COMPLEX_NUMBERS std::vector<Real> local_errors(2); // Set local error entries. local_errors[0] = error_pair.first; local_errors[1] = error_pair.second; std::vector<Real> global_errors(2); MPI_Allreduce (&local_errors[0], &global_errors[0], local_errors.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); // Store result back in the pair error_pair.first = global_errors[0]; error_pair.second = global_errors[1]; // Sanity check assert (global_errors[0] >= local_errors[0]); assert (global_errors[1] >= local_errors[1]); #endif } #endif } <commit_msg>Removed unnecessary comments.<commit_after>// $Id: exact_solution.C,v 1.11 2005-05-05 22:19:51 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "exact_solution.h" #include "transient_system.h" #include "fe.h" #include "quadrature_gauss.h" #include "fe_interface.h" #include "elem.h" ExactSolution::ExactSolution(EquationSystems& es) : _exact_value (NULL), _exact_deriv (NULL), _equation_systems(es), _mesh(es.get_mesh()) { // Initialize the _errors data structure which holds all // the eventual values of the error. for (unsigned int sys=0; sys<_equation_systems.n_systems(); ++sys) { // Reference to the system const System& system = _equation_systems(sys); // The name of the system const std::string& sys_name = system.name(); // The SystemErrorMap to be inserted ExactSolution::SystemErrorMap sem; for (unsigned int var=0; var<system.n_vars(); ++var) { // The name of this variable const std::string& var_name = system.variable_name(var); sem[var_name] = std::make_pair(0., 0.); } _errors[sys_name] = sem; } } void ExactSolution::attach_exact_value (Number fptr(const Point& p, const Parameters& parameters, const std::string& sys_name, const std::string& unknown_name)) { assert (fptr != NULL); _exact_value = fptr; } void ExactSolution::attach_exact_deriv (Gradient fptr(const Point& p, const Parameters& parameters, const std::string& sys_name, const std::string& unknown_name)) { assert (fptr != NULL); _exact_deriv = fptr; } std::pair<Number, Number>& ExactSolution::_check_inputs(const std::string& sys_name, const std::string& unknown_name) { // Be sure that an exact_value function has been attached if (_exact_value == NULL) { std::cerr << "Cannot compute error, you must provide a " << "function which computes the exact solution." << std::endl; error(); } // Make sure the requested sys_name exists. std::map<std::string, SystemErrorMap>::iterator sys_iter = _errors.find(sys_name); if (sys_iter == _errors.end()) { std::cerr << "Sorry, couldn't find the requested system." << std::endl; error(); } // Make sure the requested unknown_name exists. SystemErrorMap::iterator var_iter = (*sys_iter).second.find(unknown_name); if (var_iter == (*sys_iter).second.end()) { std::cerr << "Sorry, couldn't find the requested variable." << std::endl; error(); } // Return a reference to the proper error entry return (*var_iter).second; } void ExactSolution::compute_error(const std::string& sys_name, const std::string& unknown_name) { // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); this->_compute_error(sys_name, unknown_name, error_pair); } Number ExactSolution::l2_error(const std::string& sys_name, const std::string& unknown_name) { // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); // Return the square root of the first component of the // computed error. return std::sqrt(error_pair.first); } Number ExactSolution::h1_error(const std::string& sys_name, const std::string& unknown_name) { // Check to be sure the user has supplied the exact derivative function if (_exact_deriv == NULL) { std::cerr << "Cannot compute H1 error, you must provide a " << "function which computes the gradient of the exact solution." << std::endl; error(); } // Check the inputs for validity, and get a reference // to the proper location to store the error std::pair<Number,Number>& error_pair = this->_check_inputs(sys_name, unknown_name); // Return the square root of the sum of the computed errors. return std::sqrt(error_pair.first + error_pair.second); } void ExactSolution::_compute_error(const std::string& sys_name, const std::string& unknown_name, std::pair<Number, Number>& error_pair) { // Get a reference to the system whose error is being computed. const System& computed_system = _equation_systems.get_system (sys_name); // Get a reference to the dofmap for that system const DofMap& computed_dof_map = computed_system.get_dof_map(); // Zero the error before summation error_pair.first = 0.; error_pair.second = 0.; // get the EquationSystems parameters const Parameters& parameters = this->_equation_systems.parameters; // Get the current time, in case the exact solution depends on it. // Steady systems of equations do not have a time parameter, so this // routine needs to take that into account. // FIXME!!! // const Real time = 0.;//_equation_systems.parameter("time"); // Construct finite element object const unsigned int var = computed_system.variable_number(unknown_name); const FEType fe_type = computed_dof_map.variable_type(var); AutoPtr<FEBase> fe(FEBase::build(_mesh.mesh_dimension(), fe_type)); // Construct Quadrature rule based on default quadrature order QGauss qrule (_mesh.mesh_dimension(), fe_type.default_quadrature_order()); // Attach quadrature rule to FE object fe->attach_quadrature_rule (&qrule); // The Jacobian*weight at the quadrature points. const std::vector<Real>& JxW = fe->get_JxW(); // The value of the shape functions at the quadrature points // i.e. phi(i) = phi_values[i][qp] const std::vector<std::vector<Real> >& phi_values = fe->get_phi(); // The value of the shape function gradients at the quadrature points const std::vector<std::vector<RealGradient> >& dphi_values = fe->get_dphi(); // The XYZ locations (in physical space) of the quadrature points const std::vector<Point>& q_point = fe->get_xyz(); // The global degree of freedom indices associated // with the local degrees of freedom. std::vector<unsigned int> dof_indices; // // Begin the loop over the elements // MeshBase::const_element_iterator el = _mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = _mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { // Store a pointer to the element we are currently // working on. This allows for nicer syntax later. const Elem* elem = *el; // reinitialize the element-specific data // for the current element fe->reinit (elem); // Get the local to global degree of freedom maps computed_dof_map.dof_indices (elem, dof_indices, var); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // The number of shape functions const unsigned int n_sf = FEInterface::n_shape_functions (_mesh.mesh_dimension(), fe_type, elem->type()); assert (n_sf == dof_indices.size()); // // Begin the loop over the Quadrature points. // for (unsigned int qp=0; qp<n_qp; qp++) { // Real u_h = 0.; // RealGradient grad_u_h; Number u_h = 0.; #ifndef USE_COMPLEX_NUMBERS RealGradient grad_u_h; #else // Gradient grad_u_h; RealGradient grad_u_h_re; RealGradient grad_u_h_im; #endif // Compute solution values at the current // quadrature point. This reqiures a sum // over all the shape functions evaluated // at the quadrature point. for (unsigned int i=0; i<n_sf; i++) { // Values from current solution. u_h += phi_values[i][qp]*computed_system.current_solution (dof_indices[i]); #ifndef USE_COMPLEX_NUMBERS grad_u_h += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]); #else grad_u_h_re += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).real(); grad_u_h_im += dphi_values[i][qp]*computed_system.current_solution (dof_indices[i]).imag(); #endif } #ifdef USE_COMPLEX_NUMBERS Gradient grad_u_h (grad_u_h_re, grad_u_h_im); #endif // Compute the value of the error at this quadrature point // const Real val_error = (u_h - _exact_value(q_point[qp], const Number val_error = (u_h - _exact_value(q_point[qp], parameters, sys_name, unknown_name)); // Compute the value of the error in the gradient at this quadrature point // RealGradient grad_error; Gradient grad_error; if (_exact_deriv != NULL) { grad_error = (grad_u_h - _exact_deriv(q_point[qp], parameters, sys_name, unknown_name)); } // Add the squares of the error to each contribution error_pair.first += JxW[qp]*(val_error*val_error); error_pair.second += JxW[qp]*(grad_error*grad_error); } // end qp loop } // end element loop #ifdef HAVE_MPI if (libMesh::n_processors() > 1) { #ifndef USE_COMPLEX_NUMBERS std::vector<Real> local_errors(2); // Set local error entries. local_errors[0] = error_pair.first; local_errors[1] = error_pair.second; std::vector<Real> global_errors(2); MPI_Allreduce (&local_errors[0], &global_errors[0], local_errors.size(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); // Store result back in the pair error_pair.first = global_errors[0]; error_pair.second = global_errors[1]; // Sanity check assert (global_errors[0] >= local_errors[0]); assert (global_errors[1] >= local_errors[1]); #endif } #endif } <|endoftext|>
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/cpu/hlo_xla_runtime_pipeline.h" #include <utility> #include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h" // from @llvm-project #include "mlir/Conversion/ComplexToStandard/ComplexToStandard.h" // from @llvm-project #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project #include "mlir/Conversion/TensorToLinalg/TensorToLinalgPass.h" // from @llvm-project #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" // from @llvm-project #include "mlir/Dialect/Arith/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Arith/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project #include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project #include "mlir/Dialect/Linalg/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/MemRef/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Shape/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Shape/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Tensor/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/xla/transforms/xla_passes.h" #include "tensorflow/compiler/xla/mlir/backends/cpu/transforms/passes.h" #include "tensorflow/compiler/xla/mlir/runtime/transforms/compiler.h" #include "tensorflow/compiler/xla/mlir_hlo/gml_st/interfaces/bufferizable_op_interface_impl.h" #include "tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/passes.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Dialect/mhlo/transforms/bufferizable_op_interface_impl.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Transforms/passes.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/tsl/platform/errors.h" #include "tensorflow/tsl/platform/logging.h" namespace xla { namespace cpu { namespace { using mlir::func::FuncOp; mlir::bufferization::OneShotBufferizationOptions GetBufferizationOptions() { using mlir::bufferization::BufferizationOptions; using mlir::bufferization::OneShotBufferizationOptions; OneShotBufferizationOptions options; options.bufferizeFunctionBoundaries = true; options.allowReturnAllocs = true; options.functionBoundaryTypeConversion = BufferizationOptions::LayoutMapOption::IdentityLayoutMap; options.unknownTypeConverterFn = [](mlir::Value value, unsigned memorySpace, const BufferizationOptions& options) { return mlir::bufferization::getMemRefTypeWithStaticIdentityLayout( value.getType().cast<mlir::TensorType>(), memorySpace); }; return options; } void AddSparsificationPasses(mlir::OpPassManager& pm) { pm.addNestedPass<FuncOp>(mlir::createLinalgGeneralizationPass()); pm.addNestedPass<FuncOp>( mlir::bufferization::createEmptyTensorToAllocTensorPass()); pm.addPass(mlir::bufferization::createTensorCopyInsertionPass( GetBufferizationOptions())); pm.addPass(mlir::createSparseTensorRewritePass()); pm.addPass(mlir::createSparsificationPass()); pm.addPass(mlir::createSparseTensorConversionPass()); pm.addPass(mlir::createDenseBufferizationPass(GetBufferizationOptions())); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createFinalizingBufferizePass()); } } // namespace // -------------------------------------------------------------------------- // // Assemble a HLO XLA Runtime pipeline to lower from HLO to Linalg on buffers. // -------------------------------------------------------------------------- // static Status CreateHloXlaPipeline( mlir::OpPassManager& pm, const HloXlaRuntimePipelineOptions& options) { // Resolve all shape constraints (e.g. broadcast constraints that can be // proved statically and changed to const witness) early to allow more // efficient broadcast operations moving. // Move up broadcasting operations to allow for more fusion opportunities. pm.addPass(mlir::createInlinerPass()); pm.addPass(mlir::mhlo::createExpandHloTuplesPass("main")); // TODO(b/233771980): Remove once custom_call doesn't use tuples. pm.addNestedPass<mlir::func::FuncOp>(mlir::mhlo::createFlattenTuplePass()); pm.addPass(createXlaAbiLegalizationPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeGeneralDotPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createBroadcastPropagationPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); // Transform HLO operations to Linalg. pm.addNestedPass<mlir::func::FuncOp>(mlir::mhlo::createLegalizeSortPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeControlFlowPass()); pm.addPass(::mlir::mhlo::createLegalizeToArithmeticPass()); // TODO(kramerb): Give THLO lowerings priority over linalg when it's ready for // concat, reduce and friends. pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeHloToLinalgPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeMHLOToTHLOPass()); // Lower index cast on tensors to tensor.generate. pm.addNestedPass<mlir::func::FuncOp>(mlir::createLowerIndexCastPass()); pm.addPass(mlir::mhlo::createConvertToSignlessPass()); // Transform scatter ops. pm.addNestedPass<mlir::func::FuncOp>( mlir::gml_st::createTransformScatterForCpuPass()); // Lower shape dialect to standard to enable linalg canonicalizations (e.g. // use linalg inputs instead of outputs for memref.dim operations). pm.addNestedPass<mlir::func::FuncOp>(mlir::createShapeSimplification()); pm.addNestedPass<mlir::func::FuncOp>(mlir::createShapeToShapeLowering()); pm.addPass(mlir::createConvertShapeToStandardPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertShapeConstraintsPass()); // Fuse Linalg on tensors operations. pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::memref::createResolveShapedTypeResultDimsPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::createLinalgElementwiseOpFusionPass()); pm.addPass(mlir::createReconcileUnrealizedCastsPass()); pm.addPass(mlir::createConvertTensorToLinalgPass()); // Detensorize SCF iter args. pm.addNestedPass<mlir::func::FuncOp>(mlir::createDetensorizeScfOpsPass()); // mhlo ops on unit tensors generate trivial linalg.generics, which // one-shot-bufferize generates unnecessary allocs for. The detensorize pass // replaces these linalg.generics with scalar ops. auto detensorize = mlir::createLinalgDetensorizePass(); if (detensorize->initializeOptions("aggressive-mode=true").failed()) { return tsl::errors::Internal("Failed to set up detensorize pass."); } pm.addNestedPass<mlir::func::FuncOp>(std::move(detensorize)); pm.addNestedPass<mlir::func::FuncOp>(mlir::createScalarizationPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createEmptyTensorToAllocTensorPass()); // Always run canonicalizer (which does dead code removal) before // bufferizing anything. pm.addPass(mlir::createCanonicalizerPass()); if (options.sparse_bufferization) { // Convert Sparse tensors. AddSparsificationPasses(pm); } else { pm.addPass(mlir::hlo::createOneShotBufferizePass()); } // Handle framework specific requirements for buffers and then insert // deallocations for temporary buffers. pm.addNestedPass<mlir::func::FuncOp>(mlir::createConvertLinalgToLoopsPass()); pm.addNestedPass<mlir::func::FuncOp>(mlir::gml_st::createGmlStToScfPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::bufferization::createBufferResultsToOutParamsPass()); if (options.outline_with_xla_framework) { pm.addPass(mlir::mhlo::CreateOutlineWithXLAFrameworkPass()); } pm.addPass(mlir::createInlinerPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createBufferDeallocationPass()); pm.addPass(mlir::createBufferizationToMemRefPass()); // Specialize linalg.matmul to linalg.dot, linalg.matvec or linalg.vecmat, // and immediately canonicalize to clean up not taken branches. // pm.addNestedPass<mlir::func::FuncOp>(CreateLinalgMatmulSpecializationPass()); pm.addPass(mlir::createCanonicalizerPass()); // Tile and vectorize linalg operation using Linalg Codegen Strategy. // pm.addNestedPass<mlir::func::FuncOp>(CreateCodegenStrategyForMatMulPass()); // TODO(tpopp): Move hits to mlir::hlo::createGenericHostToLLVMPass? pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertComplexToStandardPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); mlir::VectorTransferToSCFOptions vec_to_scf_options; vec_to_scf_options.unroll = true; pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertVectorToSCFPass(vec_to_scf_options)); return OkStatus(); } Status CreateHloXlaRuntimePipeline( xla::runtime::PassManager& passes, const HloXlaRuntimePipelineOptions& options) { return CreateHloXlaPipeline(*passes, options); } Status CreateDefaultHloXlaRuntimePipeline(xla::runtime::PassManager& passes) { HloXlaRuntimePipelineOptions options; return CreateHloXlaPipeline(*passes, options); } void RegisterHloXlaRuntimePipelineDialects( xla::runtime::DialectRegistry& dialects) { mlir::arith::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::bufferization::func_ext::registerBufferizableOpInterfaceExternalModels( *dialects); mlir::gml_st::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::linalg::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::mhlo::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::scf::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::shape::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::tensor::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::vector::registerBufferizableOpInterfaceExternalModels(*dialects); } static mlir::PassPipelineRegistration<> hlo_xla_runtime_pipeline( "hlo-xla-runtime-pipeline", "Convert HLO dialect to XLA Runtime compatible dialects", [](mlir::OpPassManager& pm) { HloXlaRuntimePipelineOptions options; Status status = CreateHloXlaPipeline(pm, options); if (!status.ok()) { LOG(FATAL) << "HLO-XLA Runtime pipeline failed with: " << status.error_message(); } }); static mlir::PassPipelineRegistration<> sparsification_pipeline( "hlo-xla-runtime-sparsification", "Sparsification passes from HLO-XLA Runtime pipeline", AddSparsificationPasses); } // namespace cpu } // namespace xla <commit_msg>[xla:cpu:next][sparse] run denseOpBufferization right after insertTensorCopy [reland]<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/cpu/hlo_xla_runtime_pipeline.h" #include <utility> #include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h" // from @llvm-project #include "mlir/Conversion/ComplexToStandard/ComplexToStandard.h" // from @llvm-project #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project #include "mlir/Conversion/TensorToLinalg/TensorToLinalgPass.h" // from @llvm-project #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" // from @llvm-project #include "mlir/Dialect/Arith/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Arith/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" // from @llvm-project #include "mlir/Dialect/Bufferization/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project #include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project #include "mlir/Dialect/Linalg/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/MemRef/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/SCF/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Shape/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Shape/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Dialect/Tensor/Transforms/Passes.h" // from @llvm-project #include "mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/xla/transforms/xla_passes.h" #include "tensorflow/compiler/xla/mlir/backends/cpu/transforms/passes.h" #include "tensorflow/compiler/xla/mlir/runtime/transforms/compiler.h" #include "tensorflow/compiler/xla/mlir_hlo/gml_st/interfaces/bufferizable_op_interface_impl.h" #include "tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/passes.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Dialect/mhlo/transforms/bufferizable_op_interface_impl.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Transforms/passes.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/tsl/platform/errors.h" #include "tensorflow/tsl/platform/logging.h" namespace xla { namespace cpu { namespace { using mlir::func::FuncOp; mlir::bufferization::OneShotBufferizationOptions GetBufferizationOptions() { using mlir::bufferization::BufferizationOptions; using mlir::bufferization::OneShotBufferizationOptions; OneShotBufferizationOptions options; options.bufferizeFunctionBoundaries = true; options.allowReturnAllocs = true; options.functionBoundaryTypeConversion = BufferizationOptions::LayoutMapOption::IdentityLayoutMap; options.unknownTypeConverterFn = [](mlir::Value value, unsigned memorySpace, const BufferizationOptions& options) { return mlir::bufferization::getMemRefTypeWithStaticIdentityLayout( value.getType().cast<mlir::TensorType>(), memorySpace); }; return options; } void AddSparsificationPasses(mlir::OpPassManager& pm) { pm.addNestedPass<FuncOp>(mlir::createLinalgGeneralizationPass()); pm.addNestedPass<FuncOp>( mlir::bufferization::createEmptyTensorToAllocTensorPass()); pm.addPass(mlir::bufferization::createTensorCopyInsertionPass( GetBufferizationOptions())); pm.addPass(mlir::createDenseBufferizationPass(GetBufferizationOptions())); pm.addPass(mlir::createSparseTensorRewritePass()); pm.addPass(mlir::createSparsificationPass()); pm.addPass(mlir::createSparseTensorConversionPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createFinalizingBufferizePass()); } } // namespace // -------------------------------------------------------------------------- // // Assemble a HLO XLA Runtime pipeline to lower from HLO to Linalg on buffers. // -------------------------------------------------------------------------- // static Status CreateHloXlaPipeline( mlir::OpPassManager& pm, const HloXlaRuntimePipelineOptions& options) { // Resolve all shape constraints (e.g. broadcast constraints that can be // proved statically and changed to const witness) early to allow more // efficient broadcast operations moving. // Move up broadcasting operations to allow for more fusion opportunities. pm.addPass(mlir::createInlinerPass()); pm.addPass(mlir::mhlo::createExpandHloTuplesPass("main")); // TODO(b/233771980): Remove once custom_call doesn't use tuples. pm.addNestedPass<mlir::func::FuncOp>(mlir::mhlo::createFlattenTuplePass()); pm.addPass(createXlaAbiLegalizationPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeGeneralDotPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createBroadcastPropagationPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); // Transform HLO operations to Linalg. pm.addNestedPass<mlir::func::FuncOp>(mlir::mhlo::createLegalizeSortPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeControlFlowPass()); pm.addPass(::mlir::mhlo::createLegalizeToArithmeticPass()); // TODO(kramerb): Give THLO lowerings priority over linalg when it's ready for // concat, reduce and friends. pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeHloToLinalgPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::mhlo::createLegalizeMHLOToTHLOPass()); // Lower index cast on tensors to tensor.generate. pm.addNestedPass<mlir::func::FuncOp>(mlir::createLowerIndexCastPass()); pm.addPass(mlir::mhlo::createConvertToSignlessPass()); // Transform scatter ops. pm.addNestedPass<mlir::func::FuncOp>( mlir::gml_st::createTransformScatterForCpuPass()); // Lower shape dialect to standard to enable linalg canonicalizations (e.g. // use linalg inputs instead of outputs for memref.dim operations). pm.addNestedPass<mlir::func::FuncOp>(mlir::createShapeSimplification()); pm.addNestedPass<mlir::func::FuncOp>(mlir::createShapeToShapeLowering()); pm.addPass(mlir::createConvertShapeToStandardPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertShapeConstraintsPass()); // Fuse Linalg on tensors operations. pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::memref::createResolveShapedTypeResultDimsPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::createLinalgElementwiseOpFusionPass()); pm.addPass(mlir::createReconcileUnrealizedCastsPass()); pm.addPass(mlir::createConvertTensorToLinalgPass()); // Detensorize SCF iter args. pm.addNestedPass<mlir::func::FuncOp>(mlir::createDetensorizeScfOpsPass()); // mhlo ops on unit tensors generate trivial linalg.generics, which // one-shot-bufferize generates unnecessary allocs for. The detensorize pass // replaces these linalg.generics with scalar ops. auto detensorize = mlir::createLinalgDetensorizePass(); if (detensorize->initializeOptions("aggressive-mode=true").failed()) { return tsl::errors::Internal("Failed to set up detensorize pass."); } pm.addNestedPass<mlir::func::FuncOp>(std::move(detensorize)); pm.addNestedPass<mlir::func::FuncOp>(mlir::createScalarizationPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createEmptyTensorToAllocTensorPass()); // Always run canonicalizer (which does dead code removal) before // bufferizing anything. pm.addPass(mlir::createCanonicalizerPass()); if (options.sparse_bufferization) { // Convert Sparse tensors. AddSparsificationPasses(pm); } else { pm.addPass(mlir::hlo::createOneShotBufferizePass()); } // Handle framework specific requirements for buffers and then insert // deallocations for temporary buffers. pm.addNestedPass<mlir::func::FuncOp>(mlir::createConvertLinalgToLoopsPass()); pm.addNestedPass<mlir::func::FuncOp>(mlir::gml_st::createGmlStToScfPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::bufferization::createBufferResultsToOutParamsPass()); if (options.outline_with_xla_framework) { pm.addPass(mlir::mhlo::CreateOutlineWithXLAFrameworkPass()); } pm.addPass(mlir::createInlinerPass()); pm.addNestedPass<mlir::func::FuncOp>( mlir::bufferization::createBufferDeallocationPass()); pm.addPass(mlir::createBufferizationToMemRefPass()); // Specialize linalg.matmul to linalg.dot, linalg.matvec or linalg.vecmat, // and immediately canonicalize to clean up not taken branches. // pm.addNestedPass<mlir::func::FuncOp>(CreateLinalgMatmulSpecializationPass()); pm.addPass(mlir::createCanonicalizerPass()); // Tile and vectorize linalg operation using Linalg Codegen Strategy. // pm.addNestedPass<mlir::func::FuncOp>(CreateCodegenStrategyForMatMulPass()); // TODO(tpopp): Move hits to mlir::hlo::createGenericHostToLLVMPass? pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertComplexToStandardPass()); pm.addPass(mlir::createCSEPass()); pm.addPass(mlir::createCanonicalizerPass()); mlir::VectorTransferToSCFOptions vec_to_scf_options; vec_to_scf_options.unroll = true; pm.addNestedPass<mlir::func::FuncOp>( mlir::createConvertVectorToSCFPass(vec_to_scf_options)); return OkStatus(); } Status CreateHloXlaRuntimePipeline( xla::runtime::PassManager& passes, const HloXlaRuntimePipelineOptions& options) { return CreateHloXlaPipeline(*passes, options); } Status CreateDefaultHloXlaRuntimePipeline(xla::runtime::PassManager& passes) { HloXlaRuntimePipelineOptions options; return CreateHloXlaPipeline(*passes, options); } void RegisterHloXlaRuntimePipelineDialects( xla::runtime::DialectRegistry& dialects) { mlir::arith::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::bufferization::func_ext::registerBufferizableOpInterfaceExternalModels( *dialects); mlir::gml_st::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::linalg::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::mhlo::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::scf::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::shape::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::tensor::registerBufferizableOpInterfaceExternalModels(*dialects); mlir::vector::registerBufferizableOpInterfaceExternalModels(*dialects); } static mlir::PassPipelineRegistration<> hlo_xla_runtime_pipeline( "hlo-xla-runtime-pipeline", "Convert HLO dialect to XLA Runtime compatible dialects", [](mlir::OpPassManager& pm) { HloXlaRuntimePipelineOptions options; Status status = CreateHloXlaPipeline(pm, options); if (!status.ok()) { LOG(FATAL) << "HLO-XLA Runtime pipeline failed with: " << status.error_message(); } }); static mlir::PassPipelineRegistration<> sparsification_pipeline( "hlo-xla-runtime-sparsification", "Sparsification passes from HLO-XLA Runtime pipeline", AddSparsificationPasses); } // namespace cpu } // namespace xla <|endoftext|>
<commit_before>// Copyright (c) 2015 The CSUTIL 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 <errno.h> #include <stdio.h> #include <assert.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <arpa/inet.h> #include <sys/socket.h> #include "base/msg.h" #include "base/util.h" #include "base/coding.h" #include "base/common.h" #include "sock/tcp_client.h" namespace base { Code DefaultProtoFunc(const char *src_data, int src_data_len, int *real_len) {/*{{{*/ if (src_data == NULL || src_data_len < 0 || real_len == NULL) return kInvalidParam; if (src_data_len < kHeadLen) return kDataNotEnough; uint32_t len = 0; Code r = DecodeFixed32(std::string(src_data, src_data_len), &len); if (r != kOk) return r; if (src_data_len < (int)(kHeadLen+len)) return kDataNotEnough; *real_len = kHeadLen+len; return kOk; }/*}}}*/ TcpClient::TcpClient() : ev_(NULL), client_fd_(-1), data_proto_func_(NULL), serv_ip_(""), serv_port_(0), data_buf_(NULL), start_pos_(0), end_pos_(0), total_size_(0) { } TcpClient::~TcpClient() {/*{{{*/ CloseConnect(); if (ev_ != NULL) { delete ev_; ev_ = NULL; } if (data_buf_ != NULL) { delete data_buf_; data_buf_ = NULL; } }/*}}}*/ Code TcpClient::Init(EventType evt_type, DataProtoFunc data_proto_func) {/*{{{*/ Code ret = kOk; switch (evt_type) { case kSelect: break; case kPoll: ev_ = new EventPoll(); ret = ev_->Create(kDefaultSizeOfFds); break; case kEPoll: #if defined(__linux__) ev_ = new EventEpoll(); #else ev_ = new EventPoll(); #endif ret = ev_->Create(kDefaultSizeOfFds); break; default: ev_ = new EventPoll(); ret = ev_->Create(kDefaultSizeOfFds); break; } data_proto_func_ = data_proto_func; data_buf_ = new char[kMaxStreamBufLen]; total_size_ = kMaxStreamBufLen; return kOk; }/*}}}*/ Code TcpClient::Connect(const std::string &ip, uint16_t port) {/*{{{*/ if (ip.size() == 0) return kInvalidParam; serv_ip_ = ip; serv_port_ = port; struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); int ret = inet_pton(AF_INET, ip.c_str(), &(serv_addr.sin_addr)); assert(ret == 1); CloseConnect(); client_fd_ = socket(AF_INET, SOCK_STREAM, 0); if (client_fd_ == -1) return kSocketError; Code r = SetFdNonblock(client_fd_); if (r != kOk) return r; ev_->Add(client_fd_, EV_OUT); while (true) { ret = connect(client_fd_, (struct sockaddr*)(&serv_addr), sizeof(serv_addr)); if (ret == -1 && errno == EINTR) continue; else break; } if (ret == 0) return kOk; if ((errno != EAGAIN) && (errno != EINPROGRESS)) return kConnectError; int time_waits = 0; while (true) { r = ev_->Wait(kDefaultWaitTimeMs); // fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kOk) break; if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } CloseConnect(); return r; } int sock_err = 0; socklen_t sock_err_len; ret = getsockopt(client_fd_, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &sock_err_len); if (ret == -1) { CloseConnect(); return kSocketError; } if (sock_err != 0) { CloseConnect(); return kSocketError; } return kOk; }/*}}}*/ Code TcpClient::ReConnect() {/*{{{*/ if (serv_ip_.empty() || serv_port_ == 0) return kIpOrPortNotInit; CloseConnect(); return Connect(serv_ip_, serv_port_); }/*}}}*/ Code TcpClient::SendNative(const std::string &data) {/*{{{*/ if (data.empty()) return kInvalidParam; Code r = ev_->Mod(client_fd_, EV_OUT|EV_ERR|EV_HUP); int32_t left_len = data.size(); int time_waits = 0; while (left_len > 0) { r = ev_->Wait(kDefaultWaitTimeMs); //fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } time_waits = 0; if (r == kOk) { int fd, event; r = ev_->GetEvents(&fd, &event); assert(r == kOk && fd == client_fd_); if ((event & EV_ERR) || (event & EV_HUP)) goto err; int ret = write(client_fd_, data.data()+data.size()-left_len, left_len); if (ret == 0 || (ret == -1 && errno != EAGAIN)) goto err; if (ret == -1 && errno == EAGAIN) continue; left_len -= ret; } else goto err; } return kOk; err: CloseConnect(); return kSocketError; }/*}}}*/ Code TcpClient::Recv(std::string *data) {/*{{{*/ if (data == NULL) return kInvalidParam; Code r = kOk; int real_len = 0; while (true) { r = data_proto_func_(data_buf_+start_pos_, end_pos_-start_pos_, &real_len); if (r == kDataNotEnough) { r = RecvInternal(); if (r != kOk) return r; continue; } else if (r != kOk) { return r; } data->assign(data_buf_+start_pos_, real_len); start_pos_ += real_len; break; } return r; }/*}}}*/ void TcpClient::CloseConnect() {/*{{{*/ if (client_fd_ != -1) { close(client_fd_); client_fd_ = -1; } }/*}}}*/ Code TcpClient::RecvInternal() {/*{{{*/ if (start_pos_ == end_pos_) start_pos_ = end_pos_ = 0; if (start_pos_ != 0) { memmove(data_buf_, data_buf_+start_pos_, end_pos_-start_pos_); end_pos_ -= start_pos_; start_pos_ = 0; } if (end_pos_ == total_size_) return kDataBufFull; Code r = ev_->Mod(client_fd_, EV_IN); int time_waits = 0; while (true) { r = ev_->Wait(kDefaultWaitTimeMs); // fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } time_waits = 0; if (r == kOk) { int fd, event; r = ev_->GetEvents(&fd, &event); assert(r == kOk && fd == client_fd_); if ((event & EV_ERR) || (event & EV_HUP)) goto err; int ret = read(client_fd_, data_buf_+end_pos_, total_size_-end_pos_); if (ret == 0 || (ret == -1 && errno != EAGAIN)) goto err; if (ret == -1 && errno == EAGAIN) continue; end_pos_ += ret; break; } else goto err; } return kOk; err: CloseConnect(); return kSocketError; }/*}}}*/ } #ifdef _TCP_CLIENT_MAIN_TEST_ int main(int argc, char *argv[]) { using namespace base; TcpClient tcp_client; base::EventType event_type = base::kPoll; #if defined(__linux__) event_type = base::kEPoll; #endif base::Code ret = tcp_client.Init(event_type, DefaultProtoFunc); assert(ret == base::kOk); std::string ip("127.0.0.1"); uint16_t port = 9090; fprintf(stderr, "Start to connect ip:port <%s, %d>\n", ip.c_str(), port); ret = tcp_client.Connect(ip, port); assert(ret == base::kOk); // Encode the data and send std::string buf_out("hello world"); std::string encode_buf_out; ret = EncodeToMsg(buf_out, &encode_buf_out); assert(ret == kOk); fprintf(stderr, "buf out:%s\n", buf_out.c_str()); ret = tcp_client.SendNative(encode_buf_out); if (ret != kOk) { fprintf(stderr, "Failed to send native! ret:%d\n", (int)ret); return ret; } fprintf(stderr, "buf out:%s\n", buf_out.c_str()); ret = tcp_client.SendNative(encode_buf_out); if (ret != kOk) { fprintf(stderr, "Failed to send native! ret:%d\n", (int)ret); return ret; } // Receive the data and decode std::string buf_in; std::string decode_buf_in; ret = tcp_client.Recv(&buf_in); assert(ret == base::kOk); ret = DecodeFromMsg(buf_in, &decode_buf_in); assert(ret == kOk); fprintf(stderr, "buf in:%s\n", decode_buf_in.c_str()); ret = tcp_client.Recv(&buf_in); assert(ret == base::kOk); ret = DecodeFromMsg(buf_in, &decode_buf_in); assert(ret == kOk); fprintf(stderr, "buf in:%s\n", decode_buf_in.c_str()); return 0; } #endif <commit_msg>1)Modifying: Fix bug when closing connection<commit_after>// Copyright (c) 2015 The CSUTIL 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 <errno.h> #include <stdio.h> #include <assert.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <arpa/inet.h> #include <sys/socket.h> #include "base/msg.h" #include "base/util.h" #include "base/coding.h" #include "base/common.h" #include "sock/tcp_client.h" namespace base { Code DefaultProtoFunc(const char *src_data, int src_data_len, int *real_len) {/*{{{*/ if (src_data == NULL || src_data_len < 0 || real_len == NULL) return kInvalidParam; if (src_data_len < kHeadLen) return kDataNotEnough; uint32_t len = 0; Code r = DecodeFixed32(std::string(src_data, src_data_len), &len); if (r != kOk) return r; if (src_data_len < (int)(kHeadLen+len)) return kDataNotEnough; *real_len = kHeadLen+len; return kOk; }/*}}}*/ TcpClient::TcpClient() : ev_(NULL), client_fd_(-1), data_proto_func_(NULL), serv_ip_(""), serv_port_(0), data_buf_(NULL), start_pos_(0), end_pos_(0), total_size_(0) { } TcpClient::~TcpClient() {/*{{{*/ CloseConnect(); if (ev_ != NULL) { delete ev_; ev_ = NULL; } if (data_buf_ != NULL) { delete data_buf_; data_buf_ = NULL; } }/*}}}*/ Code TcpClient::Init(EventType evt_type, DataProtoFunc data_proto_func) {/*{{{*/ Code ret = kOk; switch (evt_type) { case kSelect: break; case kPoll: ev_ = new EventPoll(); ret = ev_->Create(kDefaultSizeOfFds); break; case kEPoll: #if defined(__linux__) ev_ = new EventEpoll(); #else ev_ = new EventPoll(); #endif ret = ev_->Create(kDefaultSizeOfFds); break; default: ev_ = new EventPoll(); ret = ev_->Create(kDefaultSizeOfFds); break; } data_proto_func_ = data_proto_func; data_buf_ = new char[kMaxStreamBufLen]; total_size_ = kMaxStreamBufLen; return kOk; }/*}}}*/ Code TcpClient::Connect(const std::string &ip, uint16_t port) {/*{{{*/ if (ip.size() == 0) return kInvalidParam; serv_ip_ = ip; serv_port_ = port; struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); int ret = inet_pton(AF_INET, ip.c_str(), &(serv_addr.sin_addr)); assert(ret == 1); CloseConnect(); client_fd_ = socket(AF_INET, SOCK_STREAM, 0); if (client_fd_ == -1) return kSocketError; Code r = SetFdNonblock(client_fd_); if (r != kOk) return r; ev_->Add(client_fd_, EV_OUT); while (true) { ret = connect(client_fd_, (struct sockaddr*)(&serv_addr), sizeof(serv_addr)); if (ret == -1 && errno == EINTR) continue; else break; } if (ret == 0) return kOk; if ((errno != EAGAIN) && (errno != EINPROGRESS)) return kConnectError; int time_waits = 0; while (true) { r = ev_->Wait(kDefaultWaitTimeMs); // fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kOk) break; if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } // Note: Other error, then close CloseConnect(); return r; } int sock_err = 0; socklen_t sock_err_len; ret = getsockopt(client_fd_, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &sock_err_len); if (ret == -1) { CloseConnect(); return kSocketError; } if (sock_err != 0) { CloseConnect(); return kSocketError; } start_pos_ = 0; end_pos_ = 0; return kOk; }/*}}}*/ Code TcpClient::ReConnect() {/*{{{*/ if (serv_ip_.empty() || serv_port_ == 0) return kIpOrPortNotInit; CloseConnect(); return Connect(serv_ip_, serv_port_); }/*}}}*/ Code TcpClient::SendNative(const std::string &data) {/*{{{*/ if (data.empty()) return kInvalidParam; Code r = ev_->Mod(client_fd_, EV_OUT|EV_ERR|EV_HUP); int32_t left_len = data.size(); int time_waits = 0; while (left_len > 0) { r = ev_->Wait(kDefaultWaitTimeMs); //fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } time_waits = 0; if (r == kOk) { int fd, event; r = ev_->GetEvents(&fd, &event); assert(r == kOk && fd == client_fd_); if ((event & EV_ERR) || (event & EV_HUP)) goto err; int ret = write(client_fd_, data.data()+data.size()-left_len, left_len); if (ret == 0 || (ret == -1 && errno != EAGAIN)) goto err; if (ret == -1 && errno == EAGAIN) continue; left_len -= ret; } else goto err; } return kOk; err: CloseConnect(); return kSocketError; }/*}}}*/ Code TcpClient::Recv(std::string *data) {/*{{{*/ if (data == NULL) return kInvalidParam; Code r = kOk; int real_len = 0; while (true) { r = data_proto_func_(data_buf_+start_pos_, end_pos_-start_pos_, &real_len); if (r == kDataNotEnough) { r = RecvInternal(); if (r != kOk) return r; continue; } else if (r != kOk) { return r; } data->assign(data_buf_+start_pos_, real_len); start_pos_ += real_len; break; } return r; }/*}}}*/ void TcpClient::CloseConnect() {/*{{{*/ if (client_fd_ != -1) { ev_->Del(client_fd_); close(client_fd_); client_fd_ = -1; start_pos_ = 0; end_pos_ = 0; } }/*}}}*/ Code TcpClient::RecvInternal() {/*{{{*/ if (start_pos_ == end_pos_) start_pos_ = end_pos_ = 0; if (start_pos_ != 0) { memmove(data_buf_, data_buf_+start_pos_, end_pos_-start_pos_); end_pos_ -= start_pos_; start_pos_ = 0; } if (end_pos_ == total_size_) return kDataBufFull; Code r = ev_->Mod(client_fd_, EV_IN); int time_waits = 0; while (true) { r = ev_->Wait(kDefaultWaitTimeMs); // fprintf(stderr, "(%s:%d) now time_waits:%d, r:%d\n", __FILE__, __LINE__, time_waits, r); if (r == kTimeOut) { time_waits += kDefaultWaitTimeMs; if (time_waits >= kDefaultMaxWaitTimeMs) { // Note: if waiting time exceed max time, then just quit CloseConnect(); return kTimeOut; } continue; } time_waits = 0; if (r == kOk) { int fd, event; r = ev_->GetEvents(&fd, &event); assert(r == kOk && fd == client_fd_); if ((event & EV_ERR) || (event & EV_HUP)) goto err; int ret = read(client_fd_, data_buf_+end_pos_, total_size_-end_pos_); if (ret == 0 || (ret == -1 && errno != EAGAIN)) goto err; if (ret == -1 && errno == EAGAIN) continue; end_pos_ += ret; break; } else goto err; } return kOk; err: CloseConnect(); return kSocketError; }/*}}}*/ } #ifdef _TCP_CLIENT_MAIN_TEST_ int main(int argc, char *argv[]) { using namespace base; TcpClient tcp_client; base::EventType event_type = base::kPoll; #if defined(__linux__) event_type = base::kEPoll; #endif base::Code ret = tcp_client.Init(event_type, DefaultProtoFunc); assert(ret == base::kOk); std::string ip("127.0.0.1"); uint16_t port = 9090; fprintf(stderr, "Start to connect ip:port <%s, %d>\n", ip.c_str(), port); ret = tcp_client.Connect(ip, port); assert(ret == base::kOk); // Encode the data and send std::string buf_out("hello world"); std::string encode_buf_out; ret = EncodeToMsg(buf_out, &encode_buf_out); assert(ret == kOk); fprintf(stderr, "buf out:%s\n", buf_out.c_str()); ret = tcp_client.SendNative(encode_buf_out); if (ret != kOk) { fprintf(stderr, "Failed to send native! ret:%d\n", (int)ret); return ret; } fprintf(stderr, "buf out:%s\n", buf_out.c_str()); ret = tcp_client.SendNative(encode_buf_out); if (ret != kOk) { fprintf(stderr, "Failed to send native! ret:%d\n", (int)ret); return ret; } // Receive the data and decode std::string buf_in; std::string decode_buf_in; ret = tcp_client.Recv(&buf_in); assert(ret == base::kOk); ret = DecodeFromMsg(buf_in, &decode_buf_in); assert(ret == kOk); fprintf(stderr, "buf in:%s\n", decode_buf_in.c_str()); ret = tcp_client.Recv(&buf_in); assert(ret == base::kOk); ret = DecodeFromMsg(buf_in, &decode_buf_in); assert(ret == kOk); fprintf(stderr, "buf in:%s\n", decode_buf_in.c_str()); return 0; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: myucp_provider.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kso $ $Date: 2001-06-06 14:46:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif // @@@ Adjust multi-include-protection-ifdef and header file name. #ifndef _MYUCP_PROVIDER_HXX #include "myucp_provider.hxx" #endif // @@@ Adjust multi-include-protection-ifdef and header file name. #ifndef _MYUCP_CONTENT_HXX #include "myucp_content.hxx" #endif using namespace com::sun; using namespace com::sun::star; // @@@ Adjust namespace name. using namespace myucp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const uno::Reference< lang::XMultiServiceFactory >& rSMgr ) : ::ucb::ContentProviderImplHelper( rSMgr ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { } //========================================================================= // // XInterface methods. // //========================================================================= // @@@ Add own interfaces. XINTERFACE_IMPL_3( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, star::ucb::XContentProvider ); //========================================================================= // // XTypeProvider methods. // //========================================================================= // @@@ Add own interfaces. XTYPEPROVIDER_IMPL_3( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, star::ucb::XContentProvider ); //========================================================================= // // XServiceInfo methods. // //========================================================================= // @@@ Adjust implementation name. Keep the prefix "com.sun.star.comp."! // @@@ Adjust service name. XSERVICEINFO_IMPL_1( ContentProvider, rtl::OUString::createFromAscii( "com.sun.star.comp.myucp.ContentProvider" ), rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual uno::Reference< star::ucb::XContent > SAL_CALL ContentProvider::queryContent( const uno::Reference< star::ucb::XContentIdentifier >& Identifier ) throw( star::ucb::IllegalIdentifierException, uno::RuntimeException ) { vos::OGuard aGuard( m_aMutex ); // Check URL scheme... rtl::OUString aScheme( rtl::OUString::createFromAscii( MYUCP_URL_SCHEME ) ); if ( !Identifier->getContentProviderScheme().equalsIgnoreAsciiCase( aScheme ) ) throw star::ucb::IllegalIdentifierException(); // @@@ Further id checks may go here... #if 0 if ( id-check-failes ) throw star::ucb::IllegalIdentifierException(); #endif // @@@ Id normalization may go here... #if 0 // Normalize URL and create new Id. rtl::OUString aCanonicURL = xxxxx( Identifier->getContentIdentifier() ); uno::Reference< star::ucb::XContentIdentifier > xCanonicId = new ::ucb::ContentIdentifier( m_xSMgr, aCanonicURL ); #else uno::Reference< star::ucb::XContentIdentifier > xCanonicId = Identifier; #endif // Check, if a content with given id already exists... uno::Reference< star::ucb::XContent > xContent = queryExistingContent( xCanonicId ).getBodyPtr(); if ( xContent.is() ) return xContent; // @@@ Decision, which content implementation to instanciate may be // made here ( in case you have different content classes ). // Create a new content. Note that the content will insert itself // into providers content list by calling addContent(...) from it's ctor. xContent = new Content( m_xSMgr, this, xCanonicId ); if ( !xContent->getIdentifier().is() ) throw star::ucb::IllegalIdentifierException(); return xContent; } <commit_msg>#89617# - Fixed queryContent(...). Mutex Guard now constructed a little bit later.<commit_after>/************************************************************************* * * $RCSfile: myucp_provider.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kso $ $Date: 2001-07-12 15:05:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif // @@@ Adjust multi-include-protection-ifdef and header file name. #ifndef _MYUCP_PROVIDER_HXX #include "myucp_provider.hxx" #endif // @@@ Adjust multi-include-protection-ifdef and header file name. #ifndef _MYUCP_CONTENT_HXX #include "myucp_content.hxx" #endif using namespace com::sun; using namespace com::sun::star; // @@@ Adjust namespace name. using namespace myucp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const uno::Reference< lang::XMultiServiceFactory >& rSMgr ) : ::ucb::ContentProviderImplHelper( rSMgr ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { } //========================================================================= // // XInterface methods. // //========================================================================= // @@@ Add own interfaces. XINTERFACE_IMPL_3( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, star::ucb::XContentProvider ); //========================================================================= // // XTypeProvider methods. // //========================================================================= // @@@ Add own interfaces. XTYPEPROVIDER_IMPL_3( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, star::ucb::XContentProvider ); //========================================================================= // // XServiceInfo methods. // //========================================================================= // @@@ Adjust implementation name. Keep the prefix "com.sun.star.comp."! // @@@ Adjust service name. XSERVICEINFO_IMPL_1( ContentProvider, rtl::OUString::createFromAscii( "com.sun.star.comp.myucp.ContentProvider" ), rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual uno::Reference< star::ucb::XContent > SAL_CALL ContentProvider::queryContent( const uno::Reference< star::ucb::XContentIdentifier >& Identifier ) throw( star::ucb::IllegalIdentifierException, uno::RuntimeException ) { // Check URL scheme... rtl::OUString aScheme( rtl::OUString::createFromAscii( MYUCP_URL_SCHEME ) ); if ( !Identifier->getContentProviderScheme().equalsIgnoreAsciiCase( aScheme ) ) throw star::ucb::IllegalIdentifierException(); // @@@ Further id checks may go here... #if 0 if ( id-check-failes ) throw star::ucb::IllegalIdentifierException(); #endif // @@@ Id normalization may go here... #if 0 // Normalize URL and create new Id. rtl::OUString aCanonicURL = xxxxx( Identifier->getContentIdentifier() ); uno::Reference< star::ucb::XContentIdentifier > xCanonicId = new ::ucb::ContentIdentifier( m_xSMgr, aCanonicURL ); #else uno::Reference< star::ucb::XContentIdentifier > xCanonicId = Identifier; #endif vos::OGuard aGuard( m_aMutex ); // Check, if a content with given id already exists... uno::Reference< star::ucb::XContent > xContent = queryExistingContent( xCanonicId ).getBodyPtr(); if ( xContent.is() ) return xContent; // @@@ Decision, which content implementation to instanciate may be // made here ( in case you have different content classes ). // Create a new content. Note that the content will insert itself // into providers content list by calling addContent(...) from it's ctor. xContent = new Content( m_xSMgr, this, xCanonicId ); if ( !xContent->getIdentifier().is() ) throw star::ucb::IllegalIdentifierException(); return xContent; } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Unit tests for the solidity parser. */ #include <string> #include <libdevcore/Log.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/Exceptions.h> #include <boost/test/unit_test.hpp> namespace dev { namespace solidity { namespace test { namespace { ASTPointer<ContractDefinition> parseText(std::string const& _source) { Parser parser; return parser.parse(std::make_shared<Scanner>(CharStream(_source))); } } BOOST_AUTO_TEST_SUITE(SolidityParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "contract test {\n" " uint256 stateVariable1;\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(missing_variable_name_in_declaration) { char const* text = "contract test {\n" " uint256 ;\n" "}\n"; BOOST_CHECK_THROW(parseText(text), ParserError); } BOOST_AUTO_TEST_CASE(empty_function) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName(hash160 arg1, address addr) const\n" " returns (int id)\n" " { }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(no_function_params) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName() {}\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(single_function_param) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(function_natspec_documentation) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " /// This is a test function\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is a test function"); } BOOST_AUTO_TEST_CASE(function_normal_comments) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " // We won't see this comment\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), ""); } BOOST_AUTO_TEST_CASE(struct_definition) { char const* text = "contract test {\n" " uint256 stateVar;\n" " struct MyStructName {\n" " address addr;\n" " uint256 count;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping) { char const* text = "contract test {\n" " mapping(address => string) names;\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping_in_struct) { char const* text = "contract test {\n" " struct test_struct {\n" " address addr;\n" " uint256 count;\n" " mapping(hash => test_struct) self_reference;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping_to_mapping_in_struct) { char const* text = "contract test {\n" " struct test_struct {\n" " address addr;\n" " mapping (uint64 => mapping (hash => uint)) complex_mapping;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(variable_definition) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " var b;\n" " uint256 c;\n" " mapping(address=>hash) d;\n" " customtype varname;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(variable_definition_with_initialization) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " var b = 2;\n" " uint256 c = 0x87;\n" " mapping(address=>hash) d;\n" " string name = \"Solidity\";" " customtype varname;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(operator_expression) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " uint256 x = (1 + 4) || false && (1 - 12) + -9;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(complex_expression) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " uint256 x = (1 + 4).member(++67)[a/=9] || true;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(while_loop) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " while (true) { uint256 x = 1; break; continue; } x = 9;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(if_statement) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " if (a >= 8) return 2; else { var b = 7; }\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(else_if_statement) { char const* text = "contract test {\n" " function fun(uint256 a) returns (address b) {\n" " if (a < 0) b = 0x67; else if (a == 0) b = 0x12; else b = 0x78;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(statement_starting_with_type_conversion) { char const* text = "contract test {\n" " function fun() {\n" " uint64(2);\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Solidity work for documentation strings<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Unit tests for the solidity parser. */ #include <string> #include <libdevcore/Log.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/Exceptions.h> #include <boost/test/unit_test.hpp> namespace dev { namespace solidity { namespace test { namespace { ASTPointer<ContractDefinition> parseText(std::string const& _source) { Parser parser; return parser.parse(std::make_shared<Scanner>(CharStream(_source))); } } BOOST_AUTO_TEST_SUITE(SolidityParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "contract test {\n" " uint256 stateVariable1;\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(missing_variable_name_in_declaration) { char const* text = "contract test {\n" " uint256 ;\n" "}\n"; BOOST_CHECK_THROW(parseText(text), ParserError); } BOOST_AUTO_TEST_CASE(empty_function) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName(hash160 arg1, address addr) const\n" " returns (int id)\n" " { }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(no_function_params) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName() {}\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(single_function_param) { char const* text = "contract test {\n" " uint256 stateVar;\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(function_natspec_documentation) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " /// This is a test function\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is a test function"); } BOOST_AUTO_TEST_CASE(function_normal_comments) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " // We won't see this comment\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), ""); } BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " /// This is test function 1\n" " function functionName1(hash hashin) returns (hash hashout) {}\n" " /// This is test function 2\n" " function functionName2(hash hashin) returns (hash hashout) {}\n" " // nothing to see here\n" " function functionName3(hash hashin) returns (hash hashout) {}\n" " /// This is test function 4\n" " function functionName4(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is test function 1"); BOOST_CHECK_NO_THROW(function = functions.at(1)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is test function 2"); BOOST_CHECK_NO_THROW(function = functions.at(2)); BOOST_CHECK_EQUAL(function->getDocumentation(), ""); BOOST_CHECK_NO_THROW(function = functions.at(3)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is test function 4"); } #if 0 /* Work in progress - currently fails*/ BOOST_AUTO_TEST_CASE(multiline_function_documentation) { ASTPointer<ContractDefinition> contract; ASTPointer<FunctionDefinition> function; char const* text = "contract test {\n" " uint256 stateVar;\n" " /// This is a test function\n" " /// and it has 2 lines\n" " function functionName1(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_CHECK_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_CHECK_NO_THROW(function = functions.at(0)); BOOST_CHECK_EQUAL(function->getDocumentation(), " This is a test function\n" " and it has 2 lines"); } #endif BOOST_AUTO_TEST_CASE(struct_definition) { char const* text = "contract test {\n" " uint256 stateVar;\n" " struct MyStructName {\n" " address addr;\n" " uint256 count;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping) { char const* text = "contract test {\n" " mapping(address => string) names;\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping_in_struct) { char const* text = "contract test {\n" " struct test_struct {\n" " address addr;\n" " uint256 count;\n" " mapping(hash => test_struct) self_reference;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(mapping_to_mapping_in_struct) { char const* text = "contract test {\n" " struct test_struct {\n" " address addr;\n" " mapping (uint64 => mapping (hash => uint)) complex_mapping;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(variable_definition) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " var b;\n" " uint256 c;\n" " mapping(address=>hash) d;\n" " customtype varname;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(variable_definition_with_initialization) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " var b = 2;\n" " uint256 c = 0x87;\n" " mapping(address=>hash) d;\n" " string name = \"Solidity\";" " customtype varname;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(operator_expression) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " uint256 x = (1 + 4) || false && (1 - 12) + -9;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(complex_expression) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " uint256 x = (1 + 4).member(++67)[a/=9] || true;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(while_loop) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " while (true) { uint256 x = 1; break; continue; } x = 9;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(if_statement) { char const* text = "contract test {\n" " function fun(uint256 a) {\n" " if (a >= 8) return 2; else { var b = 7; }\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(else_if_statement) { char const* text = "contract test {\n" " function fun(uint256 a) returns (address b) {\n" " if (a < 0) b = 0x67; else if (a == 0) b = 0x12; else b = 0x78;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_CASE(statement_starting_with_type_conversion) { char const* text = "contract test {\n" " function fun() {\n" " uint64(2);\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseText(text)); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before><commit_msg>Add checks on key string in CaesarCipher function.<commit_after><|endoftext|>
<commit_before>// MFEM Example 0 // // Compile with: make ex0 // // Sample runs: ex0 // ex0 -m ../data/fichera.mesh // ex0 -m ../data/square-disc.mesh -o 2 // // Description: This example code demonstrates the most basic usage of MFEM to // define a simple finite element discretization of the Laplace // problem -Delta u = 1 with zero Dirichlet boundary conditions. // General 2D/3D mesh files and finite element polynomial degrees // can be specified by command line options. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 1. Parse command line options const char *mesh_file = "../data/star.mesh"; int order = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element polynomial degree"); args.ParseCheck(); // 2. Read the mesh from the given mesh file, and refine once uniformly. Mesh mesh(mesh_file); mesh.UniformRefinement(); // 3. Define a finite element space on the mesh. Here we use H1 continuous // high-order Lagrange finite elements of the given order. H1_FECollection fec(order, mesh.Dimension()); FiniteElementSpace fespace(&mesh, &fec); cout << "Number of unknowns: " << fespace.GetTrueVSize() << endl; // 4. Extract the list of all the boundary DOFs. These will be marked as // Dirichlet in order to enforce zero boundary conditions. Array<int> boundary_dofs; fespace.GetBoundaryTrueDofs(boundary_dofs); // 5. Define the solution x as a finite element grid function in fespace. Set // the initial guess to zero, which also sets the boundary conditions. GridFunction x(&fespace); x = 0.0; // 6. Set up the linear form b(.) corresponding to the right-hand side. ConstantCoefficient one(1.0); LinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(one)); b.Assemble(); // 7. Set up the bilinear form a(.,.) corresponding to the -Delta operator. BilinearForm a(&fespace); a.AddDomainIntegrator(new DiffusionIntegrator); a.Assemble(); // 8. Form the linear system A X = B. This includes eliminating boundary // conditions, applying AMR constraints, and other transformations. SparseMatrix A; Vector B, X; a.FormLinearSystem(boundary_dofs, x, b, A, X, B); // 9. Solve the system using PCG with symmetric Gauss-Seidel preconditioner. GSSmoother M(A); PCG(A, M, B, X, 1, 200, 1e-12, 0.0); // 10. Recover the solution x as a grid function and save to file. The output // can be viewed using GLVis as follows: "glvis -m mesh.mesh -g sol.gf" a.RecoverFEMSolution(X, b, x); x.Save("sol.gf"); mesh.Save("mesh.mesh") return 0; } <commit_msg>Revert "Introduce a failure in a test for testing purpose"<commit_after>// MFEM Example 0 // // Compile with: make ex0 // // Sample runs: ex0 // ex0 -m ../data/fichera.mesh // ex0 -m ../data/square-disc.mesh -o 2 // // Description: This example code demonstrates the most basic usage of MFEM to // define a simple finite element discretization of the Laplace // problem -Delta u = 1 with zero Dirichlet boundary conditions. // General 2D/3D mesh files and finite element polynomial degrees // can be specified by command line options. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 1. Parse command line options const char *mesh_file = "../data/star.mesh"; int order = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element polynomial degree"); args.ParseCheck(); // 2. Read the mesh from the given mesh file, and refine once uniformly. Mesh mesh(mesh_file); mesh.UniformRefinement(); // 3. Define a finite element space on the mesh. Here we use H1 continuous // high-order Lagrange finite elements of the given order. H1_FECollection fec(order, mesh.Dimension()); FiniteElementSpace fespace(&mesh, &fec); cout << "Number of unknowns: " << fespace.GetTrueVSize() << endl; // 4. Extract the list of all the boundary DOFs. These will be marked as // Dirichlet in order to enforce zero boundary conditions. Array<int> boundary_dofs; fespace.GetBoundaryTrueDofs(boundary_dofs); // 5. Define the solution x as a finite element grid function in fespace. Set // the initial guess to zero, which also sets the boundary conditions. GridFunction x(&fespace); x = 0.0; // 6. Set up the linear form b(.) corresponding to the right-hand side. ConstantCoefficient one(1.0); LinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(one)); b.Assemble(); // 7. Set up the bilinear form a(.,.) corresponding to the -Delta operator. BilinearForm a(&fespace); a.AddDomainIntegrator(new DiffusionIntegrator); a.Assemble(); // 8. Form the linear system A X = B. This includes eliminating boundary // conditions, applying AMR constraints, and other transformations. SparseMatrix A; Vector B, X; a.FormLinearSystem(boundary_dofs, x, b, A, X, B); // 9. Solve the system using PCG with symmetric Gauss-Seidel preconditioner. GSSmoother M(A); PCG(A, M, B, X, 1, 200, 1e-12, 0.0); // 10. Recover the solution x as a grid function and save to file. The output // can be viewed using GLVis as follows: "glvis -m mesh.mesh -g sol.gf" a.RecoverFEMSolution(X, b, x); x.Save("sol.gf"); mesh.Save("mesh.mesh"); return 0; } <|endoftext|>
<commit_before>/// This file contains the implementation of VNS #include "header/vns-priv.hpp" using namespace std; namespace pcp { Solution bestSolution; Solution origSolution; bool checkValid(Solution* s); /// Some constants const int NUM_VNS = 2; const int SHAKE_START = 1; /// Implementation of VNS, see vns.hpp Solution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) { /// Backup the starting solutions bestSolution = new Solution(best); origSolution = new Solution(orig); if (DEBUG_LEVEL > 2) { cout<<"Best solution uses "<<bestSolution.colorsUsed<<" colors"<<endl; cout<<"Full solution uses "<<origSolution.colorsUsed<<" colors"<<endl; } if (DEBUG_LEVEL > 1) { cout<<"The supplied solution is valid: "<<(checkValid(&best) ? "true": "false")<<endl; } /// Define the neighborhoods to use VNS_Unit **neighbors = new VNS_Unit*[NUM_VNS]; changeNode *cN = new changeNode; changeColor *cC = new changeColor; neighbors[0] = cN; neighbors[1] = cC; time_t startTime = time(NULL); int no_imp_runs = 0; int curNeighbor = 0; int shakeSteps = shakeStart - shakeIncrement; Solution *toImprove = new Solution(&best); Solution *curBest = &best; /// Run as long as shaking still produces usefull solution while (true) { /// Run all possible neighborhood while (curNeighbor < NUM_VNS) { /// Select the new neighborhood VNS_Unit *neigh = neighbors[curNeighbor]; if (DEBUG_LEVEL > 1) { cout<<"Running: "<< neigh->name() <<endl; } /// Compute the minimum for this neighborhood Solution *improved = neigh->findLocalMin(best, orig); if (DEBUG_LEVEL > 1) { cout<<"Valid solution: "<<((checkValid(improved)) ? "true" : "false"); cout<<endl; } /// Replace the existing solution with the new solution if it is an /// improvement if (improved->colorsUsed < toImprove->colorsUsed) { delete toImprove; toImprove = improved; if (DEBUG_LEVEL > 1) { cout<<"Improvement found with "<<neigh->name()<<endl; } /// Restart neighborhoods curNeighbor = curNeighbor == 0 ? 1 : 0; } /// Step to next neighborhood, no improvement found else { if (DEBUG_LEVEL > 1) { cout<<"No improvement found"<<endl; cout<<"Test next neighborhood"<<endl; } delete improved; curNeighbor++; } if (DEBUG_LEVEL > 1) { cout<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; cout<<endl<<endl; } } // end while neighborhood /// Local minimum of neighborhoods is better than current best /// solution if (toImprove->colorsUsed < best.colorsUsed) { if (DEBUG_LEVEL > 1) { cout<<"Improvement to global best solution found"<<endl; } best = toImprove; toImprove = new Solution(curBest); no_imp_runs = 0; shakeSteps = shakeStart - shakeIncrement; } /// Reset local best solution to global best Solution else { toImprove = curBest; no_imp_runs++; /// Stopping condition, quit VNS if (no_imp_runs > unsuccessfulShake) { break; } } int shakeNeighbor = rand() % NUM_VNS; VNS_Unit *shaker = neighbors[shakeNeighbor]; toImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement)); /// No time left, abort main loop if (startTime + maxTime < time(NULL)) { if (DEBUG_LEVEL > 0) { cout<<"Time's up"<<endl; } break; } } return new Solution(curBest); } bool checkValid(Solution* s) { pair<VertexIter, VertexIter> vIter; int parts[s->numParts]; int colors[s->numParts]; typedef boost::graph_traits<Graph>::adjacency_iterator AdjIter; VertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g); bool valid = true; for (int i = 0; i < s->numParts; i++) { parts[i] = 0; } for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) { parts[vParts[*vIter.first]] = 1; colors[s->partition[vParts[*vIter.first]]] = 1; pair<AdjIter, AdjIter> aIter; for (aIter = adjacent_vertices(*vIter.first, *s->g); aIter.first != aIter.second; aIter.first++) { if (s->partition[vParts[*aIter.first]] == s->partition[vParts[*vIter.first]]) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Adjacent vertices "<<*aIter.first<<" and "<<*vIter.first; cerr<<" have same color "<<s->partition[vParts[*vIter.first]]; cerr<<endl; } } } int count = 0; for (int i = 0; i < s->numParts; i++) { if (colors[i] == 1) { count++; } } if (count != s->colorsUsed) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Wrong colorsUsed stored: stored: "<<s->colorsUsed; cerr<<", computed: "<<count<<endl; } for (int i = 0; i < s->numParts; i++) { if (parts[i] == 0) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"partition "<<i<<" seems to be missing"<<endl; } } return valid; } } <commit_msg>Removed bug where an array would be left uninitialized<commit_after>/// This file contains the implementation of VNS #include "header/vns-priv.hpp" using namespace std; namespace pcp { Solution bestSolution; Solution origSolution; bool checkValid(Solution* s); /// Some constants const int NUM_VNS = 2; const int SHAKE_START = 1; /// Implementation of VNS, see vns.hpp Solution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) { /// Backup the starting solutions bestSolution = new Solution(best); origSolution = new Solution(orig); if (DEBUG_LEVEL > 1) { cout<<"Best solution uses "<<bestSolution.colorsUsed<<" colors"<<endl; cout<<"Full solution uses "<<origSolution.colorsUsed<<" colors"<<endl; } if (DEBUG_LEVEL > 1) { cout<<"The supplied solution is valid: "<<(checkValid(&best) ? "true": "false")<<endl; } /// Define the neighborhoods to use VNS_Unit **neighbors = new VNS_Unit*[NUM_VNS]; changeNode *cN = new changeNode; changeColor *cC = new changeColor; neighbors[0] = cN; neighbors[1] = cC; time_t startTime = time(NULL); int no_imp_runs = 0; int curNeighbor = 0; int shakeSteps = shakeStart - shakeIncrement; Solution *toImprove = new Solution(&best); Solution *curBest = &best; /// Run as long as shaking still produces usefull solution while (true) { /// Run all possible neighborhood while (curNeighbor < NUM_VNS) { /// Select the new neighborhood VNS_Unit *neigh = neighbors[curNeighbor]; if (DEBUG_LEVEL > 1) { cout<<"Running: "<< neigh->name() <<endl; } /// Compute the minimum for this neighborhood Solution *improved = neigh->findLocalMin(best, orig); if (DEBUG_LEVEL > 1) { cout<<"Valid solution: "<<((checkValid(improved)) ? "true" : "false"); cout<<endl; } /// Replace the existing solution with the new solution if it is an /// improvement if (improved->colorsUsed < toImprove->colorsUsed) { delete toImprove; toImprove = improved; if (DEBUG_LEVEL > 1) { cout<<"Improvement found with "<<neigh->name()<<endl; } /// Restart neighborhoods curNeighbor = curNeighbor == 0 ? 1 : 0; } /// Step to next neighborhood, no improvement found else { if (DEBUG_LEVEL > 1) { cout<<"No improvement found"<<endl; cout<<"Test next neighborhood"<<endl; } delete improved; curNeighbor++; } if (DEBUG_LEVEL > 1) { cout<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; cout<<endl<<endl; } } // end while neighborhood /// Local minimum of neighborhoods is better than current best /// solution if (toImprove->colorsUsed < best.colorsUsed) { if (DEBUG_LEVEL > 1) { cout<<"Improvement to global best solution found"<<endl; } best = toImprove; toImprove = new Solution(curBest); no_imp_runs = 0; shakeSteps = shakeStart - shakeIncrement; } /// Reset local best solution to global best Solution else { toImprove = curBest; no_imp_runs++; /// Stopping condition, quit VNS if (no_imp_runs > unsuccessfulShake) { break; } } int shakeNeighbor = rand() % NUM_VNS; VNS_Unit *shaker = neighbors[shakeNeighbor]; toImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement)); /// No time left, abort main loop if (startTime + maxTime < time(NULL)) { if (DEBUG_LEVEL > 0) { cout<<"Time's up"<<endl; } break; } } return new Solution(curBest); } bool checkValid(Solution* s) { pair<VertexIter, VertexIter> vIter; int parts[s->numParts]; int colors[s->numParts]; typedef boost::graph_traits<Graph>::adjacency_iterator AdjIter; VertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g); bool valid = true; for (int i = 0; i < s->numParts; i++) { parts[i] = 0; colors[i] = 0; } for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) { parts[vParts[*vIter.first]] = 1; colors[s->partition[vParts[*vIter.first]]] = 1; pair<AdjIter, AdjIter> aIter; for (aIter = adjacent_vertices(*vIter.first, *s->g); aIter.first != aIter.second; aIter.first++) { if (s->partition[vParts[*aIter.first]] == s->partition[vParts[*vIter.first]]) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Adjacent vertices "<<*aIter.first<<" and "<<*vIter.first; cerr<<" have same color "<<s->partition[vParts[*vIter.first]]; cerr<<endl; } } } int count = 0; for (int i = 0; i < s->numParts; i++) { if (colors[i] == 1) { count++; } } if (count != s->colorsUsed) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Wrong colorsUsed stored: stored: "<<s->colorsUsed; cerr<<", computed: "<<count<<endl; } for (int i = 0; i < s->numParts; i++) { if (parts[i] == 0) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"partition "<<i<<" seems to be missing"<<endl; } } return valid; } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_HH #define DUNE_STUFF_FUNCTIONS_EXPRESSION_HH #include <vector> #include <limits> #include <dune/common/fvector.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/exceptions.hh> #include "expression/base.hh" #include "interfaces.hh" #include "default.hh" #include "constant.hh" namespace Dune { namespace Stuff { namespace Functions { /** * \attention If you add the create() and default_config() method, do not forget to enable the matrix valued * versions in test/function_expression.cc */ template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 > class Expression : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim*rangeDimCols > MathExpressionFunctionType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const size_t dimRange = BaseType::dimRange; static const size_t dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const std::shared_ptr< const MathExpressionFunctionType >& function, const size_t ord) : BaseType(ent) , function_(function) , order_(ord) , tmp_vector_(0) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override { return order_; } virtual void evaluate(const DomainType& xx, RangeType& ret) const override { function_->evaluate(this->entity().geometry().global(xx), tmp_vector_); for (size_t ii = 0; ii < dimRange; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < dimRangeCols; ++jj) { retRow[jj] = tmp_vector_[ii*dimRange + jj]; } } } // ... evaluate(...) virtual void jacobian(const DomainType& /*xx*/, JacobianRangeType& /*ret*/) const override { DUNE_THROW(NotImplemented, "Once we decided on the JacobianRangeType of matrix valued functions we have to implement " << "gradients for this function!"); } private: const std::shared_ptr< const MathExpressionFunctionType > function_; const size_t order_; mutable FieldVector< RangeFieldType, dimRange*dimRangeCols > tmp_vector_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static std::string static_id() { return BaseType::static_id() + ".expression"; } Expression(const std::string variable, const std::string expression, const size_t ord = 0, const std::string nm = static_id()) : function_(new MathExpressionFunctionType(variable, expression)) , order_(ord) , name_(nm) {} Expression(const std::string variable, const std::vector< std::string > expressions, const size_t ord = 0, const std::string nm = static_id()) : function_(new MathExpressionFunctionType(variable, expressions)) , order_(ord) , name_(nm) {} Expression(const ThisType& other) = default; ThisType& operator=(const ThisType& other) { if (this != &other) { function_ = other.function_; order_ = other.order_; name_ = other.name_; } return *this; } virtual std::string type() const override final { return BaseType::static_id() + ".expression"; } virtual std::string name() const override { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override { return std::unique_ptr< Localfunction >(new Localfunction(entity, function_, order_)); } private: std::shared_ptr< const MathExpressionFunctionType > function_; size_t order_; std::string name_; }; // class Expression template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim > class Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType; typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > ThisType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > MathExpressionFunctionType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, domainDim > MathExpressionGradientType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const size_t dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; static const size_t dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".expression"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["variable"] = "x"; config["expression"] = "[x[0] sin(x[0]) exp(x[0])]"; config["order"] = "3"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // get gradient std::vector< std::vector < std::string > > gradient_as_vectors; if (cfg.has_key("gradient")) { // get gradient as FieldMatrix typedef typename Dune::FieldMatrix< std::string, dimRange, dimDomain > JacobianMatrixType; const JacobianMatrixType gradient_as_matrix = cfg.get< JacobianMatrixType >("gradient"); // convert FieldMatrix to std::vector< std::vector < std::string > > assert(gradient_as_matrix.rows >= dimRange); assert(gradient_as_matrix.cols >= dimDomain); for (size_t rr = 0; rr < dimRange; ++rr) { std::vector< std::string > gradient_expression; for (size_t cc = 0; cc < dimDomain; ++cc) gradient_expression.emplace_back(gradient_as_matrix[rr][cc]); gradient_as_vectors.emplace_back(gradient_expression); } } // create return Common::make_unique< ThisType >( cfg.get("variable", default_cfg.get< std::string >("variable")), cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")), cfg.get("order", default_cfg.get< size_t >("order")), cfg.get("name", default_cfg.get< std::string >("name")), gradient_as_vectors); } // ... create(...) Expression(const std::string variable, const std::string expression, const size_t ord = default_config().get< size_t >("order"), const std::string nm = static_id(), const std::vector< std::vector< std::string > > gradient_expressions = std::vector< std::vector< std::string > >()) : function_(new MathExpressionFunctionType(variable, expression)) , order_(ord) , name_(nm) { build_gradients(variable, gradient_expressions); } Expression(const std::string variable, const std::vector< std::string > expressions, const size_t ord = default_config().get< size_t >("order"), const std::string nm = static_id(), const std::vector< std::vector< std::string > > gradient_expressions = std::vector< std::vector< std::string > >()) : function_(new MathExpressionFunctionType(variable, expressions)) , order_(ord) , name_(nm) { build_gradients(variable, gradient_expressions); } virtual std::string name() const override { return name_; } virtual size_t order() const override { return order_; } virtual void evaluate(const DomainType& xx, RangeType& ret) const override { function_->evaluate(xx, ret); #ifndef NDEBUG # ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS bool failure = false; std::string type; if (std::isnan(ret[0])) { failure = true; type = "NaN"; } else if (std::isinf(ret[0])) { failure = true; type = "inf"; } else if (std::abs(ret[0]) > (0.9 * std::numeric_limits< double >::max())) { failure = true; type = "an unlikely value"; } if (failure) DUNE_THROW(Stuff::Exceptions::internal_error, "evaluating this function yielded " << type << "!\n" << "The variable of this function is: " << function_->variable() << "\n" << "The expression of this functional is: " << function_->expression().at(0) << "\n" << "You tried to evaluate it with: xx = " << xx << "\n" << "The result was: " << ret << "\n\n" << "You can disable this check by defining DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS\n"); # endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS #endif // NDEBUG } // ... evaluate(...) virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override { if (gradients_.size() == 0) DUNE_THROW(NotImplemented, "This function does not provide any gradients!"); assert(gradients_.size() == dimRange); for (size_t ii = 0; ii < dimRange; ++ii) { gradients_[ii]->evaluate(xx, ret[ii]); } } // ... jacobian(...) private: void build_gradients(const std::string variable, const std::vector< std::vector< std::string > >& gradient_expressions) { assert(gradient_expressions.size() == 0 || gradient_expressions.size() >= dimRange); if (gradient_expressions.size() > 0) for (size_t rr = 0; rr < dimRange; ++rr) { const auto& gradient_expression = gradient_expressions[rr]; assert(gradient_expression.size() >= dimDomain); gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression)); } } // ... build_gradients(...) std::shared_ptr< const MathExpressionFunctionType > function_; size_t order_; std::string name_; std::vector< std::shared_ptr< const MathExpressionGradientType > > gradients_; }; // class Expression< ..., 1 > } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_HH <commit_msg>[functions.expression] remove assertions<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_HH #define DUNE_STUFF_FUNCTIONS_EXPRESSION_HH #include <vector> #include <limits> #include <dune/common/fvector.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/exceptions.hh> #include "expression/base.hh" #include "interfaces.hh" #include "default.hh" #include "constant.hh" namespace Dune { namespace Stuff { namespace Functions { /** * \attention If you add the create() and default_config() method, do not forget to enable the matrix valued * versions in test/function_expression.cc */ template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 > class Expression : public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalizableFunctionInterface < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim*rangeDimCols > MathExpressionFunctionType; class Localfunction : public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > { typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const size_t dimRange = BaseType::dimRange; static const size_t dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; Localfunction(const EntityType& ent, const std::shared_ptr< const MathExpressionFunctionType >& function, const size_t ord) : BaseType(ent) , function_(function) , order_(ord) , tmp_vector_(0) {} Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override { return order_; } virtual void evaluate(const DomainType& xx, RangeType& ret) const override { function_->evaluate(this->entity().geometry().global(xx), tmp_vector_); for (size_t ii = 0; ii < dimRange; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < dimRangeCols; ++jj) { retRow[jj] = tmp_vector_[ii*dimRange + jj]; } } } // ... evaluate(...) virtual void jacobian(const DomainType& /*xx*/, JacobianRangeType& /*ret*/) const override { DUNE_THROW(NotImplemented, "Once we decided on the JacobianRangeType of matrix valued functions we have to implement " << "gradients for this function!"); } private: const std::shared_ptr< const MathExpressionFunctionType > function_; const size_t order_; mutable FieldVector< RangeFieldType, dimRange*dimRangeCols > tmp_vector_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static std::string static_id() { return BaseType::static_id() + ".expression"; } Expression(const std::string variable, const std::string expression, const size_t ord = 0, const std::string nm = static_id()) : function_(new MathExpressionFunctionType(variable, expression)) , order_(ord) , name_(nm) {} Expression(const std::string variable, const std::vector< std::string > expressions, const size_t ord = 0, const std::string nm = static_id()) : function_(new MathExpressionFunctionType(variable, expressions)) , order_(ord) , name_(nm) {} Expression(const ThisType& other) = default; ThisType& operator=(const ThisType& other) { if (this != &other) { function_ = other.function_; order_ = other.order_; name_ = other.name_; } return *this; } virtual std::string type() const override final { return BaseType::static_id() + ".expression"; } virtual std::string name() const override { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override { return std::unique_ptr< Localfunction >(new Localfunction(entity, function_, order_)); } private: std::shared_ptr< const MathExpressionFunctionType > function_; size_t order_; std::string name_; }; // class Expression template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim > class Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType; typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > ThisType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > MathExpressionFunctionType; typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, domainDim > MathExpressionGradientType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const size_t dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; static const size_t dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".expression"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["variable"] = "x"; config["expression"] = "[x[0] sin(x[0]) exp(x[0])]"; config["order"] = "3"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // get gradient std::vector< std::vector < std::string > > gradient_as_vectors; if (cfg.has_key("gradient")) { // get gradient as FieldMatrix typedef typename Dune::FieldMatrix< std::string, dimRange, dimDomain > JacobianMatrixType; const JacobianMatrixType gradient_as_matrix = cfg.get< JacobianMatrixType >("gradient"); // convert FieldMatrix to std::vector< std::vector < std::string > > for (size_t rr = 0; rr < dimRange; ++rr) { std::vector< std::string > gradient_expression; for (size_t cc = 0; cc < dimDomain; ++cc) gradient_expression.emplace_back(gradient_as_matrix[rr][cc]); gradient_as_vectors.emplace_back(gradient_expression); } } // create return Common::make_unique< ThisType >( cfg.get("variable", default_cfg.get< std::string >("variable")), cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")), cfg.get("order", default_cfg.get< size_t >("order")), cfg.get("name", default_cfg.get< std::string >("name")), gradient_as_vectors); } // ... create(...) Expression(const std::string variable, const std::string expression, const size_t ord = default_config().get< size_t >("order"), const std::string nm = static_id(), const std::vector< std::vector< std::string > > gradient_expressions = std::vector< std::vector< std::string > >()) : function_(new MathExpressionFunctionType(variable, expression)) , order_(ord) , name_(nm) { build_gradients(variable, gradient_expressions); } Expression(const std::string variable, const std::vector< std::string > expressions, const size_t ord = default_config().get< size_t >("order"), const std::string nm = static_id(), const std::vector< std::vector< std::string > > gradient_expressions = std::vector< std::vector< std::string > >()) : function_(new MathExpressionFunctionType(variable, expressions)) , order_(ord) , name_(nm) { build_gradients(variable, gradient_expressions); } virtual std::string name() const override { return name_; } virtual size_t order() const override { return order_; } virtual void evaluate(const DomainType& xx, RangeType& ret) const override { function_->evaluate(xx, ret); #ifndef NDEBUG # ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS bool failure = false; std::string type; if (std::isnan(ret[0])) { failure = true; type = "NaN"; } else if (std::isinf(ret[0])) { failure = true; type = "inf"; } else if (std::abs(ret[0]) > (0.9 * std::numeric_limits< double >::max())) { failure = true; type = "an unlikely value"; } if (failure) DUNE_THROW(Stuff::Exceptions::internal_error, "evaluating this function yielded " << type << "!\n" << "The variable of this function is: " << function_->variable() << "\n" << "The expression of this functional is: " << function_->expression().at(0) << "\n" << "You tried to evaluate it with: xx = " << xx << "\n" << "The result was: " << ret << "\n\n" << "You can disable this check by defining DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS\n"); # endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS #endif // NDEBUG } // ... evaluate(...) virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override { if (gradients_.size() == 0) DUNE_THROW(NotImplemented, "This function does not provide any gradients!"); assert(gradients_.size() == dimRange); for (size_t ii = 0; ii < dimRange; ++ii) { gradients_[ii]->evaluate(xx, ret[ii]); } } // ... jacobian(...) private: void build_gradients(const std::string variable, const std::vector< std::vector< std::string > >& gradient_expressions) { assert(gradient_expressions.size() == 0 || gradient_expressions.size() >= dimRange); if (gradient_expressions.size() > 0) for (size_t rr = 0; rr < dimRange; ++rr) { const auto& gradient_expression = gradient_expressions[rr]; assert(gradient_expression.size() >= dimDomain); gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression)); } } // ... build_gradients(...) std::shared_ptr< const MathExpressionFunctionType > function_; size_t order_; std::string name_; std::vector< std::shared_ptr< const MathExpressionGradientType > > gradients_; }; // class Expression< ..., 1 > } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_HH <|endoftext|>
<commit_before>/** * @file * * @brief Tests for the Backend builder class * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <gtest/gtest-elektra.h> #include <kdb.hpp> #include <regex> class Ensure : public ::testing::Test { protected: static const char * testRoot; static const char * configFileRoot; std::string specRoot; std::string userRoot; testing::Namespaces namespaces; testing::MountpointPtr mpRoot; Ensure () : specRoot (std::string ("spec") + testRoot), userRoot (std::string ("user") + testRoot), namespaces () { } virtual void SetUp () override { mpRoot.reset (new testing::Mountpoint (testRoot, configFileRoot)); using namespace kdb; KDB kdb; KeySet ks; kdb.get (ks, testRoot); ks.append (Key (specRoot + "/speckey/#", KEY_META, "mymeta", "1", KEY_END)); ks.append (Key (userRoot + "/speckey", KEY_META, "array", "#0", KEY_END)); ks.append (Key (userRoot + "/speckey/#0", KEY_VALUE, "", KEY_END)); ks.append (Key (userRoot + "/errorkey", KEY_META, "trigger/warnings", "3", KEY_END)); // ks.append (Key (specRoot + "/goptskey", KEY_META, "opt", "1", KEY_END)); kdb.set (ks, testRoot); } virtual void TearDown () override { mpRoot.reset (); } static bool checkTracerOutput (const std::string & capture); }; const char * Ensure::testRoot = "/tests/kdb/ensure"; const char * Ensure::configFileRoot = "kdbFileEnsure.dump"; TEST_F (Ensure, GlobalUnmount) { using namespace kdb; KDB kdb; { KeySet ks; kdb.get (ks, testRoot); EXPECT_EQ (ks.lookup (userRoot + "/speckey/#0", 0).getMeta<std::string> ("mymeta"), "1") << "spec plugin didn't run"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/global/spec", KEY_VALUE, "unmounted", KEY_END)); Key root (specRoot, KEY_END); kdb.ensure (contract, root); KeySet ks; kdb.get (ks, testRoot); EXPECT_FALSE (ks.lookup (userRoot + "/speckey/#0", 0).hasMeta ("mymeta")) << "spec plugin shouldn't have run"; kdb.ensure (contract, root); kdb.get (ks, testRoot); EXPECT_FALSE (ks.lookup (userRoot + "/speckey/#0", 0).hasMeta ("mymeta")) << "global unmount should be idempotent"; } } TEST_F (Ensure, Unmount) { using namespace kdb; KDB kdb; { KeySet ks; Key root (testRoot, KEY_END); kdb.get (ks, root); kdb.set (ks, root); EXPECT_EQ (root.getMeta<std::string> ("warnings/#00/number"), "C01310") << "error plugin didn't run"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/parent/error", KEY_VALUE, "unmounted", KEY_END)); Key uroot (userRoot, KEY_END); kdb.ensure (contract, uroot); KeySet ks; Key root (testRoot, KEY_END); kdb.get (ks, root); kdb.set (ks, root); EXPECT_FALSE (root.hasMeta ("warnings")) << "error plugin shouldn't have run"; root.delMeta ("warnings"); kdb.ensure (contract, uroot); kdb.get (ks, root); kdb.set (ks, root); EXPECT_FALSE (root.hasMeta ("warnings")) << "unmount should be idempotent"; } } bool Ensure::checkTracerOutput (const std::string & capture) { EXPECT_FALSE (capture.empty ()) << "tracer plugin not run"; std::istringstream lines (capture); std::string line; size_t i = 0; bool success = true; while (std::getline (lines, line)) { std::smatch match; success = success && std::regex_match (line, match, std::regex (R"(^tracer: .*$)")); EXPECT_TRUE (success) << "A line didn't match the expected tracer output:" << std::endl << "line: " << line << std::endl; ++i; } return success; } TEST_F (Ensure, GlobalMount) { using namespace kdb; KDB kdb; Key parent (testRoot, KEY_META, "debugGlobalPositions", "", KEY_END); { testing::internal::CaptureStdout (); KeySet ks; kdb.get (ks, parent); EXPECT_TRUE (testing::internal::GetCapturedStdout ().empty ()) << "there should be no output on stdout"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/global/tracer", KEY_VALUE, "mounted", KEY_END)); Key root (specRoot, KEY_END); kdb.ensure (contract, root); testing::internal::CaptureStdout (); KeySet ks; kdb.get (ks, parent); { SCOPED_TRACE ("first ensure"); EXPECT_TRUE (checkTracerOutput (testing::internal::GetCapturedStdout ())) << "tracer output didn't match"; } kdb.ensure (contract, root); testing::internal::CaptureStdout (); kdb.get (ks, parent); { SCOPED_TRACE ("second ensure"); EXPECT_TRUE (checkTracerOutput (testing::internal::GetCapturedStdout ())) << "global mount should be idempotent"; } } } <commit_msg>core: add ensure global remount test<commit_after>/** * @file * * @brief Tests for the Backend builder class * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <gtest/gtest-elektra.h> #include <kdb.hpp> #include <regex> class Ensure : public ::testing::Test { protected: static const char * testRoot; static const char * configFileRoot; std::string specRoot; std::string userRoot; testing::Namespaces namespaces; testing::MountpointPtr mpRoot; Ensure () : specRoot (std::string ("spec") + testRoot), userRoot (std::string ("user") + testRoot), namespaces () { } virtual void SetUp () override { mpRoot.reset (new testing::Mountpoint (testRoot, configFileRoot)); using namespace kdb; KDB kdb; KeySet ks; kdb.get (ks, testRoot); ks.append (Key (specRoot + "/speckey/#", KEY_META, "mymeta", "1", KEY_END)); ks.append (Key (userRoot + "/speckey", KEY_META, "array", "#0", KEY_END)); ks.append (Key (userRoot + "/speckey/#0", KEY_VALUE, "", KEY_END)); ks.append (Key (userRoot + "/errorkey", KEY_META, "trigger/warnings", "3", KEY_END)); kdb.set (ks, testRoot); } virtual void TearDown () override { mpRoot.reset (); } static bool checkTracerOutput (const std::string & capture); }; const char * Ensure::testRoot = "/tests/kdb/ensure"; const char * Ensure::configFileRoot = "kdbFileEnsure.dump"; TEST_F (Ensure, GlobalUnmount) { using namespace kdb; KDB kdb; { KeySet ks; kdb.get (ks, testRoot); EXPECT_EQ (ks.lookup (userRoot + "/speckey/#0", 0).getMeta<std::string> ("mymeta"), "1") << "spec plugin didn't run"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/global/spec", KEY_VALUE, "unmounted", KEY_END)); Key root (specRoot, KEY_END); kdb.ensure (contract, root); KeySet ks; kdb.get (ks, testRoot); EXPECT_FALSE (ks.lookup (userRoot + "/speckey/#0", 0).hasMeta ("mymeta")) << "spec plugin shouldn't have run"; kdb.ensure (contract, root); kdb.get (ks, testRoot); EXPECT_FALSE (ks.lookup (userRoot + "/speckey/#0", 0).hasMeta ("mymeta")) << "global unmount should be idempotent"; } } TEST_F (Ensure, GlobalRemount) { using namespace kdb; { KDB kdb; KeySet ks; kdb.get (ks, testRoot); ks.append (Key (specRoot + "/otherspeckey", KEY_META, "require", "", KEY_END)); kdb.set (ks, testRoot); } { KDB kdb; KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/global/spec", KEY_VALUE, "remount", KEY_END)); contract.append (Key ("system/elektra/ensure/plugins/global/spec/config/conflict/get", KEY_VALUE, "ERROR", KEY_END)); contract.append (Key ("system/elektra/ensure/plugins/global/spec/config/conflict/set", KEY_VALUE, "ERROR", KEY_END)); Key root (specRoot, KEY_END); kdb.ensure (contract, root); Key newRoot (testRoot, KEY_END); KeySet ks; kdb.get (ks, newRoot); EXPECT_EQ (newRoot.getMeta<std::string> ("error/number"), "142") << "spec plugin should have produced error"; } } TEST_F (Ensure, Unmount) { using namespace kdb; KDB kdb; { KeySet ks; Key root (testRoot, KEY_END); kdb.get (ks, root); kdb.set (ks, root); EXPECT_EQ (root.getMeta<std::string> ("warnings/#00/number"), "C01310") << "error plugin didn't run"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/parent/error", KEY_VALUE, "unmounted", KEY_END)); Key uroot (userRoot, KEY_END); kdb.ensure (contract, uroot); KeySet ks; Key root (testRoot, KEY_END); kdb.get (ks, root); kdb.set (ks, root); EXPECT_FALSE (root.hasMeta ("warnings")) << "error plugin shouldn't have run"; root.delMeta ("warnings"); kdb.ensure (contract, uroot); kdb.get (ks, root); kdb.set (ks, root); EXPECT_FALSE (root.hasMeta ("warnings")) << "unmount should be idempotent"; } } bool Ensure::checkTracerOutput (const std::string & capture) { EXPECT_FALSE (capture.empty ()) << "tracer plugin not run"; std::istringstream lines (capture); std::string line; size_t i = 0; bool success = true; while (std::getline (lines, line)) { std::smatch match; success = success && std::regex_match (line, match, std::regex (R"(^tracer: .*$)")); EXPECT_TRUE (success) << "A line didn't match the expected tracer output:" << std::endl << "line: " << line << std::endl; ++i; } return success; } TEST_F (Ensure, GlobalMount) { using namespace kdb; KDB kdb; Key parent (testRoot, KEY_META, "debugGlobalPositions", "", KEY_END); { testing::internal::CaptureStdout (); KeySet ks; kdb.get (ks, parent); EXPECT_TRUE (testing::internal::GetCapturedStdout ().empty ()) << "there should be no output on stdout"; } { KeySet contract; contract.append (Key ("system/elektra/ensure/plugins/global/tracer", KEY_VALUE, "mounted", KEY_END)); Key root (specRoot, KEY_END); kdb.ensure (contract, root); testing::internal::CaptureStdout (); KeySet ks; kdb.get (ks, parent); { SCOPED_TRACE ("first ensure"); EXPECT_TRUE (checkTracerOutput (testing::internal::GetCapturedStdout ())) << "tracer output didn't match"; } kdb.ensure (contract, root); testing::internal::CaptureStdout (); kdb.get (ks, parent); { SCOPED_TRACE ("second ensure"); EXPECT_TRUE (checkTracerOutput (testing::internal::GetCapturedStdout ())) << "global mount should be idempotent"; } } } <|endoftext|>
<commit_before>/* */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0) */ #include <chrono> #include <seastar/core/future-util.hh> #include <seastar/core/do_with.hh> #include <seastar/core/semaphore.hh> #include <seastar/core/metrics.hh> #include <seastar/core/coroutine.hh> #include <seastar/core/sleep.hh> #include <boost/range/adaptor/map.hpp> #include <boost/range/adaptor/sliced.hpp> #include "batchlog_manager.hh" #include "canonical_mutation.hh" #include "service/storage_proxy.hh" #include "system_keyspace.hh" #include "utils/rate_limiter.hh" #include "log.hh" #include "serializer.hh" #include "db_clock.hh" #include "unimplemented.hh" #include "gms/failure_detector.hh" #include "gms/gossiper.hh" #include "schema_registry.hh" #include "idl/uuid.dist.hh" #include "idl/frozen_schema.dist.hh" #include "serializer_impl.hh" #include "serialization_visitors.hh" #include "db/schema_tables.hh" #include "idl/uuid.dist.impl.hh" #include "idl/frozen_schema.dist.impl.hh" #include "message/messaging_service.hh" #include "cql3/untyped_result_set.hh" #include "service_permit.hh" #include "cql3/query_processor.hh" static logging::logger blogger("batchlog_manager"); const uint32_t db::batchlog_manager::replay_interval; const uint32_t db::batchlog_manager::page_size; db::batchlog_manager::batchlog_manager(cql3::query_processor& qp, batchlog_manager_config config) : _qp(qp) , _write_request_timeout(std::chrono::duration_cast<db_clock::duration>(config.write_request_timeout)) , _replay_rate(config.replay_rate) , _started(make_ready_future<>()) , _delay(config.delay) { namespace sm = seastar::metrics; _metrics.add_group("batchlog_manager", { sm::make_derive("total_write_replay_attempts", _stats.write_attempts, sm::description("Counts write operations issued in a batchlog replay flow. " "The high value of this metric indicates that we have a long batch replay list.")), }); } future<> db::batchlog_manager::do_batch_log_replay() { return container().invoke_on(0, [] (auto& bm) -> future<> { auto gate_holder = bm._gate.hold(); auto sem_units = co_await get_units(bm._sem, 1); auto dest = bm._cpu++ % smp::count; blogger.debug("Batchlog replay on shard {}: starts", dest); if (dest == 0) { co_await bm.replay_all_failed_batches(); } else { co_await bm.container().invoke_on(dest, [] (auto& bm) { return with_gate(bm._gate, [&bm] { return bm.replay_all_failed_batches(); }); }); } blogger.debug("Batchlog replay on shard {}: done", dest); }); } future<> db::batchlog_manager::batchlog_replay_loop() { assert (this_shard_id() == 0); auto delay = _delay; while (!_stop.abort_requested()) { try { co_await sleep_abortable(delay, _stop); } catch (sleep_aborted&) { co_return; } try { co_await do_batch_log_replay(); } catch (...) { blogger.error("Exception in batch replay: {}", std::current_exception()); } delay = std::chrono::milliseconds(replay_interval); } } future<> db::batchlog_manager::start() { // Since replay is a "node global" operation, we should not attempt to do // it in parallel on each shard. It will just overlap/interfere. To // simplify syncing between batchlog_replay_loop and user initiated replay operations, // we use the _sem on shard zero only. Replaying batchlog can // generate a lot of work, so we distrute the real work on all cpus with // round-robin scheduling. if (this_shard_id() == 0) { _started = batchlog_replay_loop(); } return make_ready_future<>(); } future<> db::batchlog_manager::drain() { if (!_stop.abort_requested()) { _stop.request_abort(); } if (this_shard_id() == 0) { // Abort do_batch_log_replay if waiting on the semaphore. _sem.broken(); } return with_gate(_gate, [this] { return std::exchange(_started, make_ready_future<>()); }); } future<> db::batchlog_manager::stop() { return drain().finally([this] { return _gate.close(); }); } future<size_t> db::batchlog_manager::count_all_batches() const { sstring query = format("SELECT count(*) FROM {}.{}", system_keyspace::NAME, system_keyspace::BATCHLOG); return _qp.execute_internal(query).then([](::shared_ptr<cql3::untyped_result_set> rs) { return size_t(rs->one().get_as<int64_t>("count")); }); } db_clock::duration db::batchlog_manager::get_batch_log_timeout() const { // enough time for the actual write + BM removal mutation return _write_request_timeout * 2; } future<> db::batchlog_manager::replay_all_failed_batches() { typedef db_clock::rep clock_type; // rate limit is in bytes per second. Uses Double.MAX_VALUE if disabled (set to 0 in cassandra.yaml). // max rate is scaled by the number of nodes in the cluster (same as for HHOM - see CASSANDRA-5272). auto throttle = _replay_rate / _qp.proxy().get_token_metadata_ptr()->count_normal_token_owners(); auto limiter = make_lw_shared<utils::rate_limiter>(throttle); auto batch = [this, limiter](const cql3::untyped_result_set::row& row) { auto written_at = row.get_as<db_clock::time_point>("written_at"); auto id = row.get_as<utils::UUID>("id"); // enough time for the actual write + batchlog entry mutation delivery (two separate requests). auto timeout = get_batch_log_timeout(); if (db_clock::now() < written_at + timeout) { blogger.debug("Skipping replay of {}, too fresh", id); return make_ready_future<>(); } // check version of serialization format if (!row.has("version")) { blogger.warn("Skipping logged batch because of unknown version"); return make_ready_future<>(); } auto version = row.get_as<int32_t>("version"); if (version != netw::messaging_service::current_version) { blogger.warn("Skipping logged batch because of incorrect version"); return make_ready_future<>(); } auto data = row.get_blob("data"); blogger.debug("Replaying batch {}", id); auto fms = make_lw_shared<std::deque<canonical_mutation>>(); auto in = ser::as_input_stream(data); while (in.size()) { fms->emplace_back(ser::deserialize(in, boost::type<canonical_mutation>())); } auto size = data.size(); return map_reduce(*fms, [this, written_at] (canonical_mutation& fm) { return system_keyspace::get_truncated_at(fm.column_family_id()).then([written_at, &fm] (db_clock::time_point t) -> std::optional<std::reference_wrapper<canonical_mutation>> { if (written_at > t) { return { std::ref(fm) }; } else { return {}; } }); }, std::vector<mutation>(), [this] (std::vector<mutation> mutations, std::optional<std::reference_wrapper<canonical_mutation>> fm) { if (fm) { schema_ptr s = _qp.db().find_schema(fm.value().get().column_family_id()); mutations.emplace_back(fm.value().get().to_mutation(s)); } return mutations; }).then([this, id, limiter, written_at, size, fms] (std::vector<mutation> mutations) { if (mutations.empty()) { return make_ready_future<>(); } const auto ttl = [this, &mutations, written_at]() -> clock_type { /* * Calculate ttl for the mutations' hints (and reduce ttl by the time the mutations spent in the batchlog). * This ensures that deletes aren't "undone" by an old batch replay. */ auto unadjusted_ttl = std::numeric_limits<gc_clock::rep>::max(); warn(unimplemented::cause::HINT); #if 0 for (auto& m : *mutations) { unadjustedTTL = Math.min(unadjustedTTL, HintedHandOffManager.calculateHintTTL(mutation)); } #endif return unadjusted_ttl - std::chrono::duration_cast<gc_clock::duration>(db_clock::now() - written_at).count(); }(); if (ttl <= 0) { return make_ready_future<>(); } // Origin does the send manually, however I can't see a super great reason to do so. // Our normal write path does not add much redundancy to the dispatch, and rate is handled after send // in both cases. // FIXME: verify that the above is reasonably true. return limiter->reserve(size).then([this, mutations = std::move(mutations), id] { _stats.write_attempts += mutations.size(); // #1222 - change cl level to ALL, emulating origins behaviour of sending/hinting // to all natural end points. // Note however that origin uses hints here, and actually allows for this // send to partially or wholly fail in actually sending stuff. Since we don't // have hints (yet), send with CL=ALL, and hope we can re-do this soon. // See below, we use retry on write failure. return _qp.proxy().mutate(mutations, db::consistency_level::ALL, db::no_timeout, nullptr, empty_service_permit()); }); }).then_wrapped([this, id](future<> batch_result) { try { batch_result.get(); } catch (data_dictionary::no_such_keyspace& ex) { // should probably ignore and drop the batch } catch (...) { // timeout, overload etc. // Do _not_ remove the batch, assuning we got a node write error. // Since we don't have hints (which origin is satisfied with), // we have to resort to keeping this batch to next lap. return make_ready_future<>(); } // delete batch auto schema = _qp.db().find_schema(system_keyspace::NAME, system_keyspace::BATCHLOG); auto key = partition_key::from_singular(*schema, id); mutation m(schema, key); auto now = service::client_state(service::client_state::internal_tag()).get_timestamp(); m.partition().apply_delete(*schema, clustering_key_prefix::make_empty(), tombstone(now, gc_clock::now())); return _qp.proxy().mutate_locally(m, tracing::trace_state_ptr(), db::commitlog::force_sync::no); }); }; return seastar::with_gate(_gate, [this, batch = std::move(batch)] { blogger.debug("Started replayAllFailedBatches (cpu {})", this_shard_id()); typedef ::shared_ptr<cql3::untyped_result_set> page_ptr; sstring query = format("SELECT id, data, written_at, version FROM {}.{} LIMIT {:d}", system_keyspace::NAME, system_keyspace::BATCHLOG, page_size); return _qp.execute_internal(query).then([this, batch = std::move(batch)](page_ptr page) { return do_with(std::move(page), [this, batch = std::move(batch)](page_ptr & page) mutable { return repeat([this, &page, batch = std::move(batch)]() mutable { if (page->empty()) { return make_ready_future<stop_iteration>(stop_iteration::yes); } auto id = page->back().get_as<utils::UUID>("id"); return parallel_for_each(*page, batch).then([this, &page, id]() { if (page->size() < page_size) { return make_ready_future<stop_iteration>(stop_iteration::yes); // we've exhausted the batchlog, next query would be empty. } sstring query = format("SELECT id, data, written_at, version FROM {}.{} WHERE token(id) > token(?) LIMIT {:d}", system_keyspace::NAME, system_keyspace::BATCHLOG, page_size); return _qp.execute_internal(query, {id}).then([&page](auto res) { page = std::move(res); return make_ready_future<stop_iteration>(stop_iteration::no); }); }); }); }); }).then([this] { // TODO FIXME : cleanup() #if 0 ColumnFamilyStore cfs = Keyspace.open(SystemKeyspace.NAME).getColumnFamilyStore(SystemKeyspace.BATCHLOG); cfs.forceBlockingFlush(); Collection<Descriptor> descriptors = new ArrayList<>(); for (SSTableReader sstr : cfs.getSSTables()) descriptors.add(sstr.descriptor); if (!descriptors.isEmpty()) // don't pollute the logs if there is nothing to compact. CompactionManager.instance.submitUserDefined(cfs, descriptors, Integer.MAX_VALUE).get(); #endif }).then([this] { blogger.debug("Finished replayAllFailedBatches"); }); }); } <commit_msg>batchlog_manager: batchlog_replay_loop: ignore broken_semaphore if abort_requested<commit_after>/* */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0) */ #include <chrono> #include <seastar/core/future-util.hh> #include <seastar/core/do_with.hh> #include <seastar/core/semaphore.hh> #include <seastar/core/metrics.hh> #include <seastar/core/coroutine.hh> #include <seastar/core/sleep.hh> #include <boost/range/adaptor/map.hpp> #include <boost/range/adaptor/sliced.hpp> #include "batchlog_manager.hh" #include "canonical_mutation.hh" #include "service/storage_proxy.hh" #include "system_keyspace.hh" #include "utils/rate_limiter.hh" #include "log.hh" #include "serializer.hh" #include "db_clock.hh" #include "unimplemented.hh" #include "gms/failure_detector.hh" #include "gms/gossiper.hh" #include "schema_registry.hh" #include "idl/uuid.dist.hh" #include "idl/frozen_schema.dist.hh" #include "serializer_impl.hh" #include "serialization_visitors.hh" #include "db/schema_tables.hh" #include "idl/uuid.dist.impl.hh" #include "idl/frozen_schema.dist.impl.hh" #include "message/messaging_service.hh" #include "cql3/untyped_result_set.hh" #include "service_permit.hh" #include "cql3/query_processor.hh" static logging::logger blogger("batchlog_manager"); const uint32_t db::batchlog_manager::replay_interval; const uint32_t db::batchlog_manager::page_size; db::batchlog_manager::batchlog_manager(cql3::query_processor& qp, batchlog_manager_config config) : _qp(qp) , _write_request_timeout(std::chrono::duration_cast<db_clock::duration>(config.write_request_timeout)) , _replay_rate(config.replay_rate) , _started(make_ready_future<>()) , _delay(config.delay) { namespace sm = seastar::metrics; _metrics.add_group("batchlog_manager", { sm::make_derive("total_write_replay_attempts", _stats.write_attempts, sm::description("Counts write operations issued in a batchlog replay flow. " "The high value of this metric indicates that we have a long batch replay list.")), }); } future<> db::batchlog_manager::do_batch_log_replay() { return container().invoke_on(0, [] (auto& bm) -> future<> { auto gate_holder = bm._gate.hold(); auto sem_units = co_await get_units(bm._sem, 1); auto dest = bm._cpu++ % smp::count; blogger.debug("Batchlog replay on shard {}: starts", dest); if (dest == 0) { co_await bm.replay_all_failed_batches(); } else { co_await bm.container().invoke_on(dest, [] (auto& bm) { return with_gate(bm._gate, [&bm] { return bm.replay_all_failed_batches(); }); }); } blogger.debug("Batchlog replay on shard {}: done", dest); }); } future<> db::batchlog_manager::batchlog_replay_loop() { assert (this_shard_id() == 0); auto delay = _delay; while (!_stop.abort_requested()) { try { co_await sleep_abortable(delay, _stop); } catch (sleep_aborted&) { co_return; } try { co_await do_batch_log_replay(); } catch (seastar::broken_semaphore&) { if (_stop.abort_requested()) { co_return; } on_internal_error_noexcept(blogger, fmt::format("Unexcepted exception in batchlog reply: {}", std::current_exception())); } catch (...) { blogger.error("Exception in batch replay: {}", std::current_exception()); } delay = std::chrono::milliseconds(replay_interval); } } future<> db::batchlog_manager::start() { // Since replay is a "node global" operation, we should not attempt to do // it in parallel on each shard. It will just overlap/interfere. To // simplify syncing between batchlog_replay_loop and user initiated replay operations, // we use the _sem on shard zero only. Replaying batchlog can // generate a lot of work, so we distrute the real work on all cpus with // round-robin scheduling. if (this_shard_id() == 0) { _started = batchlog_replay_loop(); } return make_ready_future<>(); } future<> db::batchlog_manager::drain() { if (!_stop.abort_requested()) { _stop.request_abort(); } if (this_shard_id() == 0) { // Abort do_batch_log_replay if waiting on the semaphore. _sem.broken(); } return with_gate(_gate, [this] { return std::exchange(_started, make_ready_future<>()); }); } future<> db::batchlog_manager::stop() { return drain().finally([this] { return _gate.close(); }); } future<size_t> db::batchlog_manager::count_all_batches() const { sstring query = format("SELECT count(*) FROM {}.{}", system_keyspace::NAME, system_keyspace::BATCHLOG); return _qp.execute_internal(query).then([](::shared_ptr<cql3::untyped_result_set> rs) { return size_t(rs->one().get_as<int64_t>("count")); }); } db_clock::duration db::batchlog_manager::get_batch_log_timeout() const { // enough time for the actual write + BM removal mutation return _write_request_timeout * 2; } future<> db::batchlog_manager::replay_all_failed_batches() { typedef db_clock::rep clock_type; // rate limit is in bytes per second. Uses Double.MAX_VALUE if disabled (set to 0 in cassandra.yaml). // max rate is scaled by the number of nodes in the cluster (same as for HHOM - see CASSANDRA-5272). auto throttle = _replay_rate / _qp.proxy().get_token_metadata_ptr()->count_normal_token_owners(); auto limiter = make_lw_shared<utils::rate_limiter>(throttle); auto batch = [this, limiter](const cql3::untyped_result_set::row& row) { auto written_at = row.get_as<db_clock::time_point>("written_at"); auto id = row.get_as<utils::UUID>("id"); // enough time for the actual write + batchlog entry mutation delivery (two separate requests). auto timeout = get_batch_log_timeout(); if (db_clock::now() < written_at + timeout) { blogger.debug("Skipping replay of {}, too fresh", id); return make_ready_future<>(); } // check version of serialization format if (!row.has("version")) { blogger.warn("Skipping logged batch because of unknown version"); return make_ready_future<>(); } auto version = row.get_as<int32_t>("version"); if (version != netw::messaging_service::current_version) { blogger.warn("Skipping logged batch because of incorrect version"); return make_ready_future<>(); } auto data = row.get_blob("data"); blogger.debug("Replaying batch {}", id); auto fms = make_lw_shared<std::deque<canonical_mutation>>(); auto in = ser::as_input_stream(data); while (in.size()) { fms->emplace_back(ser::deserialize(in, boost::type<canonical_mutation>())); } auto size = data.size(); return map_reduce(*fms, [this, written_at] (canonical_mutation& fm) { return system_keyspace::get_truncated_at(fm.column_family_id()).then([written_at, &fm] (db_clock::time_point t) -> std::optional<std::reference_wrapper<canonical_mutation>> { if (written_at > t) { return { std::ref(fm) }; } else { return {}; } }); }, std::vector<mutation>(), [this] (std::vector<mutation> mutations, std::optional<std::reference_wrapper<canonical_mutation>> fm) { if (fm) { schema_ptr s = _qp.db().find_schema(fm.value().get().column_family_id()); mutations.emplace_back(fm.value().get().to_mutation(s)); } return mutations; }).then([this, id, limiter, written_at, size, fms] (std::vector<mutation> mutations) { if (mutations.empty()) { return make_ready_future<>(); } const auto ttl = [this, &mutations, written_at]() -> clock_type { /* * Calculate ttl for the mutations' hints (and reduce ttl by the time the mutations spent in the batchlog). * This ensures that deletes aren't "undone" by an old batch replay. */ auto unadjusted_ttl = std::numeric_limits<gc_clock::rep>::max(); warn(unimplemented::cause::HINT); #if 0 for (auto& m : *mutations) { unadjustedTTL = Math.min(unadjustedTTL, HintedHandOffManager.calculateHintTTL(mutation)); } #endif return unadjusted_ttl - std::chrono::duration_cast<gc_clock::duration>(db_clock::now() - written_at).count(); }(); if (ttl <= 0) { return make_ready_future<>(); } // Origin does the send manually, however I can't see a super great reason to do so. // Our normal write path does not add much redundancy to the dispatch, and rate is handled after send // in both cases. // FIXME: verify that the above is reasonably true. return limiter->reserve(size).then([this, mutations = std::move(mutations), id] { _stats.write_attempts += mutations.size(); // #1222 - change cl level to ALL, emulating origins behaviour of sending/hinting // to all natural end points. // Note however that origin uses hints here, and actually allows for this // send to partially or wholly fail in actually sending stuff. Since we don't // have hints (yet), send with CL=ALL, and hope we can re-do this soon. // See below, we use retry on write failure. return _qp.proxy().mutate(mutations, db::consistency_level::ALL, db::no_timeout, nullptr, empty_service_permit()); }); }).then_wrapped([this, id](future<> batch_result) { try { batch_result.get(); } catch (data_dictionary::no_such_keyspace& ex) { // should probably ignore and drop the batch } catch (...) { // timeout, overload etc. // Do _not_ remove the batch, assuning we got a node write error. // Since we don't have hints (which origin is satisfied with), // we have to resort to keeping this batch to next lap. return make_ready_future<>(); } // delete batch auto schema = _qp.db().find_schema(system_keyspace::NAME, system_keyspace::BATCHLOG); auto key = partition_key::from_singular(*schema, id); mutation m(schema, key); auto now = service::client_state(service::client_state::internal_tag()).get_timestamp(); m.partition().apply_delete(*schema, clustering_key_prefix::make_empty(), tombstone(now, gc_clock::now())); return _qp.proxy().mutate_locally(m, tracing::trace_state_ptr(), db::commitlog::force_sync::no); }); }; return seastar::with_gate(_gate, [this, batch = std::move(batch)] { blogger.debug("Started replayAllFailedBatches (cpu {})", this_shard_id()); typedef ::shared_ptr<cql3::untyped_result_set> page_ptr; sstring query = format("SELECT id, data, written_at, version FROM {}.{} LIMIT {:d}", system_keyspace::NAME, system_keyspace::BATCHLOG, page_size); return _qp.execute_internal(query).then([this, batch = std::move(batch)](page_ptr page) { return do_with(std::move(page), [this, batch = std::move(batch)](page_ptr & page) mutable { return repeat([this, &page, batch = std::move(batch)]() mutable { if (page->empty()) { return make_ready_future<stop_iteration>(stop_iteration::yes); } auto id = page->back().get_as<utils::UUID>("id"); return parallel_for_each(*page, batch).then([this, &page, id]() { if (page->size() < page_size) { return make_ready_future<stop_iteration>(stop_iteration::yes); // we've exhausted the batchlog, next query would be empty. } sstring query = format("SELECT id, data, written_at, version FROM {}.{} WHERE token(id) > token(?) LIMIT {:d}", system_keyspace::NAME, system_keyspace::BATCHLOG, page_size); return _qp.execute_internal(query, {id}).then([&page](auto res) { page = std::move(res); return make_ready_future<stop_iteration>(stop_iteration::no); }); }); }); }); }).then([this] { // TODO FIXME : cleanup() #if 0 ColumnFamilyStore cfs = Keyspace.open(SystemKeyspace.NAME).getColumnFamilyStore(SystemKeyspace.BATCHLOG); cfs.forceBlockingFlush(); Collection<Descriptor> descriptors = new ArrayList<>(); for (SSTableReader sstr : cfs.getSSTables()) descriptors.add(sstr.descriptor); if (!descriptors.isEmpty()) // don't pollute the logs if there is nothing to compact. CompactionManager.instance.submitUserDefined(cfs, descriptors, Integer.MAX_VALUE).get(); #endif }).then([this] { blogger.debug("Finished replayAllFailedBatches"); }); }); } <|endoftext|>
<commit_before>#include "statement.h" #include "adapter.h" #include "result.h" #include "query.h" VALUE cSwiftStatement; void statement_mark(StatementWrapper *handle) { if (handle) rb_gc_mark(handle->adapter); } void statement_free(StatementWrapper *handle) { if (handle) { if (handle->free) delete handle->statement; delete handle; } } VALUE statement_alloc(VALUE klass) { StatementWrapper *handle = 0; return Data_Wrap_Struct(klass, statement_mark, statement_free, handle); } VALUE statement_wrap_handle(VALUE klass, VALUE adapter, dbi::AbstractStatement *statement) { StatementWrapper *handle = new StatementWrapper; handle->statement = statement; handle->adapter = adapter; handle->free = true; VALUE obj = Data_Wrap_Struct(klass, statement_mark, statement_free, handle); if (!NIL_P(adapter)) rb_iv_set(obj, "@timezone", rb_iv_get(adapter, "@timezone")); return obj; } dbi::AbstractStatement* statement_handle(VALUE self) { StatementWrapper *handle; Data_Get_Struct(self, StatementWrapper, handle); if (!handle) rb_raise(eSwiftRuntimeError, "Invalid object, did you forget to call #super?"); return handle->statement; } // TODO: Change bind_values to an array in the interface? Avoid array -> splat -> array. static VALUE statement_execute(int argc, VALUE *argv, VALUE self) { VALUE bind_values, block; rb_scan_args(argc, argv, "0*&", &bind_values, &block); dbi::AbstractStatement *statement = (dbi::AbstractStatement*)statement_handle(self); try { Query query; query.statement = statement; if (RARRAY_LEN(bind_values) > 0) query_bind_values(&query, bind_values); if (dbi::_trace) dbi::logMessage(dbi::_trace_fd, dbi::formatParams(statement->command(), query.bind)); if (rb_thread_blocking_region(((VALUE (*)(void*))query_execute_statement), &query, RUBY_UBF_IO, 0) == Qfalse) rb_raise(eSwiftRuntimeError, "%s", query.error); } CATCH_DBI_EXCEPTIONS(); StatementWrapper *handle; Data_Get_Struct(self, StatementWrapper, handle); VALUE result = result_wrap_handle(cSwiftResult, handle->adapter, statement->result(), true); rb_iv_set(result, "@scheme", rb_iv_get(self, "@scheme")); return rb_block_given_p() ? result_each(result) : result; } VALUE statement_insert_id(VALUE self) { dbi::AbstractStatement *statement = statement_handle(self); try { return SIZET2NUM(statement->lastInsertID()); } CATCH_DBI_EXCEPTIONS(); return Qnil; } VALUE statement_initialize(VALUE self, VALUE adapter, VALUE sql) { dbi::Handle *handle = adapter_handle(adapter); if (NIL_P(adapter)) rb_raise(eSwiftArgumentError, "Statement#new called without an Adapter instance."); if (NIL_P(sql)) rb_raise(eSwiftArgumentError, "Statement#new called without a command."); try { // needs to happen before wrapping in case it raises errors. dbi::AbstractStatement *statement = handle->conn()->prepare(CSTRING(sql)); StatementWrapper *statement_handle = new StatementWrapper; statement_handle->statement = statement; statement_handle->adapter = adapter; statement_handle->free = true; DATA_PTR(self) = statement_handle; } CATCH_DBI_EXCEPTIONS(); return Qnil; } void init_swift_statement() { VALUE mSwift = rb_define_module("Swift"); cSwiftStatement = rb_define_class_under(mSwift, "Statement", rb_cObject); rb_define_method(cSwiftStatement, "execute", RUBY_METHOD_FUNC(statement_execute), -1); rb_define_method(cSwiftStatement, "initialize", RUBY_METHOD_FUNC(statement_initialize), 2); rb_define_method(cSwiftStatement, "insert_id", RUBY_METHOD_FUNC(statement_insert_id), 0); rb_define_alloc_func(cSwiftStatement, statement_alloc); } <commit_msg>removed array->splat->array todo<commit_after>#include "statement.h" #include "adapter.h" #include "result.h" #include "query.h" VALUE cSwiftStatement; void statement_mark(StatementWrapper *handle) { if (handle) rb_gc_mark(handle->adapter); } void statement_free(StatementWrapper *handle) { if (handle) { if (handle->free) delete handle->statement; delete handle; } } VALUE statement_alloc(VALUE klass) { StatementWrapper *handle = 0; return Data_Wrap_Struct(klass, statement_mark, statement_free, handle); } VALUE statement_wrap_handle(VALUE klass, VALUE adapter, dbi::AbstractStatement *statement) { StatementWrapper *handle = new StatementWrapper; handle->statement = statement; handle->adapter = adapter; handle->free = true; VALUE obj = Data_Wrap_Struct(klass, statement_mark, statement_free, handle); if (!NIL_P(adapter)) rb_iv_set(obj, "@timezone", rb_iv_get(adapter, "@timezone")); return obj; } dbi::AbstractStatement* statement_handle(VALUE self) { StatementWrapper *handle; Data_Get_Struct(self, StatementWrapper, handle); if (!handle) rb_raise(eSwiftRuntimeError, "Invalid object, did you forget to call #super?"); return handle->statement; } // array -> splat -> array is an overhead, but it reads nicer. static VALUE statement_execute(int argc, VALUE *argv, VALUE self) { VALUE bind_values, block; rb_scan_args(argc, argv, "0*&", &bind_values, &block); dbi::AbstractStatement *statement = (dbi::AbstractStatement*)statement_handle(self); try { Query query; query.statement = statement; if (RARRAY_LEN(bind_values) > 0) query_bind_values(&query, bind_values); if (dbi::_trace) dbi::logMessage(dbi::_trace_fd, dbi::formatParams(statement->command(), query.bind)); if (rb_thread_blocking_region(((VALUE (*)(void*))query_execute_statement), &query, RUBY_UBF_IO, 0) == Qfalse) rb_raise(eSwiftRuntimeError, "%s", query.error); } CATCH_DBI_EXCEPTIONS(); StatementWrapper *handle; Data_Get_Struct(self, StatementWrapper, handle); VALUE result = result_wrap_handle(cSwiftResult, handle->adapter, statement->result(), true); rb_iv_set(result, "@scheme", rb_iv_get(self, "@scheme")); return rb_block_given_p() ? result_each(result) : result; } VALUE statement_insert_id(VALUE self) { dbi::AbstractStatement *statement = statement_handle(self); try { return SIZET2NUM(statement->lastInsertID()); } CATCH_DBI_EXCEPTIONS(); return Qnil; } VALUE statement_initialize(VALUE self, VALUE adapter, VALUE sql) { dbi::Handle *handle = adapter_handle(adapter); if (NIL_P(adapter)) rb_raise(eSwiftArgumentError, "Statement#new called without an Adapter instance."); if (NIL_P(sql)) rb_raise(eSwiftArgumentError, "Statement#new called without a command."); try { // needs to happen before wrapping in case it raises errors. dbi::AbstractStatement *statement = handle->conn()->prepare(CSTRING(sql)); StatementWrapper *statement_handle = new StatementWrapper; statement_handle->statement = statement; statement_handle->adapter = adapter; statement_handle->free = true; DATA_PTR(self) = statement_handle; } CATCH_DBI_EXCEPTIONS(); return Qnil; } void init_swift_statement() { VALUE mSwift = rb_define_module("Swift"); cSwiftStatement = rb_define_class_under(mSwift, "Statement", rb_cObject); rb_define_method(cSwiftStatement, "execute", RUBY_METHOD_FUNC(statement_execute), -1); rb_define_method(cSwiftStatement, "initialize", RUBY_METHOD_FUNC(statement_initialize), 2); rb_define_method(cSwiftStatement, "insert_id", RUBY_METHOD_FUNC(statement_insert_id), 0); rb_define_alloc_func(cSwiftStatement, statement_alloc); } <|endoftext|>
<commit_before>#include "catch.hpp" #include "build_machine.hpp" #include "compass.hpp" #include <bitset> #include <vector> #include <iostream> #include <string> #include <algorithm> TEST_CASE_METHOD( host_reference, "machine_specific" ){ SECTION( "vendor_right" ){ auto value = compass::runtime::vendor(); REQUIRE(value.size()!=0u); // std::transform(value.begin(), value.end(), // value.begin(), // ::tolower); REQUIRE(value.find(expected_vendor)!=std::string::npos); } SECTION( "brand_right" ){ auto value = compass::runtime::brand(); REQUIRE(value.empty()!=true); REQUIRE_THAT(value, Catch::Matchers::Contains(expected_brand) ); } SECTION( "device_name_right" ){ auto value = compass::runtime::device_name(); REQUIRE(value.empty()!=true); REQUIRE_THAT(value, Catch::Matchers::Contains(expected_device_name) ); } SECTION( "ncores_right" ){ auto value = compass::runtime::threads(); REQUIRE(value!=0); REQUIRE(value==expected_ncores); } // SECTION( "physical_cores_right" ){ // auto value = compass::runtime::physical_threads(); // REQUIRE(value!=0); // REQUIRE(value==expected_nphyscores); // } SECTION( "has_sse_right_at_ct" ){ auto value = compass::compiletime::has<compass::feature::sse()>::enabled; REQUIRE(true);//this just needs to compile } SECTION( "has_sse_right" ){ auto value = compass::runtime::has(compass::feature::sse()); REQUIRE(value==expected_has_sse); } SECTION( "has_sse2_right" ){ auto value = compass::runtime::has(compass::feature::sse2()); REQUIRE(value==expected_has_sse2); if(expected_has_sse2){ REQUIRE(compass::compiletime::has<compass::feature::sse2>::enabled==expected_has_sse2); } } SECTION( "has_sse3_right" ){ auto value = compass::runtime::has(compass::feature::sse3()); REQUIRE(value==expected_has_sse3); if(expected_has_sse3) REQUIRE(compass::compiletime::has<compass::feature::sse3>::enabled==expected_has_sse3); } SECTION( "has_sse4_right" ){ auto value = compass::runtime::has(compass::feature::sse4()); REQUIRE(value==expected_has_sse4); if(expected_has_sse4) REQUIRE(compass::compiletime::has<compass::feature::sse4>::enabled==expected_has_sse4); } SECTION( "has_avx_right" ){ auto value = compass::runtime::has(compass::feature::avx()); REQUIRE(value==expected_has_avx); } SECTION( "has_multiple_features" ){ auto value = compass::runtime::accumulate(compass::feature::avx(),compass::feature::sse4(),compass::feature::sse3()); const bool expected = (expected_has_avx || expected_has_sse4 || expected_has_sse3 ); REQUIRE(bool(value) == expected ); std::bitset<3> mask((unsigned long)value); REQUIRE(mask[0] == expected_has_avx); REQUIRE(mask[1] == expected_has_sse4); REQUIRE(mask[2] == expected_has_sse3); } SECTION( "has_avx2_right" ){ auto value = compass::runtime::has(compass::feature::avx2()); REQUIRE(value==expected_has_avx2); } SECTION( "correct_l2_cache_size" ){ auto value = compass::runtime::size::cache::level(2); REQUIRE(value > 0); if(expected_L2_size_kB){ REQUIRE(value >> 10 ==expected_L2_size_kB); } } } <commit_msg>comparing the device name is optional<commit_after>#include "catch.hpp" #include "build_machine.hpp" #include "compass.hpp" #include <bitset> #include <vector> #include <iostream> #include <string> #include <algorithm> TEST_CASE_METHOD( host_reference, "machine_specific" ){ SECTION( "vendor_right" ){ auto value = compass::runtime::vendor(); REQUIRE(value.size()!=0u); // std::transform(value.begin(), value.end(), // value.begin(), // ::tolower); REQUIRE(value.find(expected_vendor)!=std::string::npos); } SECTION( "brand_right" ){ auto value = compass::runtime::brand(); REQUIRE(value.empty()!=true); REQUIRE_THAT(value, Catch::Matchers::Contains(expected_brand) ); } SECTION( "device_name_right" ){ auto value = compass::runtime::device_name(); if(expected_device_name.size() > 0){ REQUIRE(value.empty()!=true);} REQUIRE_THAT(value, Catch::Matchers::Contains(expected_device_name) ); } SECTION( "ncores_right" ){ auto value = compass::runtime::threads(); REQUIRE(value!=0); REQUIRE(value==expected_ncores); } // SECTION( "physical_cores_right" ){ // auto value = compass::runtime::physical_threads(); // REQUIRE(value!=0); // REQUIRE(value==expected_nphyscores); // } SECTION( "has_sse_right_at_ct" ){ auto value = compass::compiletime::has<compass::feature::sse()>::enabled; REQUIRE(true);//this just needs to compile } SECTION( "has_sse_right" ){ auto value = compass::runtime::has(compass::feature::sse()); REQUIRE(value==expected_has_sse); } SECTION( "has_sse2_right" ){ auto value = compass::runtime::has(compass::feature::sse2()); REQUIRE(value==expected_has_sse2); if(expected_has_sse2){ REQUIRE(compass::compiletime::has<compass::feature::sse2>::enabled==expected_has_sse2); } } SECTION( "has_sse3_right" ){ auto value = compass::runtime::has(compass::feature::sse3()); REQUIRE(value==expected_has_sse3); if(expected_has_sse3) REQUIRE(compass::compiletime::has<compass::feature::sse3>::enabled==expected_has_sse3); } SECTION( "has_sse4_right" ){ auto value = compass::runtime::has(compass::feature::sse4()); REQUIRE(value==expected_has_sse4); if(expected_has_sse4) REQUIRE(compass::compiletime::has<compass::feature::sse4>::enabled==expected_has_sse4); } SECTION( "has_avx_right" ){ auto value = compass::runtime::has(compass::feature::avx()); REQUIRE(value==expected_has_avx); } SECTION( "has_multiple_features" ){ auto value = compass::runtime::accumulate(compass::feature::avx(),compass::feature::sse4(),compass::feature::sse3()); const bool expected = (expected_has_avx || expected_has_sse4 || expected_has_sse3 ); REQUIRE(bool(value) == expected ); std::bitset<3> mask((unsigned long)value); REQUIRE(mask[0] == expected_has_avx); REQUIRE(mask[1] == expected_has_sse4); REQUIRE(mask[2] == expected_has_sse3); } SECTION( "has_avx2_right" ){ auto value = compass::runtime::has(compass::feature::avx2()); REQUIRE(value==expected_has_avx2); } SECTION( "correct_l2_cache_size" ){ auto value = compass::runtime::size::cache::level(2); REQUIRE(value > 0); if(expected_L2_size_kB){ REQUIRE(value >> 10 ==expected_L2_size_kB); } } } <|endoftext|>
<commit_before>#include "cppunit/extensions/HelperMacros.h" #include "FooLib.h" class FooLibTest : public CppUnit::TestFixture { public: void setUp() { a = 4; b = 5; pFoo = new Foo(a, b); } void tearDown() { delete pFoo; } void testSum() { CPPUNIT_ASSERT_EQUAL(9, pFoo->sum()); } CPPUNIT_TEST_SUITE(FooLibTest); CPPUNIT_TEST(testSum); CPPUNIT_TEST_SUITE_END(); private: int a; int b; Foo* pFoo; }; CPPUNIT_TEST_SUITE_REGISTRATION(FooLibTest); <commit_msg>sample fixed<commit_after>#include "cppunit/extensions/HelperMacros.h" #include "FooLib.h" class FooLibTest : public CppUnit::TestFixture { public: void setUp() { a = 4; b = 5; pFoo = new Foo(a, b); } void tearDown() { delete pFoo; } void testSum() { CPPUNIT_ASSERT_EQUAL(9, pFoo->sum()); } void testMul() { CPPUNIT_ASSERT_EQUAL(20, pFoo->mul()); } CPPUNIT_TEST_SUITE(FooLibTest); CPPUNIT_TEST(testSum); CPPUNIT_TEST(testMul); CPPUNIT_TEST_SUITE_END(); private: int a; int b; Foo* pFoo; }; CPPUNIT_TEST_SUITE_REGISTRATION(FooLibTest); <|endoftext|>
<commit_before><commit_msg>Reverse polarity of CLOCK_MONOTONIC_COARSE check<commit_after><|endoftext|>
<commit_before> // .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Newhall // NOLINT(whitespace/line_length) // Benchmarking on 1 X 3310 MHz CPU // 2015/05/24-13:16:32 // Benchmark Time(ns) CPU(ns) Iterations // ----------------------------------------------------------- // BM_NewhallApproximation/4 589 562 2000000 // BM_NewhallApproximation/8 657 624 2000000 // BM_NewhallApproximation/16 754 741 2000000 #include <random> #include <vector> #include "benchmark/benchmark.h" #include "geometry/named_quantities.hpp" #include "numerics/newhall.hpp" #include "quantities/named_quantities.hpp" #include "quantities/si.hpp" namespace principia { using geometry::Instant; using quantities::Variation; using quantities::si::Second; namespace numerics { void BM_NewhallApproximation(benchmark::State& state) { int const degree = state.range_x(); std::mt19937_64 random(42); std::vector<double> p; std::vector<Variation<double>> v; Instant const t0; Instant const t_min = t0 + static_cast<double>(random()) * Second; Instant const t_max = t_min + static_cast<double>(random()) * Second; double error_estimate; while (state.KeepRunning()) { state.PauseTiming(); p.clear(); v.clear(); for (int i = 0; i <= 8; ++i) { p.push_back(static_cast<double>(static_cast<double>(random()))); v.push_back(static_cast<double>(static_cast<double>(random())) / Second); } state.ResumeTiming(); auto const series = NewhallApproximationInЧебышёвBasis<double>(degree, p, v, t_min, t_max, error_estimate); } } BENCHMARK(BM_NewhallApproximation)->Arg(4)->Arg(8)->Arg(16); } // namespace numerics } // namespace principia <commit_msg>Better benchmarks for Newhall.<commit_after> // .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Newhall // NOLINT(whitespace/line_length) // Benchmarking on 1 X 3310 MHz CPU // 2015/05/24-13:16:32 // Benchmark Time(ns) CPU(ns) Iterations // ----------------------------------------------------------- // BM_NewhallApproximation/4 589 562 2000000 // BM_NewhallApproximation/8 657 624 2000000 // BM_NewhallApproximation/16 754 741 2000000 #include <memory> #include <random> #include <vector> #include "astronomy/frames.hpp" #include "base/not_null.hpp" #include "benchmark/benchmark.h" #include "geometry/named_quantities.hpp" #include "numerics/newhall.hpp" #include "numerics/polynomial.hpp" #include "numerics/polynomial_evaluators.hpp" #include "quantities/named_quantities.hpp" #include "quantities/si.hpp" namespace principia { using astronomy::ICRFJ2000Ecliptic; using base::not_null; using geometry::Displacement; using geometry::Instant; using quantities::Variation; using quantities::si::Metre; using quantities::si::Second; namespace numerics { template<typename Result, Result (*newhall)(int degree, std::vector<double> const& q, std::vector<Variation<double>> const& v, Instant const& t_min, Instant const& t_max, double& error_estimate)> void BM_NewhallApproximationDouble(benchmark::State& state) { int const degree = state.range_x(); std::mt19937_64 random(42); std::vector<double> p; std::vector<Variation<double>> v; Instant const t0; Instant const t_min = t0 + static_cast<double>(random()) * Second; Instant const t_max = t_min + static_cast<double>(random()) * Second; double error_estimate; while (state.KeepRunning()) { state.PauseTiming(); p.clear(); v.clear(); for (int i = 0; i <= 8; ++i) { p.push_back(static_cast<double>(static_cast<double>(random()))); v.push_back(static_cast<double>(static_cast<double>(random())) / Second); } state.ResumeTiming(); auto const series = newhall(degree, p, v, t_min, t_max, error_estimate); } } template<typename Result, Result (*newhall)( int degree, std::vector<Displacement<ICRFJ2000Ecliptic>> const& q, std::vector<Variation<Displacement<ICRFJ2000Ecliptic>>> const& v, Instant const& t_min, Instant const& t_max, Displacement<ICRFJ2000Ecliptic>& error_estimate)> void BM_NewhallApproximationDisplacement(benchmark::State& state) { int const degree = state.range_x(); std::mt19937_64 random(42); std::vector<Displacement<ICRFJ2000Ecliptic>> p; std::vector<Variation<Displacement<ICRFJ2000Ecliptic>>> v; Instant const t0; Instant const t_min = t0 + static_cast<double>(random()) * Second; Instant const t_max = t_min + static_cast<double>(random()) * Second; Displacement<ICRFJ2000Ecliptic> error_estimate; while (state.KeepRunning()) { state.PauseTiming(); p.clear(); v.clear(); for (int i = 0; i <= 8; ++i) { p.push_back(Displacement<ICRFJ2000Ecliptic>( {static_cast<double>(random()) * Metre, static_cast<double>(random()) * Metre, static_cast<double>(random()) * Metre})); v.push_back(Variation<Displacement<ICRFJ2000Ecliptic>>( {static_cast<double>(random()) * Metre / Second, static_cast<double>(random()) * Metre / Second, static_cast<double>(random()) * Metre / Second})); } state.ResumeTiming(); auto const series = newhall(degree, p, v, t_min, t_max, error_estimate); } } using ResultЧебышёвDouble = ЧебышёвSeries<double>; using ResultЧебышёвDisplacement = ЧебышёвSeries<Displacement<ICRFJ2000Ecliptic>>; using ResultMonomialDouble = not_null<std::unique_ptr<Polynomial<double, Instant>>>; using ResultMonomialDisplacement = not_null< std::unique_ptr<Polynomial<Displacement<ICRFJ2000Ecliptic>, Instant>>>; BENCHMARK_TEMPLATE2( BM_NewhallApproximationDouble, ResultЧебышёвDouble, &NewhallApproximationInЧебышёвBasis<double>) ->Arg(4)->Arg(8)->Arg(16); BENCHMARK_TEMPLATE2( BM_NewhallApproximationDisplacement, ResultЧебышёвDisplacement, &NewhallApproximationInЧебышёвBasis<Displacement<ICRFJ2000Ecliptic>>) ->Arg(4)->Arg(8)->Arg(16); BENCHMARK_TEMPLATE2( BM_NewhallApproximationDouble, ResultMonomialDouble, (&NewhallApproximationInMonomialBasis<double, EstrinEvaluator>)) ->Arg(4)->Arg(8)->Arg(16); BENCHMARK_TEMPLATE2( BM_NewhallApproximationDisplacement, ResultMonomialDisplacement, (&NewhallApproximationInMonomialBasis<Displacement<ICRFJ2000Ecliptic>, EstrinEvaluator>)) ->Arg(4)->Arg(8)->Arg(16); } // namespace numerics } // namespace principia <|endoftext|>
<commit_before>/** * \file GainMaxColoredExpanderFilter.cpp */ #include "GainMaxColoredExpanderFilter.h" #include <cmath> #include <cstdint> #include <iostream> #include <stdexcept> namespace ATK { template<typename DataType_> GainMaxColoredExpanderFilter<DataType_>::GainMaxColoredExpanderFilter(int nb_channels, size_t LUTsize, size_t LUTprecision) :Parent(nb_channels, LUTsize, LUTprecision), softness(static_cast<DataType_>(.0001)), max_reduction(0.01), color(0), quality(0) { recomputeLUT(); } template<typename DataType_> GainMaxColoredExpanderFilter<DataType_>::~GainMaxColoredExpanderFilter() { //Future has to be deleted in child destructor as it uses computeGain if(recomputeFuture.valid()) { recomputeFuture.wait(); } } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_softness(DataType_ softness) { if (softness <= 0) { throw std::out_of_range("Softness factor must be strictly positive value"); } this->softness = softness; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_softness() const { return softness; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_max_reduction(DataType_ max_reduction) { if (max_reduction <= 0) { throw std::out_of_range("Maximum reduction factor must be strictly positive value"); } this->max_reduction = max_reduction; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_max_reduction_db(DataType_ max_reduction_db) { this->max_reduction = static_cast<DataType_>(std::pow(10, max_reduction_db / 10)); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_max_reduction() const { return max_reduction; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_color(DataType_ color) { this->color = color; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_color() const { return color; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_quality(DataType_ quality) { if (quality <= 0) { throw std::out_of_range("Quality factor must be a strictly positive value"); } this->quality = quality; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_quality() const { return quality; } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::computeGain( DataType_ value ) const { if(value == 0) return std::pow(max_reduction, 1./(ratio - 1)); DataType diff = -10 * std::log10(std::sqrt(value * value + std::pow(max_reduction, 2. / (ratio - 1)))); DataType additional_color = color * std::exp(- diff * diff * quality); return static_cast<DataType>(std::pow(10, -(std::sqrt(diff*diff + softness) + diff) / 40 * (ratio - 1))) + additional_color; } template class GainMaxColoredExpanderFilter<float>; template class GainMaxColoredExpanderFilter<double>; } <commit_msg>Forgot to recompute after max reduction change... + simplified gain compute by removing sqrt and putting it out of the log call.<commit_after>/** * \file GainMaxColoredExpanderFilter.cpp */ #include "GainMaxColoredExpanderFilter.h" #include <cmath> #include <cstdint> #include <iostream> #include <stdexcept> namespace ATK { template<typename DataType_> GainMaxColoredExpanderFilter<DataType_>::GainMaxColoredExpanderFilter(int nb_channels, size_t LUTsize, size_t LUTprecision) :Parent(nb_channels, LUTsize, LUTprecision), softness(static_cast<DataType_>(.0001)), max_reduction(0.01), color(0), quality(0) { recomputeLUT(); } template<typename DataType_> GainMaxColoredExpanderFilter<DataType_>::~GainMaxColoredExpanderFilter() { //Future has to be deleted in child destructor as it uses computeGain if(recomputeFuture.valid()) { recomputeFuture.wait(); } } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_softness(DataType_ softness) { if (softness <= 0) { throw std::out_of_range("Softness factor must be strictly positive value"); } this->softness = softness; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_softness() const { return softness; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_max_reduction(DataType_ max_reduction) { if (max_reduction <= 0) { throw std::out_of_range("Maximum reduction factor must be strictly positive value"); } this->max_reduction = max_reduction; start_recomputeLUT(); } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_max_reduction_db(DataType_ max_reduction_db) { this->max_reduction = static_cast<DataType_>(std::pow(10, max_reduction_db / 10)); start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_max_reduction() const { return max_reduction; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_color(DataType_ color) { this->color = color; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_color() const { return color; } template<typename DataType_> void GainMaxColoredExpanderFilter<DataType_>::set_quality(DataType_ quality) { if (quality <= 0) { throw std::out_of_range("Quality factor must be a strictly positive value"); } this->quality = quality; start_recomputeLUT(); } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::get_quality() const { return quality; } template<typename DataType_> DataType_ GainMaxColoredExpanderFilter<DataType_>::computeGain( DataType_ value ) const { if(value == 0) return std::pow(max_reduction, 1./(ratio - 1)); DataType diff = -5 * std::log10(value * value + std::pow(max_reduction, 2. / (ratio - 1))); DataType additional_color = color * std::exp(- diff * diff * quality); return static_cast<DataType>(std::pow(10, -(std::sqrt(diff*diff + softness) + diff) / 40 * (ratio - 1))) + additional_color; } template class GainMaxColoredExpanderFilter<float>; template class GainMaxColoredExpanderFilter<double>; } <|endoftext|>
<commit_before><commit_msg>TBBUTTON bugfix<commit_after><|endoftext|>
<commit_before>// RUN: %clangxx_asan -flto=thin -O %s -o %t.thinlto // RUN: not %run %t.thinlto crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t.thinlto bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t.thinlto bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t.thinlto crash // // Test crash due to __sanitizer_annotate_contiguous_container. #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <commit_msg>[ThinLTO] New test needs to require LTO<commit_after>// RUN: %clangxx_asan -flto=thin -O %s -o %t.thinlto // RUN: not %run %t.thinlto crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t.thinlto bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t.thinlto bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t.thinlto crash // // Test crash due to __sanitizer_annotate_contiguous_container. // REQUIRES: lto #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <|endoftext|>
<commit_before>// // Class to identify resonance candidate pairs, which are then // added back into the mini event to serve as daughters for // another particle. // #include "Riostream.h" #include "TMath.h" #include "TString.h" #include "AliRsnMiniParticle.h" #include "AliRsnMiniPair.h" #include "AliRsnMiniEvent.h" #include "AliRsnMiniAnalysisTask.h" #include "AliLog.h" #include "AliRsnCutSet.h" ClassImp(AliRsnMiniResonanceFinder) //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::AliRsnMiniResonanceFinder(const char *name) : TNamed(name, ""), fCutIDrsn(0), fResMass(0.0), fResPDG(0), fPairCuts(0x0), fPair(), fSelRes(0), fSel1(0), fSel2(0), fPairMode(0), fEvent(0x0) { // // Constructor // fCutID[0] = fCutID[1] = -1; fDaughter[0] = fDaughter[1] = AliRsnDaughter::kUnknown; fCharge[0] = fCharge[1] = 0; } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::AliRsnMiniResonanceFinder(const AliRsnMiniResonanceFinder& copy) : TNamed(copy), fCutIDrsn(copy.fCutIDrsn), fResMass(copy.fResMass), fResPDG(copy.fResPDG), fPairCuts(copy.fPairCuts), fPair(), fSelRes(0), fSel1(0), fSel2(0), fPairMode(copy.fPairMode), fEvent(copy.fEvent) { // // Copy constructor // Int_t i; for (i = 0; i < 2; i++) { fCutID[i] = copy.fCutID[i]; fDaughter[i] = copy.fDaughter[i]; fCharge[i] = copy.fCharge[i]; } } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder &AliRsnMiniResonanceFinder::operator=(const AliRsnMiniResonanceFinder &copy) { // // Assignment operator // if (this == &copy) return *this; fCutIDrsn = copy.fCutIDrsn; fResMass = copy.fResMass; fResPDG = copy.fResPDG; fPairCuts = copy.fPairCuts; fPairMode = copy.fPairMode; fEvent = copy.fEvent; Int_t i; for (i = 0; i < 2; i++) { fCutID[i] = copy.fCutID[i]; fDaughter[i] = copy.fDaughter[i]; fCharge[i] = copy.fCharge[i]; } fSelRes.Set(0); fSel1.Set(0); fSel2.Set(0); return (*this); } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::~AliRsnMiniResonanceFinder() { // // Destructor. // return; } /* //__________________________________________________________________________________________________ Int_t AliRsnMiniResonanceFinder::ConnectTo(AliRsnMiniAnalysisTask* task) { // // IMPORTANT: Do not assign any additional track cuts to the AliRsnMiniAnalysisTask // after calling this ConnectTo function. // task->SetResonanceFinder(this); fCutIDrsn = task->GetNumberOfTrackCuts(); return fCutIDrsn;// plug this value into AliRsnMiniOutput objects } */ //__________________________________________________________________________________________________ Int_t AliRsnMiniResonanceFinder::RunResonanceFinder(AliRsnMiniEvent* event) { // // Loops on the passed mini-event, and for each pair of particles // which satisfy the charge and cut requirements defined here, add an entry. // Returns the number of successful fillings. // // loop variables Int_t i1, i2, start, nadded = 0; AliRsnMiniParticle *r, *p1, *p2; // it is necessary to know if criteria for the two daughters are the same Bool_t sameCriteria = ((fCharge[0] == fCharge[1]) && (fDaughter[0] == fDaughter[1])); TString selList1 = ""; TString selList2 = ""; Int_t n1 = event->CountParticles(fSel1, fCharge[0], fCutID[0]); Int_t n2 = event->CountParticles(fSel2, fCharge[1], fCutID[1]); for (i1 = 0; i1 < n1; i1++) selList1.Append(Form("%d ", fSel1[i1])); for (i2 = 0; i2 < n2; i2++) selList2.Append(Form("%d ", fSel2[i2])); AliDebugClass(1, Form("[%10s] Part #1: -- evID %6d -- charge = %c -- cut ID = %d --> %4d tracks (%s)", GetName(), event->ID(), fCharge[0], fCutID[0], n1, selList1.Data())); AliDebugClass(1, Form("[%10s] Part #2: -- evID %6d -- charge = %c -- cut ID = %d --> %4d tracks (%s)", GetName(), event->ID(), fCharge[1], fCutID[1], n2, selList2.Data())); if (!n1 || !n2) { AliDebugClass(1, "No pairs to mix"); return 0; } // external loop for (i1 = 0; i1 < n1; i1++) { p1 = event->GetParticle(fSel1[i1]); // define starting point for inner loop // if daughter selection criteria (charge, cuts) are the same // and the two events coincide, internal loop must start from // the first track *after* current one; // otherwise it starts from the beginning start = (sameCriteria ? i1 + 1 : 0); AliDebugClass(2, Form("Start point = %d", start)); // internal loop for (i2 = start; i2 < n2; i2++) { p2 = event->GetParticle(fSel2[i2]); // avoid to mix a particle with itself if (p1->Index() == p2->Index()) { AliDebugClass(2, "Skipping same index"); continue; } // sum momenta fPair.Fill(p1, p2, GetMass(0), GetMass(1), fResMass); // check pair against cuts if (fPairCuts && !fPairCuts->IsSelected(&fPair)) continue; // package the pair as a mini particle if(fPairMode==1 && (p1->Mother()<0 || p1->Mother()!=p2->Mother() || !AliRsnDaughter::IsEquivalentPDGCode(p1->MotherPDG(),GetResonancePDG()) ) ) continue;// use only true pairs (MC) if(fPairMode==2 && p1->Mother()>=0 && p1->Mother()==p2->Mother()) continue;// use only false pairs (MC) r = event->AddParticle(); r->Clear(); r->SetResonance(); r->Charge() = '0'; r->SetCutBit(fCutIDrsn); if(p1->Charge()=='+'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p1->Index(); r->IndexV0Neg() = p2->Index(); r->Charge() = '0'; // does not account for double charges, e.g., Delta++ }else if(p2->Charge()=='0'){ r->IndexV0Pos() = p2->IndexV0Pos(); r->IndexV0Neg() = p2->IndexV0Neg(); r->IndexBachelor() = p1->Index(); r->Charge() = '+'; } }else if(p1->Charge()=='-'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p2->Index(); r->IndexV0Neg() = p1->Index(); r->Charge() = '0'; // does not account for double charges, e.g., anti-Delta-- }else if(p2->Charge()=='0'){ r->IndexV0Pos() = p2->IndexV0Pos(); r->IndexV0Neg() = p2->IndexV0Neg(); r->IndexBachelor() = p1->Index(); r->Charge() = '-'; } }else if(p1->Charge()=='0'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p1->IndexV0Pos(); r->IndexV0Neg() = p1->IndexV0Neg(); r->IndexBachelor() = p2->Index(); r->Charge() = p2->Charge(); } } r->PrecX() = fPair.Sum(0).X(); r->PrecY() = fPair.Sum(0).Y(); r->PrecZ() = fPair.Sum(0).Z(); r->StoredMass(0) = fPair.InvMass(0); if(p1->Mother()>=0 && p1->Mother()==p2->Mother()){ r->Index() = p1->Mother(); r->PsimX() = p1->PmotherX(); r->PsimY() = p1->PmotherY(); r->PsimZ() = p1->PmotherZ(); r->PDG() = p1->MotherPDG(); }else{ r->PsimX() = fPair.Sum(1).X(); r->PsimY() = fPair.Sum(1).Y(); r->PsimZ() = fPair.Sum(1).Z(); } r->StoredMass(1) = fPair.InvMass(1); r->PmotherX() = r->PmotherY() = r->PmotherZ() = 0.0;// filled later nadded++; } // end internal loop } // end external loop event->CountParticles(fSelRes, '0', fCutIDrsn); AliDebugClass(1, Form("Pairs added in total = %4d", nadded)); return nadded; } //__________________________________________________________________________________________________ void AliRsnMiniResonanceFinder::FillMother(AliMCEvent* event, AliRsnMiniEvent* mini) { // // Loops over MC tracks to find matches to resonances that have been reconatructed and selected. // Adds information about their mothers to the mini event. // ESD version if (!event) { AliError("Missing AliMCEvent"); return; } if (!mini) { AliError("Missing AliRsnMiniEvent"); return; } AliMCParticle *p,*mother; AliRsnMiniParticle* r; Int_t j,k,imother, npart = event->GetNumberOfTracks(); for (j=0; j<npart; j++) { p = (AliMCParticle*) event->GetTrack(j); if (!p) continue; if (!AliRsnDaughter::IsEquivalentPDGCode(p->Particle()->GetPdgCode() , GetResonancePDG())) continue; r = 0; imother = -2; mother = 0; for (k=0; k<fSelRes.GetSize(); k++){ r = mini->GetParticle(fSelRes[k]); if(!r || r->Index()!=j) continue; imother=p->GetMother(); if(imother<0) continue; mother = dynamic_cast<AliMCParticle*>(event->GetTrack(imother)); if(!mother){ AliError("Failed casting the mother particle!"); continue; } r->Mother() = imother; r->PmotherX() = mother->Px(); r->PmotherY() = mother->Py(); r->PmotherZ() = mother->Pz(); r->MotherPDG() = mother->PdgCode(); break; } } return; } //__________________________________________________________________________________________________ void AliRsnMiniResonanceFinder::FillMother(TClonesArray* event, AliRsnMiniEvent* mini) { // // Loops over MC tracks to find matches to resonances that have been reconatructed and selected. // Adds information about their mothers to the mini event. // AOD version if (!event) { AliError("Missing AOD Event"); return; } if (!mini) { AliError("Missing AliRsnMiniEvent"); return; } AliAODMCParticle *p,*mother; AliRsnMiniParticle* r; Int_t j,k,imother, npart = event->GetEntries(); for (j=0; j<npart; j++) { p = (AliAODMCParticle*) event->At(j); if (!p) continue; if (!AliRsnDaughter::IsEquivalentPDGCode(p->GetPdgCode() , GetResonancePDG())) continue; r = 0; imother = -2; mother = 0; for (k=0; k<fSelRes.GetSize(); k++){ r = mini->GetParticle(fSelRes[k]); if(!r || r->Index()!=j) continue; imother=p->GetMother(); if(imother<0) continue; mother = dynamic_cast<AliAODMCParticle*>(event->At(imother)); if(!mother){ AliError("Failed casting the mother particle!"); continue; } r->Mother() = imother; r->PmotherX() = mother->Px(); r->PmotherY() = mother->Py(); r->PmotherZ() = mother->Pz(); r->MotherPDG() = mother->PdgCode(); break; } } return; } <commit_msg>Added option for resonances to have charge for MC analysis<commit_after>// // Class to identify resonance candidate pairs, which are then // added back into the mini event to serve as daughters for // another particle. // #include "Riostream.h" #include "TMath.h" #include "TString.h" #include "AliRsnMiniParticle.h" #include "AliRsnMiniPair.h" #include "AliRsnMiniEvent.h" #include "AliRsnMiniAnalysisTask.h" #include "AliLog.h" #include "AliRsnCutSet.h" ClassImp(AliRsnMiniResonanceFinder) //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::AliRsnMiniResonanceFinder(const char *name) : TNamed(name, ""), fCutIDrsn(0), fResMass(0.0), fResPDG(0), fPairCuts(0x0), fPair(), fSelRes(0), fSel1(0), fSel2(0), fPairMode(0), fEvent(0x0) { // // Constructor // fCutID[0] = fCutID[1] = -1; fDaughter[0] = fDaughter[1] = AliRsnDaughter::kUnknown; fCharge[0] = fCharge[1] = 0; } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::AliRsnMiniResonanceFinder(const AliRsnMiniResonanceFinder& copy) : TNamed(copy), fCutIDrsn(copy.fCutIDrsn), fResMass(copy.fResMass), fResPDG(copy.fResPDG), fPairCuts(copy.fPairCuts), fPair(), fSelRes(0), fSel1(0), fSel2(0), fPairMode(copy.fPairMode), fEvent(copy.fEvent) { // // Copy constructor // Int_t i; for (i = 0; i < 2; i++) { fCutID[i] = copy.fCutID[i]; fDaughter[i] = copy.fDaughter[i]; fCharge[i] = copy.fCharge[i]; } } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder &AliRsnMiniResonanceFinder::operator=(const AliRsnMiniResonanceFinder &copy) { // // Assignment operator // if (this == &copy) return *this; fCutIDrsn = copy.fCutIDrsn; fResMass = copy.fResMass; fResPDG = copy.fResPDG; fPairCuts = copy.fPairCuts; fPairMode = copy.fPairMode; fEvent = copy.fEvent; Int_t i; for (i = 0; i < 2; i++) { fCutID[i] = copy.fCutID[i]; fDaughter[i] = copy.fDaughter[i]; fCharge[i] = copy.fCharge[i]; } fSelRes.Set(0); fSel1.Set(0); fSel2.Set(0); return (*this); } //__________________________________________________________________________________________________ AliRsnMiniResonanceFinder::~AliRsnMiniResonanceFinder() { // // Destructor. // return; } /* //__________________________________________________________________________________________________ Int_t AliRsnMiniResonanceFinder::ConnectTo(AliRsnMiniAnalysisTask* task) { // // IMPORTANT: Do not assign any additional track cuts to the AliRsnMiniAnalysisTask // after calling this ConnectTo function. // task->SetResonanceFinder(this); fCutIDrsn = task->GetNumberOfTrackCuts(); return fCutIDrsn;// plug this value into AliRsnMiniOutput objects } */ //__________________________________________________________________________________________________ Int_t AliRsnMiniResonanceFinder::RunResonanceFinder(AliRsnMiniEvent* event) { // // Loops on the passed mini-event, and for each pair of particles // which satisfy the charge and cut requirements defined here, add an entry. // Returns the number of successful fillings. // // loop variables Int_t i1, i2, start, nadded = 0; AliRsnMiniParticle *r, *p1, *p2; //Set charge for resonance Char_t RsnCharge; if(fCharge[0] == '+'){ if(fCharge[1] == '-') RsnCharge = '0'; else if(fCharge[1] == '+') RsnCharge = '0'; else if(fCharge[1] == '0') RsnCharge = '+'; }else if(fCharge[0] == '-'){ if(fCharge[1] == '-') RsnCharge = '0'; else if(fCharge[1] == '+') RsnCharge = '0'; else if(fCharge[1] == '0') RsnCharge = '-'; }else if(fCharge[0] == '0'){ if(fCharge[1] == '-') RsnCharge = '-'; else if(fCharge[1] == '+') RsnCharge = '+'; else if(fCharge[1] == '0') RsnCharge = '0'; } // it is necessary to know if criteria for the two daughters are the same Bool_t sameCriteria = ((fCharge[0] == fCharge[1]) && (fDaughter[0] == fDaughter[1])); TString selList1 = ""; TString selList2 = ""; Int_t n1 = event->CountParticles(fSel1, fCharge[0], fCutID[0]); Int_t n2 = event->CountParticles(fSel2, fCharge[1], fCutID[1]); for (i1 = 0; i1 < n1; i1++) selList1.Append(Form("%d ", fSel1[i1])); for (i2 = 0; i2 < n2; i2++) selList2.Append(Form("%d ", fSel2[i2])); AliDebugClass(1, Form("[%10s] Part #1: -- evID %6d -- charge = %c -- cut ID = %d --> %4d tracks (%s)", GetName(), event->ID(), fCharge[0], fCutID[0], n1, selList1.Data())); AliDebugClass(1, Form("[%10s] Part #2: -- evID %6d -- charge = %c -- cut ID = %d --> %4d tracks (%s)", GetName(), event->ID(), fCharge[1], fCutID[1], n2, selList2.Data())); if (!n1 || !n2) { AliDebugClass(1, "No pairs to mix"); return 0; } // external loop for (i1 = 0; i1 < n1; i1++) { p1 = event->GetParticle(fSel1[i1]); // define starting point for inner loop // if daughter selection criteria (charge, cuts) are the same // and the two events coincide, internal loop must start from // the first track *after* current one; // otherwise it starts from the beginning start = (sameCriteria ? i1 + 1 : 0); AliDebugClass(2, Form("Start point = %d", start)); // internal loop for (i2 = start; i2 < n2; i2++) { p2 = event->GetParticle(fSel2[i2]); // avoid to mix a particle with itself if (p1->Index() == p2->Index()) { AliDebugClass(2, "Skipping same index"); continue; } // sum momenta fPair.Fill(p1, p2, GetMass(0), GetMass(1), fResMass); // check pair against cuts if (fPairCuts && !fPairCuts->IsSelected(&fPair)) continue; // package the pair as a mini particle if(fPairMode==1 && (p1->Mother()<0 || p1->Mother()!=p2->Mother() || !AliRsnDaughter::IsEquivalentPDGCode(p1->MotherPDG(),GetResonancePDG()) ) ) continue;// use only true pairs (MC) if(fPairMode==2 && p1->Mother()>=0 && p1->Mother()==p2->Mother()) continue;// use only false pairs (MC) r = event->AddParticle(); r->Clear(); r->SetResonance(); r->Charge() = '0'; r->SetCutBit(fCutIDrsn); if(p1->Charge()=='+'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p1->Index(); r->IndexV0Neg() = p2->Index(); r->Charge() = '0'; // does not account for double charges, e.g., Delta++ }else if(p2->Charge()=='0'){ r->IndexV0Pos() = p2->IndexV0Pos(); r->IndexV0Neg() = p2->IndexV0Neg(); r->IndexBachelor() = p1->Index(); r->Charge() = '+'; } }else if(p1->Charge()=='-'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p2->Index(); r->IndexV0Neg() = p1->Index(); r->Charge() = '0'; // does not account for double charges, e.g., anti-Delta-- }else if(p2->Charge()=='0'){ r->IndexV0Pos() = p2->IndexV0Pos(); r->IndexV0Neg() = p2->IndexV0Neg(); r->IndexBachelor() = p1->Index(); r->Charge() = '-'; } }else if(p1->Charge()=='0'){ if(p2->Charge()=='-' || p2->Charge()=='+'){ r->IndexV0Pos() = p1->IndexV0Pos(); r->IndexV0Neg() = p1->IndexV0Neg(); r->IndexBachelor() = p2->Index(); r->Charge() = p2->Charge(); } } r->PrecX() = fPair.Sum(0).X(); r->PrecY() = fPair.Sum(0).Y(); r->PrecZ() = fPair.Sum(0).Z(); r->StoredMass(0) = fPair.InvMass(0); if(p1->Mother()>=0 && p1->Mother()==p2->Mother()){ r->Index() = p1->Mother(); r->PsimX() = p1->PmotherX(); r->PsimY() = p1->PmotherY(); r->PsimZ() = p1->PmotherZ(); r->PDG() = p1->MotherPDG(); }else{ r->PsimX() = fPair.Sum(1).X(); r->PsimY() = fPair.Sum(1).Y(); r->PsimZ() = fPair.Sum(1).Z(); } r->StoredMass(1) = fPair.InvMass(1); r->PmotherX() = r->PmotherY() = r->PmotherZ() = 0.0;// filled later nadded++; } // end internal loop } // end external loop event->CountParticles(fSelRes, RsnCharge, fCutIDrsn); AliDebugClass(1, Form("Pairs added in total = %4d", nadded)); return nadded; } //__________________________________________________________________________________________________ void AliRsnMiniResonanceFinder::FillMother(AliMCEvent* event, AliRsnMiniEvent* mini) { // // Loops over MC tracks to find matches to resonances that have been reconatructed and selected. // Adds information about their mothers to the mini event. // ESD version if (!event) { AliError("Missing AliMCEvent"); return; } if (!mini) { AliError("Missing AliRsnMiniEvent"); return; } AliMCParticle *p,*mother; AliRsnMiniParticle* r; Int_t j,k,imother, npart = event->GetNumberOfTracks(); for (j=0; j<npart; j++) { p = (AliMCParticle*) event->GetTrack(j); if (!p) continue; if (!AliRsnDaughter::IsEquivalentPDGCode(p->Particle()->GetPdgCode() , GetResonancePDG())) continue; r = 0; imother = -2; mother = 0; for (k=0; k<fSelRes.GetSize(); k++){ r = mini->GetParticle(fSelRes[k]); if(!r || r->Index()!=j) continue; imother=p->GetMother(); if(imother<0) continue; mother = dynamic_cast<AliMCParticle*>(event->GetTrack(imother)); if(!mother){ AliError("Failed casting the mother particle!"); continue; } r->Mother() = imother; r->PmotherX() = mother->Px(); r->PmotherY() = mother->Py(); r->PmotherZ() = mother->Pz(); r->MotherPDG() = mother->PdgCode(); break; } } return; } //__________________________________________________________________________________________________ void AliRsnMiniResonanceFinder::FillMother(TClonesArray* event, AliRsnMiniEvent* mini) { // // Loops over MC tracks to find matches to resonances that have been reconatructed and selected. // Adds information about their mothers to the mini event. // AOD version if (!event) { AliError("Missing AOD Event"); return; } if (!mini) { AliError("Missing AliRsnMiniEvent"); return; } AliAODMCParticle *p,*mother; AliRsnMiniParticle* r; Int_t j,k,imother, npart = event->GetEntries(); for (j=0; j<npart; j++) { p = (AliAODMCParticle*) event->At(j); if (!p) continue; if (!AliRsnDaughter::IsEquivalentPDGCode(p->GetPdgCode() , GetResonancePDG())) continue; r = 0; imother = -2; mother = 0; for (k=0; k<fSelRes.GetSize(); k++){ r = mini->GetParticle(fSelRes[k]); if(!r || r->Index()!=j) continue; imother=p->GetMother(); if(imother<0) continue; mother = dynamic_cast<AliAODMCParticle*>(event->At(imother)); if(!mother){ AliError("Failed casting the mother particle!"); continue; } r->Mother() = imother; r->PmotherX() = mother->Px(); r->PmotherY() = mother->Py(); r->PmotherZ() = mother->Pz(); r->MotherPDG() = mother->PdgCode(); break; } } return; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <string> #include <iterator> #include <ctime> #include <unordered_map> #include <algorithm> #include <cmath> #include <chrono> #include <iostream> #include <fstream> #include <string> #include <iterator> #include <unordered_map> #include <unordered_set> #include <set> #include <algorithm> #include <chrono> #include <map> #include <set> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> using namespace std; char randomNucleotide(){ switch (rand() % 4){ case 0: return 'A'; case 1: return 'C'; case 2: return 'G'; case 3: return 'T'; } return 'A'; } string randomSequence(const uint length){ string result(length, 'A'); for(uint i(0); i < length; ++i){ result[i] = randomNucleotide(); } return result; } string mutateSequence(const string& referenceSequence, uint maxMutRate=6, vector <double> ratioMutation={0.06,0.73,0.21}){ //~ double substitutionRate(mutRate * ratioMutation[0]); //~ double insertionRate(mutRate * ratioMutation[1]); //~ double deletionRate(mutRate * ratioMutation[2]); string result; result.reserve(5 * referenceSequence.size()); for(uint i(0); i < referenceSequence.size(); ++i){ uint mutRate(rand() % maxMutRate); double substitutionRate(mutRate * ratioMutation[0]); double insertionRate(mutRate * ratioMutation[1]); double deletionRate(mutRate * ratioMutation[2]); uint dice(rand() % 100); if(dice<substitutionRate){ //SUBSTITUTION char newNucleotide(randomNucleotide()); while(newNucleotide == referenceSequence[i]){ newNucleotide = randomNucleotide(); } result.push_back(newNucleotide); continue; } if(dice < deletionRate+substitutionRate){ //DELETION continue; } if(dice < deletionRate + substitutionRate + insertionRate){ //INSERTION char newNucleotide(randomNucleotide()); result.push_back(newNucleotide); --i; continue; } //NO ERROR result.push_back(referenceSequence[i]); } return result; } vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=1, uint totalExonNumber=6, uint exonNumber=6, uint sizeExons=100){ vector<string> result; vector<string> exonList; for(uint i(0); i < totalExonNumber; ++i){ exonList.push_back(randomSequence(sizeExons)); } string transcript; transcript.reserve(exonNumber*sizeExons); unordered_set<uint> selectedExons; for(uint i(0); i < transcriptNumber; ++i){ uint dice1(rand() % (totalExonNumber-3)); uint transcriptExonNumber(dice1 + 3); //~ cout << transcriptExonNumber << endl; transcript = ""; selectedExons = {}; while(selectedExons.size() != transcriptExonNumber){ selectedExons.insert(rand() % totalExonNumber); } for(uint ii(0); ii < totalExonNumber; ++ii){ if(selectedExons.count(ii) == 1){ transcript += exonList[ii]; } } result.push_back(transcript); } return result; } void generateReads(uint numberReads, uint referencesNumber=1, const string& outFileName="simulatedReads.fa", const string& refFileName="RefFile"){ ofstream out(outFileName); ofstream outRef(refFileName); vector<vector<string>> referenceList; for(uint i(0);i < referencesNumber; ++i){ referenceList.push_back(generateAlternativeTranscriptReferences()); for(uint ii(0); ii<referenceList[i].size(); ++ii){ outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << endl; outRef << referenceList[i][ii] << endl; } } string refRead,realRead; for(uint i(0); i < numberReads; ++i){ uint dice1(rand() % referencesNumber); uint dice2(rand() % referenceList[dice1].size()); refRead = referenceList[dice1][dice2]; realRead = mutateSequence(refRead); out << ">referenceNumber:" << dice1 << " alternativeNumber" << dice2 << endl; out << realRead << endl; } } int main(int argc, char ** argv){ srand (time(NULL)); auto startChrono = chrono::system_clock::now(); generateReads(1000); auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono; cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl; return 0; } <commit_msg>small fixes<commit_after>#include <iostream> #include <fstream> #include <vector> #include <string> #include <iterator> #include <ctime> #include <unordered_map> #include <algorithm> #include <cmath> #include <chrono> #include <iostream> #include <fstream> #include <string> #include <iterator> #include <unordered_map> #include <unordered_set> #include <set> #include <algorithm> #include <chrono> #include <map> #include <set> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> using namespace std; char randomNucleotide(){ switch (rand() % 4){ case 0: return 'A'; case 1: return 'C'; case 2: return 'G'; case 3: return 'T'; } return 'A'; } string randomSequence(const uint length){ string result(length, 'A'); for(uint i(0); i < length; ++i){ result[i] = randomNucleotide(); } return result; } //~ string mutateSequence(const string& referenceSequence, uint maxMutRate=6, vector <double> ratioMutation={0.06,0.73,0.21}){ string mutateSequence(const string& referenceSequence, uint maxMutRate=6, vector <double> ratioMutation={0.06,0.73,0.21}){ string result; result.reserve(5 * referenceSequence.size()); for(uint i(0); i < referenceSequence.size(); ++i){ uint mutRate(maxMutRate); //~ uint mutRate(rand() % maxMutRate); double substitutionRate(mutRate * ratioMutation[0]); double insertionRate(mutRate * ratioMutation[1]); double deletionRate(mutRate * ratioMutation[2]); uint dice(rand() % 100); if(dice<substitutionRate){ //SUBSTITUTION char newNucleotide(randomNucleotide()); while(newNucleotide == referenceSequence[i]){ newNucleotide = randomNucleotide(); } result.push_back(newNucleotide); continue; } if(dice < deletionRate+substitutionRate){ //DELETION continue; } if(dice < deletionRate + substitutionRate + insertionRate){ //INSERTION char newNucleotide(randomNucleotide()); result.push_back(newNucleotide); --i; continue; } //NO ERROR result.push_back(referenceSequence[i]); } return result; } vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=3, uint totalExonNumber=15, uint exonNumber=6, uint sizeExons=100){ //~ vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=3, uint totalExonNumber=15, uint exonNumber=6, uint sizeExons=100){ vector<string> result; vector<string> exonList; for(uint i(0); i < totalExonNumber; ++i){ exonList.push_back(randomSequence(sizeExons)); } string transcript; transcript.reserve(exonNumber*sizeExons); unordered_set<uint> selectedExons; for(uint i(0); i < transcriptNumber; ++i){ uint dice1(rand() % (totalExonNumber-3)); uint transcriptExonNumber(dice1 + 3); //~ cout << transcriptExonNumber << endl; transcript = ""; selectedExons = {}; while(selectedExons.size() != transcriptExonNumber){ selectedExons.insert(rand() % totalExonNumber); } for(uint ii(0); ii < totalExonNumber; ++ii){ if(selectedExons.count(ii) == 1){ transcript += exonList[ii]; } } result.push_back(transcript); } return result; } void generateReads(uint numberReads, uint referencesNumber=100, const string& outFileName="simulatedReads.fa", const string& refFileName="RefFile"){ ofstream out(outFileName); ofstream outRef(refFileName); vector<vector<string>> referenceList; for(uint i(0);i < referencesNumber; ++i){ referenceList.push_back(generateAlternativeTranscriptReferences()); for(uint ii(0); ii<referenceList[i].size(); ++ii){ outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << endl; outRef << referenceList[i][ii] << endl; } } string refRead,realRead; for(uint i(0); i < numberReads; ++i){ uint dice1(rand() % referencesNumber); uint dice2(rand() % referenceList[dice1].size()); refRead = referenceList[dice1][dice2]; realRead = mutateSequence(refRead); out << ">referenceNumber:" << dice1 << " alternativeNumber" << dice2 << endl; out << realRead << endl; } } int main(int argc, char ** argv){ srand (time(NULL)); auto startChrono = chrono::system_clock::now(); generateReads(1000); auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono; cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl; return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "XMLIndexBibliographyConfigurationContext.hxx" #include "XMLIndexBibliographyEntryContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <tools/debug.hxx> #include <rtl/ustring.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::lang::XMultiServiceFactory; const sal_Char sAPI_FieldMaster_Bibliography[] = "com.sun.star.text.FieldMaster.Bibliography"; TYPEINIT1( XMLIndexBibliographyConfigurationContext, SvXMLStyleContext ); XMLIndexBibliographyConfigurationContext::XMLIndexBibliographyConfigurationContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList) : SvXMLStyleContext(rImport, nPrfx, rLocalName, xAttrList, XML_STYLE_FAMILY_TEXT_BIBLIOGRAPHYCONFIG), sFieldMaster_Bibliography( RTL_CONSTASCII_USTRINGPARAM(sAPI_FieldMaster_Bibliography)), sBracketBefore(RTL_CONSTASCII_USTRINGPARAM("BracketBefore")), sBracketAfter(RTL_CONSTASCII_USTRINGPARAM("BracketAfter")), sIsNumberEntries(RTL_CONSTASCII_USTRINGPARAM("IsNumberEntries")), sIsSortByPosition(RTL_CONSTASCII_USTRINGPARAM("IsSortByPosition")), sSortKeys(RTL_CONSTASCII_USTRINGPARAM("SortKeys")), sSortKey(RTL_CONSTASCII_USTRINGPARAM("SortKey")), sIsSortAscending(RTL_CONSTASCII_USTRINGPARAM("IsSortAscending")), sSortAlgorithm(RTL_CONSTASCII_USTRINGPARAM("SortAlgorithm")), sLocale(RTL_CONSTASCII_USTRINGPARAM("Locale")), sSuffix(), sPrefix(), sAlgorithm(), aLocale(), bNumberedEntries(sal_False), bSortByPosition(sal_True) { } XMLIndexBibliographyConfigurationContext::~XMLIndexBibliographyConfigurationContext() { } void XMLIndexBibliographyConfigurationContext::StartElement( const Reference<XAttributeList> & xAttrList) { sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); ProcessAttribute(nPrefix, sLocalName, xAttrList->getValueByIndex(nAttr)); // else: ignore } } void XMLIndexBibliographyConfigurationContext::ProcessAttribute( sal_uInt16 nPrefix, OUString sLocalName, OUString sValue) { if( XML_NAMESPACE_TEXT == nPrefix ) { if( IsXMLToken(sLocalName, XML_PREFIX) ) { sPrefix = sValue; } else if( IsXMLToken(sLocalName, XML_SUFFIX) ) { sSuffix = sValue; } else if( IsXMLToken(sLocalName, XML_NUMBERED_ENTRIES) ) { bool bTmp; if( SvXMLUnitConverter::convertBool(bTmp, sValue) ) { bNumberedEntries = bTmp; } } else if( IsXMLToken(sLocalName, XML_SORT_BY_POSITION) ) { bool bTmp; if (SvXMLUnitConverter::convertBool(bTmp, sValue)) { bSortByPosition = bTmp; } } else if( IsXMLToken(sLocalName, XML_SORT_ALGORITHM) ) { sAlgorithm = sValue; } } else if( XML_NAMESPACE_FO == nPrefix ) { if( IsXMLToken(sLocalName, XML_LANGUAGE) ) { aLocale.Language = sValue; } else if( IsXMLToken(sLocalName, XML_COUNTRY) ) { aLocale.Country = sValue; } } } SvXMLImportContext *XMLIndexBibliographyConfigurationContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { OUString sKey; sal_Bool bSort(sal_True); // process children here and use default context! if ( ( nPrefix == XML_NAMESPACE_TEXT ) && IsXMLToken( rLocalName, XML_SORT_KEY ) ) { sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrfx = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (nPrfx == XML_NAMESPACE_TEXT) { if ( IsXMLToken( sLocalName, XML_KEY ) ) { sKey = xAttrList->getValueByIndex(nAttr); } else if ( IsXMLToken( sLocalName, XML_SORT_ASCENDING ) ) { bool bTmp; if (SvXMLUnitConverter::convertBool( bTmp, xAttrList->getValueByIndex(nAttr))) { bSort = bTmp; } } } } // valid data? sal_uInt16 nKey; if (SvXMLUnitConverter::convertEnum(nKey, sKey, aBibliographyDataFieldMap)) { Any aAny; Sequence<PropertyValue> aKey(2); PropertyValue aNameValue; aNameValue.Name = sSortKey; aAny <<= (sal_Int16)nKey; aNameValue.Value = aAny; aKey[0] = aNameValue; PropertyValue aSortValue; aSortValue.Name = sIsSortAscending; aAny.setValue(&bSort, ::getBooleanCppuType()); aSortValue.Value = aAny; aKey[1] = aSortValue; aSortKeys.push_back(aKey); } } return SvXMLImportContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } void XMLIndexBibliographyConfigurationContext::CreateAndInsert(sal_Bool) { // (code almost the same as export...) // insert and block mode is handled in insertStyleFamily // first: get field master // (we'll create one, and get the only master for this type) Reference<XMultiServiceFactory> xFactory(GetImport().GetModel(),UNO_QUERY); if( xFactory.is() ) { Sequence<rtl::OUString> aServices = xFactory->getAvailableServiceNames(); sal_Bool bFound(sal_False); sal_Int32 i(0); sal_Int32 nServiceCount(aServices.getLength()); while (i < nServiceCount && !bFound) { if (aServices[i].equals(sFieldMaster_Bibliography)) // here we should use a methode which compares in reverse order if available // #85282# bFound = sal_True; else i++; } if (bFound) { Reference<XInterface> xIfc = xFactory->createInstance(sFieldMaster_Bibliography); if( xIfc.is() ) { Reference<XPropertySet> xPropSet( xIfc, UNO_QUERY ); Any aAny; aAny <<= sSuffix; xPropSet->setPropertyValue(sBracketAfter, aAny); aAny <<= sPrefix; xPropSet->setPropertyValue(sBracketBefore, aAny); aAny.setValue(&bNumberedEntries, ::getBooleanCppuType()); xPropSet->setPropertyValue(sIsNumberEntries, aAny); aAny.setValue(&bSortByPosition, ::getBooleanCppuType()); xPropSet->setPropertyValue(sIsSortByPosition, aAny); if( (aLocale.Language.getLength() > 0) && (aLocale.Country.getLength() > 0) ) { aAny <<= aLocale; xPropSet->setPropertyValue(sLocale, aAny); } if( sAlgorithm.getLength() > 0 ) { aAny <<= sAlgorithm; xPropSet->setPropertyValue(sSortAlgorithm, aAny); } sal_Int32 nCount = aSortKeys.size(); Sequence<Sequence<PropertyValue> > aKeysSeq(nCount); for(i = 0; i < nCount; i++) { aKeysSeq[i] = aSortKeys[i]; } aAny <<= aKeysSeq; xPropSet->setPropertyValue(sSortKeys, aAny); } // else: can't get FieldMaster -> ignore } } // else: can't even get Factory -> ignore } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix typo<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "XMLIndexBibliographyConfigurationContext.hxx" #include "XMLIndexBibliographyEntryContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <tools/debug.hxx> #include <rtl/ustring.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::lang::XMultiServiceFactory; const sal_Char sAPI_FieldMaster_Bibliography[] = "com.sun.star.text.FieldMaster.Bibliography"; TYPEINIT1( XMLIndexBibliographyConfigurationContext, SvXMLStyleContext ); XMLIndexBibliographyConfigurationContext::XMLIndexBibliographyConfigurationContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList) : SvXMLStyleContext(rImport, nPrfx, rLocalName, xAttrList, XML_STYLE_FAMILY_TEXT_BIBLIOGRAPHYCONFIG), sFieldMaster_Bibliography( RTL_CONSTASCII_USTRINGPARAM(sAPI_FieldMaster_Bibliography)), sBracketBefore(RTL_CONSTASCII_USTRINGPARAM("BracketBefore")), sBracketAfter(RTL_CONSTASCII_USTRINGPARAM("BracketAfter")), sIsNumberEntries(RTL_CONSTASCII_USTRINGPARAM("IsNumberEntries")), sIsSortByPosition(RTL_CONSTASCII_USTRINGPARAM("IsSortByPosition")), sSortKeys(RTL_CONSTASCII_USTRINGPARAM("SortKeys")), sSortKey(RTL_CONSTASCII_USTRINGPARAM("SortKey")), sIsSortAscending(RTL_CONSTASCII_USTRINGPARAM("IsSortAscending")), sSortAlgorithm(RTL_CONSTASCII_USTRINGPARAM("SortAlgorithm")), sLocale(RTL_CONSTASCII_USTRINGPARAM("Locale")), sSuffix(), sPrefix(), sAlgorithm(), aLocale(), bNumberedEntries(sal_False), bSortByPosition(sal_True) { } XMLIndexBibliographyConfigurationContext::~XMLIndexBibliographyConfigurationContext() { } void XMLIndexBibliographyConfigurationContext::StartElement( const Reference<XAttributeList> & xAttrList) { sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); ProcessAttribute(nPrefix, sLocalName, xAttrList->getValueByIndex(nAttr)); // else: ignore } } void XMLIndexBibliographyConfigurationContext::ProcessAttribute( sal_uInt16 nPrefix, OUString sLocalName, OUString sValue) { if( XML_NAMESPACE_TEXT == nPrefix ) { if( IsXMLToken(sLocalName, XML_PREFIX) ) { sPrefix = sValue; } else if( IsXMLToken(sLocalName, XML_SUFFIX) ) { sSuffix = sValue; } else if( IsXMLToken(sLocalName, XML_NUMBERED_ENTRIES) ) { bool bTmp; if( SvXMLUnitConverter::convertBool(bTmp, sValue) ) { bNumberedEntries = bTmp; } } else if( IsXMLToken(sLocalName, XML_SORT_BY_POSITION) ) { bool bTmp; if (SvXMLUnitConverter::convertBool(bTmp, sValue)) { bSortByPosition = bTmp; } } else if( IsXMLToken(sLocalName, XML_SORT_ALGORITHM) ) { sAlgorithm = sValue; } } else if( XML_NAMESPACE_FO == nPrefix ) { if( IsXMLToken(sLocalName, XML_LANGUAGE) ) { aLocale.Language = sValue; } else if( IsXMLToken(sLocalName, XML_COUNTRY) ) { aLocale.Country = sValue; } } } SvXMLImportContext *XMLIndexBibliographyConfigurationContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { OUString sKey; sal_Bool bSort(sal_True); // process children here and use default context! if ( ( nPrefix == XML_NAMESPACE_TEXT ) && IsXMLToken( rLocalName, XML_SORT_KEY ) ) { sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrfx = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (nPrfx == XML_NAMESPACE_TEXT) { if ( IsXMLToken( sLocalName, XML_KEY ) ) { sKey = xAttrList->getValueByIndex(nAttr); } else if ( IsXMLToken( sLocalName, XML_SORT_ASCENDING ) ) { bool bTmp; if (SvXMLUnitConverter::convertBool( bTmp, xAttrList->getValueByIndex(nAttr))) { bSort = bTmp; } } } } // valid data? sal_uInt16 nKey; if (SvXMLUnitConverter::convertEnum(nKey, sKey, aBibliographyDataFieldMap)) { Any aAny; Sequence<PropertyValue> aKey(2); PropertyValue aNameValue; aNameValue.Name = sSortKey; aAny <<= (sal_Int16)nKey; aNameValue.Value = aAny; aKey[0] = aNameValue; PropertyValue aSortValue; aSortValue.Name = sIsSortAscending; aAny.setValue(&bSort, ::getBooleanCppuType()); aSortValue.Value = aAny; aKey[1] = aSortValue; aSortKeys.push_back(aKey); } } return SvXMLImportContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } void XMLIndexBibliographyConfigurationContext::CreateAndInsert(sal_Bool) { // (code almost the same as export...) // insert and block mode is handled in insertStyleFamily // first: get field master // (we'll create one, and get the only master for this type) Reference<XMultiServiceFactory> xFactory(GetImport().GetModel(),UNO_QUERY); if( xFactory.is() ) { Sequence<rtl::OUString> aServices = xFactory->getAvailableServiceNames(); sal_Bool bFound(sal_False); sal_Int32 i(0); sal_Int32 nServiceCount(aServices.getLength()); while (i < nServiceCount && !bFound) { if (aServices[i].equals(sFieldMaster_Bibliography)) // here we should use a method which compares in reverse order if available // #85282# bFound = sal_True; else i++; } if (bFound) { Reference<XInterface> xIfc = xFactory->createInstance(sFieldMaster_Bibliography); if( xIfc.is() ) { Reference<XPropertySet> xPropSet( xIfc, UNO_QUERY ); Any aAny; aAny <<= sSuffix; xPropSet->setPropertyValue(sBracketAfter, aAny); aAny <<= sPrefix; xPropSet->setPropertyValue(sBracketBefore, aAny); aAny.setValue(&bNumberedEntries, ::getBooleanCppuType()); xPropSet->setPropertyValue(sIsNumberEntries, aAny); aAny.setValue(&bSortByPosition, ::getBooleanCppuType()); xPropSet->setPropertyValue(sIsSortByPosition, aAny); if( (aLocale.Language.getLength() > 0) && (aLocale.Country.getLength() > 0) ) { aAny <<= aLocale; xPropSet->setPropertyValue(sLocale, aAny); } if( sAlgorithm.getLength() > 0 ) { aAny <<= sAlgorithm; xPropSet->setPropertyValue(sSortAlgorithm, aAny); } sal_Int32 nCount = aSortKeys.size(); Sequence<Sequence<PropertyValue> > aKeysSeq(nCount); for(i = 0; i < nCount; i++) { aKeysSeq[i] = aSortKeys[i]; } aAny <<= aKeysSeq; xPropSet->setPropertyValue(sSortKeys, aAny); } // else: can't get FieldMaster -> ignore } } // else: can't even get Factory -> ignore } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestScalarBarWidget.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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware 2011-12 // This work was supported by Commissariat a l'Energie Atomique (CEA/DIF) #include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkMultiBlockDataSet.h" #include "vtkMultiBlockPLOT3DReader.h" #include "vtkPolyDataMapper.h" #include "vtkProperty2D.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkScalarBarActor.h" #include "vtkStructuredGrid.h" #include "vtkStructuredGridGeometryFilter.h" #include "vtkTextProperty.h" #include "vtkTestUtilities.h" int TestScalarBar( int argc, char *argv[] ) { char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/combxyz.bin"); char* fname2 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/combq.bin"); // Start by loading some data. vtkSmartPointer<vtkMultiBlockPLOT3DReader> pl3d = vtkSmartPointer<vtkMultiBlockPLOT3DReader>::New(); pl3d->SetXYZFileName( fname ); pl3d->SetQFileName( fname2 ); pl3d->SetScalarFunctionNumber( 100 ); pl3d->SetVectorFunctionNumber( 202 ); pl3d->Update(); delete [] fname; delete [] fname2; // An outline is shown for context. vtkSmartPointer<vtkStructuredGridGeometryFilter> outline = vtkSmartPointer<vtkStructuredGridGeometryFilter>::New(); outline->SetInputData( pl3d->GetOutput()->GetBlock( 0 )); outline->SetExtent( 0, 100, 0, 100, 9, 9 ); vtkSmartPointer<vtkPolyDataMapper> outlineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); outlineMapper->SetInputConnection( outline->GetOutputPort()); vtkSmartPointer<vtkActor> outlineActor = vtkSmartPointer<vtkActor>::New(); outlineActor->SetMapper( outlineMapper ); // Create the RenderWindow, Renderer and all Actors // vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( renWin ); vtkSmartPointer<vtkScalarBarActor> scalarBar1 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar1->SetTitle("Density"); scalarBar1->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar1->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar1->GetPositionCoordinate()->SetValue( .6, .05 ); scalarBar1->SetWidth( 0.15 ); scalarBar1->SetHeight( 0.5 ); scalarBar1->SetTextPositionToPrecedeScalarBar(); scalarBar1->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar1->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar1->SetDrawFrame( 1 ); scalarBar1->GetFrameProperty()->SetColor( 0., 0., 0. ); scalarBar1->SetDrawBackground( 1 ); scalarBar1->GetBackgroundProperty()->SetColor( 1., 1., 1. ); vtkSmartPointer<vtkScalarBarActor> scalarBar2 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar2->SetTitle("Density"); scalarBar2->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar2->SetOrientationToHorizontal(); scalarBar2->SetWidth( 0.5 ); scalarBar2->SetHeight( 0.15 ); scalarBar2->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar2->GetPositionCoordinate()->SetValue( 0.05, 0.05 ); scalarBar2->SetTextPositionToPrecedeScalarBar(); scalarBar2->GetTitleTextProperty()->SetColor( 1., 0., 0. ); scalarBar2->GetLabelTextProperty()->SetColor( .8, 0., 0. ); scalarBar2->SetDrawFrame( 1 ); scalarBar2->GetFrameProperty()->SetColor( 1., 0., 0. ); scalarBar2->SetDrawBackground( 1 ); scalarBar2->GetBackgroundProperty()->SetColor( .5, .5, .5 ); vtkSmartPointer<vtkScalarBarActor> scalarBar3 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar3->SetTitle("Density"); scalarBar3->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar3->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar3->GetPositionCoordinate()->SetValue( .8, .05 ); scalarBar3->SetWidth( 0.15 ); scalarBar3->SetHeight( 0.5 ); scalarBar3->SetTextPositionToSucceedScalarBar(); scalarBar3->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar3->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar3->SetDrawFrame( 1 ); scalarBar3->GetFrameProperty()->SetColor( 0., 0., 0. ); scalarBar3->SetDrawBackground( 0 ); vtkSmartPointer<vtkScalarBarActor> scalarBar4 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar4->SetTitle("Density"); scalarBar4->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar4->SetOrientationToHorizontal(); scalarBar4->SetWidth( 0.5 ); scalarBar4->SetHeight( 0.15 ); scalarBar4->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar4->GetPositionCoordinate()->SetValue( .05, .8 ); scalarBar4->SetTextPositionToSucceedScalarBar(); scalarBar4->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar4->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar4->SetDrawFrame( 1 ); scalarBar4->GetFrameProperty()->SetColor( 1., 1., 1. ); scalarBar4->SetDrawBackground( 0 ); vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); camera->SetFocalPoint( 8, 0, 30 ); camera->SetPosition( 6, 0, 50 ); // Add the actors to the renderer, set the background and size // ren1->AddActor( outlineActor ); ren1->AddActor( scalarBar1 ); ren1->AddActor( scalarBar2 ); ren1->AddActor( scalarBar3 ); ren1->AddActor( scalarBar4 ); ren1->GradientBackgroundOn(); ren1->SetBackground( .5,.5,.5 ); ren1->SetBackground2( .0,.0,.0 ); ren1->SetActiveCamera( camera ); // render the image renWin->SetWindowName( "VTK - Scalar Bar options" ); renWin->SetSize( 700, 500 ); renWin->SetMultiSamples( 0 ); renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <commit_msg>Style fixed<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestScalarBarWidget.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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware 2011-12 // This work was supported by Commissariat a l'Energie Atomique (CEA/DIF) #include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkMultiBlockDataSet.h" #include "vtkMultiBlockPLOT3DReader.h" #include "vtkPolyDataMapper.h" #include "vtkProperty2D.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkScalarBarActor.h" #include "vtkStructuredGrid.h" #include "vtkStructuredGridGeometryFilter.h" #include "vtkTextProperty.h" #include "vtkTestUtilities.h" int TestScalarBar( int argc, char *argv[] ) { char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/combxyz.bin"); char* fname2 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/combq.bin"); // Start by loading some data. vtkSmartPointer<vtkMultiBlockPLOT3DReader> pl3d = vtkSmartPointer<vtkMultiBlockPLOT3DReader>::New(); pl3d->SetXYZFileName( fname ); pl3d->SetQFileName( fname2 ); pl3d->SetScalarFunctionNumber( 100 ); pl3d->SetVectorFunctionNumber( 202 ); pl3d->Update(); delete [] fname; delete [] fname2; // An outline is shown for context. vtkSmartPointer<vtkStructuredGridGeometryFilter> outline = vtkSmartPointer<vtkStructuredGridGeometryFilter>::New(); outline->SetInputData( pl3d->GetOutput()->GetBlock( 0 )); outline->SetExtent( 0, 100, 0, 100, 9, 9 ); vtkSmartPointer<vtkPolyDataMapper> outlineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); outlineMapper->SetInputConnection( outline->GetOutputPort()); vtkSmartPointer<vtkActor> outlineActor = vtkSmartPointer<vtkActor>::New(); outlineActor->SetMapper( outlineMapper ); // Create the RenderWindow, Renderer and all Actors vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( renWin ); vtkSmartPointer<vtkScalarBarActor> scalarBar1 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar1->SetTitle("Density"); scalarBar1->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar1->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar1->GetPositionCoordinate()->SetValue( .6, .05 ); scalarBar1->SetWidth( 0.15 ); scalarBar1->SetHeight( 0.5 ); scalarBar1->SetTextPositionToPrecedeScalarBar(); scalarBar1->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar1->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar1->SetDrawFrame( 1 ); scalarBar1->GetFrameProperty()->SetColor( 0., 0., 0. ); scalarBar1->SetDrawBackground( 1 ); scalarBar1->GetBackgroundProperty()->SetColor( 1., 1., 1. ); vtkSmartPointer<vtkScalarBarActor> scalarBar2 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar2->SetTitle("Density"); scalarBar2->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar2->SetOrientationToHorizontal(); scalarBar2->SetWidth( 0.5 ); scalarBar2->SetHeight( 0.15 ); scalarBar2->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar2->GetPositionCoordinate()->SetValue( 0.05, 0.05 ); scalarBar2->SetTextPositionToPrecedeScalarBar(); scalarBar2->GetTitleTextProperty()->SetColor( 1., 0., 0. ); scalarBar2->GetLabelTextProperty()->SetColor( .8, 0., 0. ); scalarBar2->SetDrawFrame( 1 ); scalarBar2->GetFrameProperty()->SetColor( 1., 0., 0. ); scalarBar2->SetDrawBackground( 1 ); scalarBar2->GetBackgroundProperty()->SetColor( .5, .5, .5 ); vtkSmartPointer<vtkScalarBarActor> scalarBar3 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar3->SetTitle("Density"); scalarBar3->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar3->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar3->GetPositionCoordinate()->SetValue( .8, .05 ); scalarBar3->SetWidth( 0.15 ); scalarBar3->SetHeight( 0.5 ); scalarBar3->SetTextPositionToSucceedScalarBar(); scalarBar3->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar3->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar3->SetDrawFrame( 1 ); scalarBar3->GetFrameProperty()->SetColor( 0., 0., 0. ); scalarBar3->SetDrawBackground( 0 ); vtkSmartPointer<vtkScalarBarActor> scalarBar4 = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar4->SetTitle("Density"); scalarBar4->SetLookupTable( outlineMapper->GetLookupTable()); scalarBar4->SetOrientationToHorizontal(); scalarBar4->SetWidth( 0.5 ); scalarBar4->SetHeight( 0.15 ); scalarBar4->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar4->GetPositionCoordinate()->SetValue( .05, .8 ); scalarBar4->SetTextPositionToSucceedScalarBar(); scalarBar4->GetTitleTextProperty()->SetColor( 0., 0., 1. ); scalarBar4->GetLabelTextProperty()->SetColor( 0., 0., 1. ); scalarBar4->SetDrawFrame( 1 ); scalarBar4->GetFrameProperty()->SetColor( 1., 1., 1. ); scalarBar4->SetDrawBackground( 0 ); vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); camera->SetFocalPoint( 8, 0, 30 ); camera->SetPosition( 6, 0, 50 ); // Add the actors to the renderer, set the background and size // ren1->AddActor( outlineActor ); ren1->AddActor( scalarBar1 ); ren1->AddActor( scalarBar2 ); ren1->AddActor( scalarBar3 ); ren1->AddActor( scalarBar4 ); ren1->GradientBackgroundOn(); ren1->SetBackground( .5,.5,.5 ); ren1->SetBackground2( .0,.0,.0 ); ren1->SetActiveCamera( camera ); // render the image renWin->SetWindowName( "VTK - Scalar Bar options" ); renWin->SetSize( 700, 500 ); renWin->SetMultiSamples( 0 ); renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "csllbc/common/Export.h" #include "csllbc/comm/csComponent.h" csllbc_Component::csllbc_Component(_D::Deleg_Comp_OnInit initDeleg, _D::Deleg_Comp_OnDestroy destroyDeleg, _D::Deleg_Comp_OnStart startDeleg, _D::Deleg_Comp_OnStop stopDeleg, _D::Deleg_Comp_OnUpdate updateDeleg, _D::Deleg_Comp_OnIdle idleDeleg, _D::Deleg_Comp_OnSessionCreate sessionCreateDeleg, _D::Deleg_Comp_OnSessionDestroy sessionDestroyDeleg, _D::Deleg_Comp_OnAsyncConnResult asyncConnResultDeleg, _D::Deleg_Comp_OnProtoReport protoReportDeleg, _D::Deleg_Comp_OnUnHandledPacket unHandledPacketDeleg) { _initDeleg = initDeleg; _destroyDeleg = destroyDeleg; _startDeleg = startDeleg; _stopDeleg = stopDeleg; _updateDeleg = updateDeleg; _idleDeleg = idleDeleg; _sessionCreateDeleg = sessionCreateDeleg; _sessionDestroyDeleg = sessionDestroyDeleg; _asyncConnResultDeleg = asyncConnResultDeleg; _protoReportDeleg = protoReportDeleg; _unHandledPacketDeleg = unHandledPacketDeleg; } bool csllbc_Component::OnInitialize() { (*_initDeleg)(); return true; } void csllbc_Component::OnDestroy() { (*_destroyDeleg)(); } bool csllbc_Component::OnStart(bool &startFinished) { (*_startDeleg)(); return true; } void csllbc_Component::OnStop(bool &stopFinished) { (*_stopDeleg)(); } void csllbc_Component::OnUpdate() { (*_updateDeleg)(); } void csllbc_Component::OnIdle(int idleTime) { (*_idleDeleg)(idleTime); } void csllbc_Component::OnSessionCreate(const LLBC_SessionInfo &sessionInfo) { const LLBC_SockAddr_IN &localAddr = sessionInfo.GetLocalAddr(); const LLBC_String localHost = localAddr.GetIpAsString(); const LLBC_SockAddr_IN &remoteAddr = sessionInfo.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_sessionCreateDeleg)(sessionInfo.IsListenSession(), sessionInfo.GetSessionId(), sessionInfo.GetAcceptSessionId(), static_cast<int>(sessionInfo.GetSocket()), localHost.c_str(), static_cast<int>(localHost.length()), localAddr.GetPort(), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort()); } void csllbc_Component::OnSessionDestroy(const LLBC_SessionDestroyInfo &destroyInfo) { const LLBC_SessionInfo &sessionInfo = destroyInfo.GetSessionInfo(); const LLBC_SockAddr_IN &localAddr = sessionInfo.GetLocalAddr(); const LLBC_String localHost = localAddr.GetIpAsString(); const LLBC_SockAddr_IN &remoteAddr = sessionInfo.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_sessionDestroyDeleg)(sessionInfo.IsListenSession(), sessionInfo.GetSessionId(), sessionInfo.GetAcceptSessionId(), static_cast<int>(sessionInfo.GetSocket()), localHost.c_str(), static_cast<int>(localHost.length()), localAddr.GetPort(), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort(), destroyInfo.IsDestroyedFromService(), destroyInfo.GetReason().c_str(), static_cast<int>(destroyInfo.GetReason().length()), destroyInfo.GetErrno(), destroyInfo.GetSubErrno()); } void csllbc_Component::OnAsyncConnResult(const LLBC_AsyncConnResult &result) { const LLBC_SockAddr_IN &remoteAddr = result.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_asyncConnResultDeleg)(result.IsConnected(), result.GetReason().c_str(), static_cast<int>(result.GetReason().length()), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort()); } void csllbc_Component::OnProtoReport(const LLBC_ProtoReport &report) { (*_protoReportDeleg)(report.GetSessionId(), report.GetLayer(), report.GetLevel(), report.GetReport().c_str(), static_cast<int>(report.GetReport().length())); } void csllbc_Component::OnUnHandledPacket(const LLBC_Packet &packet) { (*_unHandledPacketDeleg)(packet.GetSessionId(), packet.GetOpcode(), const_cast<void *>(packet.GetPayload()), static_cast<int>(packet.GetPayloadLength()), packet.GetStatus()); }<commit_msg>修复windows编译warnings<commit_after>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "csllbc/common/Export.h" #include "csllbc/comm/csComponent.h" csllbc_Component::csllbc_Component(_D::Deleg_Comp_OnInit initDeleg, _D::Deleg_Comp_OnDestroy destroyDeleg, _D::Deleg_Comp_OnStart startDeleg, _D::Deleg_Comp_OnStop stopDeleg, _D::Deleg_Comp_OnUpdate updateDeleg, _D::Deleg_Comp_OnIdle idleDeleg, _D::Deleg_Comp_OnSessionCreate sessionCreateDeleg, _D::Deleg_Comp_OnSessionDestroy sessionDestroyDeleg, _D::Deleg_Comp_OnAsyncConnResult asyncConnResultDeleg, _D::Deleg_Comp_OnProtoReport protoReportDeleg, _D::Deleg_Comp_OnUnHandledPacket unHandledPacketDeleg) { _initDeleg = initDeleg; _destroyDeleg = destroyDeleg; _startDeleg = startDeleg; _stopDeleg = stopDeleg; _updateDeleg = updateDeleg; _idleDeleg = idleDeleg; _sessionCreateDeleg = sessionCreateDeleg; _sessionDestroyDeleg = sessionDestroyDeleg; _asyncConnResultDeleg = asyncConnResultDeleg; _protoReportDeleg = protoReportDeleg; _unHandledPacketDeleg = unHandledPacketDeleg; } bool csllbc_Component::OnInitialize(bool &initFinished) { (*_initDeleg)(); return true; } void csllbc_Component::OnDestroy(bool &destroyFinished) { (*_destroyDeleg)(); } bool csllbc_Component::OnStart(bool &startFinished) { (*_startDeleg)(); return true; } void csllbc_Component::OnStop(bool &stopFinished) { (*_stopDeleg)(); } void csllbc_Component::OnUpdate() { (*_updateDeleg)(); } void csllbc_Component::OnIdle(int idleTime) { (*_idleDeleg)(idleTime); } void csllbc_Component::OnSessionCreate(const LLBC_SessionInfo &sessionInfo) { const LLBC_SockAddr_IN &localAddr = sessionInfo.GetLocalAddr(); const LLBC_String localHost = localAddr.GetIpAsString(); const LLBC_SockAddr_IN &remoteAddr = sessionInfo.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_sessionCreateDeleg)(sessionInfo.IsListenSession(), sessionInfo.GetSessionId(), sessionInfo.GetAcceptSessionId(), static_cast<int>(sessionInfo.GetSocket()), localHost.c_str(), static_cast<int>(localHost.length()), localAddr.GetPort(), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort()); } void csllbc_Component::OnSessionDestroy(const LLBC_SessionDestroyInfo &destroyInfo) { const LLBC_SessionInfo &sessionInfo = destroyInfo.GetSessionInfo(); const LLBC_SockAddr_IN &localAddr = sessionInfo.GetLocalAddr(); const LLBC_String localHost = localAddr.GetIpAsString(); const LLBC_SockAddr_IN &remoteAddr = sessionInfo.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_sessionDestroyDeleg)(sessionInfo.IsListenSession(), sessionInfo.GetSessionId(), sessionInfo.GetAcceptSessionId(), static_cast<int>(sessionInfo.GetSocket()), localHost.c_str(), static_cast<int>(localHost.length()), localAddr.GetPort(), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort(), destroyInfo.IsDestroyedFromService(), destroyInfo.GetReason().c_str(), static_cast<int>(destroyInfo.GetReason().length()), destroyInfo.GetErrno(), destroyInfo.GetSubErrno()); } void csllbc_Component::OnAsyncConnResult(const LLBC_AsyncConnResult &result) { const LLBC_SockAddr_IN &remoteAddr = result.GetPeerAddr(); const LLBC_String remoteHost = remoteAddr.GetIpAsString(); (*_asyncConnResultDeleg)(result.IsConnected(), result.GetReason().c_str(), static_cast<int>(result.GetReason().length()), remoteHost.c_str(), static_cast<int>(remoteHost.length()), remoteAddr.GetPort()); } void csllbc_Component::OnProtoReport(const LLBC_ProtoReport &report) { (*_protoReportDeleg)(report.GetSessionId(), report.GetLayer(), report.GetLevel(), report.GetReport().c_str(), static_cast<int>(report.GetReport().length())); } void csllbc_Component::OnUnHandledPacket(const LLBC_Packet &packet) { (*_unHandledPacketDeleg)(packet.GetSessionId(), packet.GetOpcode(), const_cast<void *>(packet.GetPayload()), static_cast<int>(packet.GetPayloadLength()), packet.GetStatus()); } <|endoftext|>
<commit_before>/******************************************************************************* * thrill/api/groupby.hpp * * DIANode for a groupby to indx operation. * Performs the actual groupby operation * * Part of Project Thrill. * * Copyright (C) 2015 Huyen Chau Nguyen <hello@chau-nguyen.de> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_API_GROUPBY_INDEX_HEADER #define THRILL_API_GROUPBY_INDEX_HEADER #include <thrill/api/dia.hpp> #include <thrill/api/dop_node.hpp> #include <thrill/api/groupby_iterator.hpp> #include <thrill/common/functional.hpp> #include <thrill/common/logger.hpp> #include <thrill/core/iterator_wrapper.hpp> #include <thrill/core/multiway_merge.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace thrill { namespace api { template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename GroupFunction, typename HashFunction> class GroupByIndexNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using ValueOut = ValueType; using ValueIn = typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0>>::type; using File = data::File; using Reader = typename File::Reader; using Writer = typename File::Writer; struct ValueComparator { ValueComparator(const GroupByIndexNode& info) : info_(info) { } const GroupByIndexNode& info_; bool operator () (const ValueIn& i, const ValueIn& j) { auto i_cmp = info_.hash_function_(info_.key_extractor_(i)); auto j_cmp = info_.hash_function_(info_.key_extractor_(j)); return (i_cmp < j_cmp); } }; using Super::context_; public: /*! * Constructor for a GroupByIndexNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ GroupByIndexNode(const ParentDIARef& parent, const KeyExtractor& key_extractor, const GroupFunction& groupby_function, std::size_t number_keys, const ValueOut& neutral_element, StatsNode* stats_node, const HashFunction& hash_function = HashFunction()) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, stats_node), key_extractor_(key_extractor), groupby_function_(groupby_function), number_keys_(number_keys), key_range_start_(std::get<0>(common::CalculateLocalRange( number_keys_, context_.num_workers(), context_.my_rank()))), key_range_end_(std::min(std::get<1>( common::CalculateLocalRange(number_keys_, context_.num_workers(), context_.my_rank())), number_keys_)), neutral_element_(neutral_element), hash_function_(hash_function), channel_(parent.ctx().GetNewChannel()), emitter_(channel_->OpenWriters()) { // Hook PreOp auto pre_op_fn = [=](const ValueIn& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain, this->type()); channel_->OnClose([this]() { this->WriteChannelStats(this->channel_); }); } //! Virtual destructor for a GroupByIndexNode. virtual ~GroupByIndexNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() override { MainOp(); } void PushData(bool consume) final { using Iterator = thrill::core::FileIteratorWrapper<ValueIn>; const std::size_t num_runs = files_.size(); // if there's only one run, store it if (num_runs == 1) { RunUserFunc(files_[0], consume); } // otherwise sort all runs using multiway merge else { std::vector<std::pair<Iterator, Iterator> > seq; seq.reserve(num_runs); for (std::size_t t = 0; t < num_runs; ++t) { std::shared_ptr<Reader> reader = std::make_shared<Reader>(files_[t].GetReader(consume)); Iterator s = Iterator(&files_[t], reader, 0, true); Iterator e = Iterator(&files_[t], reader, files_[t].num_items(), false); seq.push_back(std::make_pair(std::move(s), std::move(e))); } auto puller = core::get_sequential_file_multiway_merge_tree<true, false>( std::begin(seq), std::end(seq), totalsize_, ValueComparator(*this)); std::size_t curr_index = key_range_start_; if (puller.HasNext()) { // create iterator to pass to user_function auto user_iterator = GroupByMultiwayMergeIterator <ValueIn, KeyExtractor, ValueComparator> (puller, key_extractor_); while (user_iterator.HasNextForReal()) { if (user_iterator.GetNextKey() != curr_index) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } } else { //call user function const ValueOut res = groupby_function_(user_iterator, user_iterator.GetNextKey()); // push result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { // LOG << "grouped to value " << res; func(res); } } ++curr_index; } } while (curr_index < key_range_end_ - 1) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } ++curr_index; } } } void Dispose() override { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { return FunctionStack<ValueType>(); } private: const KeyExtractor& key_extractor_; const GroupFunction& groupby_function_; const std::size_t number_keys_; const std::size_t key_range_start_; const std::size_t key_range_end_; const ValueOut& neutral_element_; HashFunction hash_function_; std::size_t totalsize_ = 0; data::ChannelPtr channel_; std::vector<data::Channel::Writer> emitter_; std::vector<data::File> files_; void RunUserFunc(File& f, bool consume) { auto r = f.GetReader(consume); if (r.HasNext()) { // create iterator to pass to user_function auto user_iterator = GroupByIterator<ValueIn, KeyExtractor, ValueComparator>(r, key_extractor_); std::size_t curr_index = key_range_start_; while (user_iterator.HasNextForReal()) { if (user_iterator.GetNextKey() != curr_index) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } } else { // call user function const ValueOut res = groupby_function_(user_iterator, user_iterator.GetNextKey()); // push result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { // LOG << "grouped to value " << res; func(res); } } ++curr_index; } while (curr_index < key_range_end_ - 1) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } ++curr_index; } } } /* * Send all elements to their designated PEs */ void PreOp(const ValueIn& v) { const Key k = key_extractor_(v); assert(k < number_keys_); const auto recipient = k * emitter_.size() / number_keys_; assert(recipient < emitter_.size()); emitter_[recipient](v); } /* * Sort and store elements in a file */ void FlushVectorToFile(std::vector<ValueIn>& v) { // sort run and sort to file std::sort(v.begin(), v.end(), ValueComparator(*this)); File f = context_.GetFile(); { Writer w = f.GetWriter(); for (const ValueIn& e : v) { w(e); } w.Close(); } files_.push_back(f); } //! Receive elements from other workers. auto MainOp() { LOG << "running group by main op"; const bool consume = true; const std::size_t FIXED_VECTOR_SIZE = 1000000000 / sizeof(ValueIn); std::vector<ValueIn> incoming; incoming.reserve(FIXED_VECTOR_SIZE); // close all emitters for (auto& e : emitter_) { e.Close(); } // get incoming elements auto reader = channel_->OpenConcatReader(consume); while (reader.HasNext()) { // if vector is full save to disk if (incoming.size() == FIXED_VECTOR_SIZE) { totalsize_ += FIXED_VECTOR_SIZE; FlushVectorToFile(incoming); incoming.clear(); } // store incoming element const ValueIn elem = reader.template Next<ValueIn>(); incoming.push_back(elem); } totalsize_ += incoming.size(); FlushVectorToFile(incoming); std::vector<ValueIn>().swap(incoming); } }; /******************************************************************************/ template <typename ValueType, typename Stack> template <typename ValueOut, typename KeyExtractor, typename GroupFunction, typename HashFunction> auto DIARef<ValueType, Stack>::GroupByIndex( const KeyExtractor &key_extractor, const GroupFunction &groupby_function, const std::size_t number_keys, const ValueOut& neutral_element) const { using DOpResult = ValueOut; static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("GroupByIndex", DIANodeType::DOP); using GroupByResultNode = GroupByIndexNode<DOpResult, DIARef, KeyExtractor, GroupFunction, HashFunction>; auto shared_node = std::make_shared<GroupByResultNode>(*this, key_extractor, groupby_function, number_keys, neutral_element, stats_node); auto groupby_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(groupby_stack)>( shared_node, groupby_stack, { stats_node }); } } // namespace api } // namespace thrill #endif // !THRILL_API_GROUPBY_INDEX_HEADER /******************************************************************************/ <commit_msg>fix off by one error in indices<commit_after>/******************************************************************************* * thrill/api/groupby.hpp * * DIANode for a groupby to indx operation. * Performs the actual groupby operation * * Part of Project Thrill. * * Copyright (C) 2015 Huyen Chau Nguyen <hello@chau-nguyen.de> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_API_GROUPBY_INDEX_HEADER #define THRILL_API_GROUPBY_INDEX_HEADER #include <thrill/api/dia.hpp> #include <thrill/api/dop_node.hpp> #include <thrill/api/groupby_iterator.hpp> #include <thrill/common/functional.hpp> #include <thrill/common/logger.hpp> #include <thrill/core/iterator_wrapper.hpp> #include <thrill/core/multiway_merge.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace thrill { namespace api { template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename GroupFunction, typename HashFunction> class GroupByIndexNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using ValueOut = ValueType; using ValueIn = typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0>>::type; using File = data::File; using Reader = typename File::Reader; using Writer = typename File::Writer; struct ValueComparator { ValueComparator(const GroupByIndexNode& info) : info_(info) { } const GroupByIndexNode& info_; bool operator () (const ValueIn& i, const ValueIn& j) { auto i_cmp = info_.hash_function_(info_.key_extractor_(i)); auto j_cmp = info_.hash_function_(info_.key_extractor_(j)); return (i_cmp < j_cmp); } }; using Super::context_; public: /*! * Constructor for a GroupByIndexNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ GroupByIndexNode(const ParentDIARef& parent, const KeyExtractor& key_extractor, const GroupFunction& groupby_function, std::size_t number_keys, const ValueOut& neutral_element, StatsNode* stats_node, const HashFunction& hash_function = HashFunction()) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, stats_node), key_extractor_(key_extractor), groupby_function_(groupby_function), number_keys_(number_keys), key_range_start_(std::get<0>(common::CalculateLocalRange( number_keys_, context_.num_workers(), context_.my_rank()))), key_range_end_(std::min(std::get<1>( common::CalculateLocalRange(number_keys_, context_.num_workers(), context_.my_rank())), number_keys_)), neutral_element_(neutral_element), hash_function_(hash_function), channel_(parent.ctx().GetNewChannel()), emitter_(channel_->OpenWriters()) { // Hook PreOp auto pre_op_fn = [=](const ValueIn& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain, this->type()); channel_->OnClose([this]() { this->WriteChannelStats(this->channel_); }); } //! Virtual destructor for a GroupByIndexNode. virtual ~GroupByIndexNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() override { MainOp(); } void PushData(bool consume) final { using Iterator = thrill::core::FileIteratorWrapper<ValueIn>; const std::size_t num_runs = files_.size(); // if there's only one run, store it if (num_runs == 1) { RunUserFunc(files_[0], consume); } // otherwise sort all runs using multiway merge else { std::vector<std::pair<Iterator, Iterator> > seq; seq.reserve(num_runs); for (std::size_t t = 0; t < num_runs; ++t) { std::shared_ptr<Reader> reader = std::make_shared<Reader>(files_[t].GetReader(consume)); Iterator s = Iterator(&files_[t], reader, 0, true); Iterator e = Iterator(&files_[t], reader, files_[t].num_items(), false); seq.push_back(std::make_pair(std::move(s), std::move(e))); } auto puller = core::get_sequential_file_multiway_merge_tree<true, false>( std::begin(seq), std::end(seq), totalsize_, ValueComparator(*this)); std::size_t curr_index = key_range_start_; if (puller.HasNext()) { // create iterator to pass to user_function auto user_iterator = GroupByMultiwayMergeIterator <ValueIn, KeyExtractor, ValueComparator> (puller, key_extractor_); while (user_iterator.HasNextForReal()) { if (user_iterator.GetNextKey() != curr_index) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } } else { //call user function const ValueOut res = groupby_function_(user_iterator, user_iterator.GetNextKey()); // push result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { // LOG << "grouped to value " << res; func(res); } } ++curr_index; } } while (curr_index < key_range_end_) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } ++curr_index; } } } void Dispose() override { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { return FunctionStack<ValueType>(); } private: const KeyExtractor& key_extractor_; const GroupFunction& groupby_function_; const std::size_t number_keys_; const std::size_t key_range_start_; const std::size_t key_range_end_; const ValueOut& neutral_element_; HashFunction hash_function_; std::size_t totalsize_ = 0; data::ChannelPtr channel_; std::vector<data::Channel::Writer> emitter_; std::vector<data::File> files_; void RunUserFunc(File& f, bool consume) { auto r = f.GetReader(consume); if (r.HasNext()) { // create iterator to pass to user_function auto user_iterator = GroupByIterator<ValueIn, KeyExtractor, ValueComparator>(r, key_extractor_); std::size_t curr_index = key_range_start_; while (user_iterator.HasNextForReal()) { if (user_iterator.GetNextKey() != curr_index) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } } else { // call user function const ValueOut res = groupby_function_(user_iterator, user_iterator.GetNextKey()); // push result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { // LOG << "grouped to value " << res; func(res); } } ++curr_index; } while (curr_index < key_range_end_) { // push neutral element as result to callback functions for (auto func : DIANode<ValueType>::callbacks_) { func(neutral_element_); } ++curr_index; } } } /* * Send all elements to their designated PEs */ void PreOp(const ValueIn& v) { const Key k = key_extractor_(v); assert(k < number_keys_); const auto recipient = k * emitter_.size() / number_keys_; assert(recipient < emitter_.size()); emitter_[recipient](v); } /* * Sort and store elements in a file */ void FlushVectorToFile(std::vector<ValueIn>& v) { // sort run and sort to file std::sort(v.begin(), v.end(), ValueComparator(*this)); File f = context_.GetFile(); { Writer w = f.GetWriter(); for (const ValueIn& e : v) { w(e); } w.Close(); } files_.push_back(f); } //! Receive elements from other workers. auto MainOp() { LOG << "running group by main op"; const bool consume = true; const std::size_t FIXED_VECTOR_SIZE = 1000000000 / sizeof(ValueIn); std::vector<ValueIn> incoming; incoming.reserve(FIXED_VECTOR_SIZE); // close all emitters for (auto& e : emitter_) { e.Close(); } // get incoming elements auto reader = channel_->OpenConcatReader(consume); while (reader.HasNext()) { // if vector is full save to disk if (incoming.size() == FIXED_VECTOR_SIZE) { totalsize_ += FIXED_VECTOR_SIZE; FlushVectorToFile(incoming); incoming.clear(); } // store incoming element const ValueIn elem = reader.template Next<ValueIn>(); incoming.push_back(elem); } totalsize_ += incoming.size(); FlushVectorToFile(incoming); std::vector<ValueIn>().swap(incoming); } }; /******************************************************************************/ template <typename ValueType, typename Stack> template <typename ValueOut, typename KeyExtractor, typename GroupFunction, typename HashFunction> auto DIARef<ValueType, Stack>::GroupByIndex( const KeyExtractor &key_extractor, const GroupFunction &groupby_function, const std::size_t number_keys, const ValueOut& neutral_element) const { using DOpResult = ValueOut; static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("GroupByIndex", DIANodeType::DOP); using GroupByResultNode = GroupByIndexNode<DOpResult, DIARef, KeyExtractor, GroupFunction, HashFunction>; auto shared_node = std::make_shared<GroupByResultNode>(*this, key_extractor, groupby_function, number_keys, neutral_element, stats_node); auto groupby_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(groupby_stack)>( shared_node, groupby_stack, { stats_node }); } } // namespace api } // namespace thrill #endif // !THRILL_API_GROUPBY_INDEX_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "DataTransformMenu.h" #include <QAction> #include <QMainWindow> #include <QMenu> #include "AddExpressionReaction.h" #include "AddPythonTransformReaction.h" #include "CloneDataReaction.h" #include "ConvertToFloatReaction.h" #include "CropReaction.h" #include "DeleteDataReaction.h" #include "Utilities.h" namespace tomviz { DataTransformMenu::DataTransformMenu(QMainWindow* mainWindow, QMenu* transform, QMenu* seg) : QObject(mainWindow), m_transformMenu(transform), m_segmentationMenu(seg), m_mainWindow(mainWindow) { // Build the menu now buildTransforms(); buildSegmentation(); } void DataTransformMenu::buildTransforms() { QMainWindow* mainWindow = m_mainWindow; QMenu* menu = m_transformMenu; menu->clear(); // Build the Data Transforms menu auto customPythonAction = menu->addAction("Custom Transform"); auto cropDataAction = menu->addAction("Crop"); auto convertDataAction = menu->addAction("Convert To Float"); auto reinterpretSignedToUnignedAction = menu->addAction("Reinterpret Signed to Unsigned"); menu->addSeparator(); auto shiftUniformAction = menu->addAction("Shift Volume"); auto deleteSliceAction = menu->addAction("Delete Slices"); auto padVolumeAction = menu->addAction("Pad Volume"); auto downsampleByTwoAction = menu->addAction("Bin Volume x2"); auto resampleAction = menu->addAction("Resample"); auto rotateAction = menu->addAction("Rotate"); auto clearAction = menu->addAction("Clear Subvolume"); menu->addSeparator(); auto setNegativeVoxelsToZeroAction = menu->addAction("Set Negative Voxels To Zero"); auto addConstantAction = menu->addAction("Add Constant"); auto invertDataAction = menu->addAction("Invert Data"); auto squareRootAction = menu->addAction("Square Root Data"); auto hannWindowAction = menu->addAction("Hann Window"); auto fftAbsLogAction = menu->addAction("FFT (abs log)"); auto gradientMagnitudeSobelAction = menu->addAction("Gradient Magnitude"); auto unsharpMaskAction = menu->addAction("Unsharp Mask"); auto laplaceFilterAction = menu->addAction("Laplace Filter"); auto gaussianFilterAction = menu->addAction("Gaussian Filter"); auto peronaMalikeAnisotropicDiffusionAction = menu->addAction("Perona-Malik Anisotropic Diffusion"); auto medianFilterAction = menu->addAction("Median Filter"); menu->addSeparator(); auto cloneAction = menu->addAction("Clone"); auto deleteDataAction = menu->addAction( QIcon(":/QtWidgets/Icons/pqDelete32.png"), "Delete Data and Modules"); deleteDataAction->setToolTip("Delete Data"); // Add our Python script reactions, these compose Python into menu entries. new AddExpressionReaction(customPythonAction); new CropReaction(cropDataAction, mainWindow); new ConvertToFloatReaction(convertDataAction); new AddPythonTransformReaction( reinterpretSignedToUnignedAction, "Reinterpret Signed to Unsigned", readInPythonScript("ReinterpretSignedToUnsigned")); new AddPythonTransformReaction( shiftUniformAction, "Shift Volume", readInPythonScript("Shift_Stack_Uniformly"), false, false, readInJSONDescription("Shift_Stack_Uniformly")); new AddPythonTransformReaction(deleteSliceAction, "Delete Slices", readInPythonScript("deleteSlices")); new AddPythonTransformReaction(padVolumeAction, "Pad Volume", readInPythonScript("Pad_Data"), false, false, readInJSONDescription("Pad_Data")); new AddPythonTransformReaction(downsampleByTwoAction, "Bin Volume x2", readInPythonScript("BinVolumeByTwo")); new AddPythonTransformReaction(resampleAction, "Resample", readInPythonScript("Resample"), false, false, readInJSONDescription("Resample")); new AddPythonTransformReaction(rotateAction, "Rotate", readInPythonScript("Rotate3D"), false, false, readInJSONDescription("Rotate3D")); new AddPythonTransformReaction(clearAction, "Clear Volume", readInPythonScript("ClearVolume")); new AddPythonTransformReaction(setNegativeVoxelsToZeroAction, "Set Negative Voxels to Zero", readInPythonScript("SetNegativeVoxelsToZero")); new AddPythonTransformReaction(addConstantAction, "Add a Constant", readInPythonScript("AddConstant"), false, false, readInJSONDescription("AddConstant")); new AddPythonTransformReaction(invertDataAction, "Invert Data", readInPythonScript("InvertData")); new AddPythonTransformReaction(squareRootAction, "Square Root Data", readInPythonScript("Square_Root_Data")); new AddPythonTransformReaction(hannWindowAction, "Hann Window", readInPythonScript("HannWindow3D")); new AddPythonTransformReaction(fftAbsLogAction, "FFT (ABS LOG)", readInPythonScript("FFT_AbsLog")); new AddPythonTransformReaction(gradientMagnitudeSobelAction, "Gradient Magnitude", readInPythonScript("GradientMagnitude_Sobel")); new AddPythonTransformReaction(unsharpMaskAction, "Unsharp Mask", readInPythonScript("UnsharpMask"), false, false, readInJSONDescription("UnsharpMask")); new AddPythonTransformReaction(laplaceFilterAction, "Laplace Filter", readInPythonScript("LaplaceFilter")); new AddPythonTransformReaction(gaussianFilterAction, "Gaussian Filter", readInPythonScript("GaussianFilter"), false, false, readInJSONDescription("GaussianFilter")); new AddPythonTransformReaction( peronaMalikeAnisotropicDiffusionAction, "Perona-Malik Anisotropic Diffusion", readInPythonScript("PeronaMalikAnisotropicDiffusion"), false, false, readInJSONDescription("PeronaMalikAnisotropicDiffusion")); new AddPythonTransformReaction(medianFilterAction, "Median Filter", readInPythonScript("MedianFilter"), false, false, readInJSONDescription("MedianFilter")); new CloneDataReaction(cloneAction); new DeleteDataReaction(deleteDataAction); // TODO - enable/disable menu actions depending on whether the selected // DataSource has // the properties required by the Data Transform } void DataTransformMenu::buildSegmentation() { QMenu* menu = m_segmentationMenu; menu->clear(); auto customPythonITKAction = menu->addAction("Custom ITK Transform"); menu->addSeparator(); auto binaryThresholdAction = menu->addAction("Binary Threshold"); auto otsuMultipleThresholdAction = menu->addAction("Otsu Multiple Threshold"); auto connectedComponentsAction = menu->addAction("Connected Components"); menu->addSeparator(); auto binaryDilateAction = menu->addAction("Binary Dilate"); auto binaryErodeAction = menu->addAction("Binary Erode"); auto binaryOpenAction = menu->addAction("Binary Open"); auto binaryCloseAction = menu->addAction("Binary Close"); auto binaryMinMaxCurvatureFlowAction = menu->addAction("Binary MinMax Curvature Flow"); menu->addSeparator(); auto labelObjectAttributesAction = menu->addAction("Label Object Attributes"); auto labelObjectPrincipalAxesAction = menu->addAction("Label Object Principal Axes"); auto distanceFromAxisAction = menu->addAction("Label Object Distance From Principal Axis"); menu->addSeparator(); auto segmentParticlesAction = menu->addAction("Segment Particles"); auto segmentPoresAction = menu->addAction("Segment Pores"); new AddExpressionReaction(customPythonITKAction); new AddPythonTransformReaction(binaryThresholdAction, "Binary Threshold", readInPythonScript("BinaryThreshold"), false, false, readInJSONDescription("BinaryThreshold")); new AddPythonTransformReaction( otsuMultipleThresholdAction, "Otsu Multiple Threshold", readInPythonScript("OtsuMultipleThreshold"), false, false, readInJSONDescription("OtsuMultipleThreshold")); new AddPythonTransformReaction( connectedComponentsAction, "Connected Components", readInPythonScript("ConnectedComponents"), false, false, readInJSONDescription("ConnectedComponents")); new AddPythonTransformReaction(binaryDilateAction, "Binary Dilate", readInPythonScript("BinaryDilate"), false, false, readInJSONDescription("BinaryDilate")); new AddPythonTransformReaction(binaryErodeAction, "Binary Erode", readInPythonScript("BinaryErode"), false, false, readInJSONDescription("BinaryErode")); new AddPythonTransformReaction(binaryOpenAction, "Binary Open", readInPythonScript("BinaryOpen"), false, false, readInJSONDescription("BinaryOpen")); new AddPythonTransformReaction(binaryCloseAction, "Binary Close", readInPythonScript("BinaryClose"), false, false, readInJSONDescription("BinaryClose")); new AddPythonTransformReaction( binaryMinMaxCurvatureFlowAction, "Binary MinMax Curvature Flow", readInPythonScript("BinaryMinMaxCurvatureFlow"), false, false, readInJSONDescription("BinaryMinMaxCurvatureFlow")); new AddPythonTransformReaction( labelObjectAttributesAction, "Label Object Attributes", readInPythonScript("LabelObjectAttributes"), false, false, readInJSONDescription("LabelObjectAttributes")); new AddPythonTransformReaction( labelObjectPrincipalAxesAction, "Label Object Principal Axes", readInPythonScript("LabelObjectPrincipalAxes"), false, false, readInJSONDescription("LabelObjectPrincipalAxes")); new AddPythonTransformReaction( distanceFromAxisAction, "Label Object Distance From Principal Axis", readInPythonScript("LabelObjectDistanceFromPrincipalAxis"), false, false, readInJSONDescription("LabelObjectDistanceFromPrincipalAxis")); new AddPythonTransformReaction(segmentParticlesAction, "Segment Particles", readInPythonScript("SegmentParticles"), false, false, readInJSONDescription("SegmentParticles")); new AddPythonTransformReaction(segmentPoresAction, "Segment Pores", readInPythonScript("SegmentPores"), false, false, readInJSONDescription("SegmentPores")); } void DataTransformMenu::updateActions() { } } <commit_msg>Fixed typo in menu entry<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "DataTransformMenu.h" #include <QAction> #include <QMainWindow> #include <QMenu> #include "AddExpressionReaction.h" #include "AddPythonTransformReaction.h" #include "CloneDataReaction.h" #include "ConvertToFloatReaction.h" #include "CropReaction.h" #include "DeleteDataReaction.h" #include "Utilities.h" namespace tomviz { DataTransformMenu::DataTransformMenu(QMainWindow* mainWindow, QMenu* transform, QMenu* seg) : QObject(mainWindow), m_transformMenu(transform), m_segmentationMenu(seg), m_mainWindow(mainWindow) { // Build the menu now buildTransforms(); buildSegmentation(); } void DataTransformMenu::buildTransforms() { QMainWindow* mainWindow = m_mainWindow; QMenu* menu = m_transformMenu; menu->clear(); // Build the Data Transforms menu auto customPythonAction = menu->addAction("Custom Transform"); auto cropDataAction = menu->addAction("Crop"); auto convertDataAction = menu->addAction("Convert to Float"); auto reinterpretSignedToUnignedAction = menu->addAction("Reinterpret Signed to Unsigned"); menu->addSeparator(); auto shiftUniformAction = menu->addAction("Shift Volume"); auto deleteSliceAction = menu->addAction("Delete Slices"); auto padVolumeAction = menu->addAction("Pad Volume"); auto downsampleByTwoAction = menu->addAction("Bin Volume x2"); auto resampleAction = menu->addAction("Resample"); auto rotateAction = menu->addAction("Rotate"); auto clearAction = menu->addAction("Clear Subvolume"); menu->addSeparator(); auto setNegativeVoxelsToZeroAction = menu->addAction("Set Negative Voxels To Zero"); auto addConstantAction = menu->addAction("Add Constant"); auto invertDataAction = menu->addAction("Invert Data"); auto squareRootAction = menu->addAction("Square Root Data"); auto hannWindowAction = menu->addAction("Hann Window"); auto fftAbsLogAction = menu->addAction("FFT (abs log)"); auto gradientMagnitudeSobelAction = menu->addAction("Gradient Magnitude"); auto unsharpMaskAction = menu->addAction("Unsharp Mask"); auto laplaceFilterAction = menu->addAction("Laplace Filter"); auto gaussianFilterAction = menu->addAction("Gaussian Filter"); auto peronaMalikeAnisotropicDiffusionAction = menu->addAction("Perona-Malik Anisotropic Diffusion"); auto medianFilterAction = menu->addAction("Median Filter"); menu->addSeparator(); auto cloneAction = menu->addAction("Clone"); auto deleteDataAction = menu->addAction( QIcon(":/QtWidgets/Icons/pqDelete32.png"), "Delete Data and Modules"); deleteDataAction->setToolTip("Delete Data"); // Add our Python script reactions, these compose Python into menu entries. new AddExpressionReaction(customPythonAction); new CropReaction(cropDataAction, mainWindow); new ConvertToFloatReaction(convertDataAction); new AddPythonTransformReaction( reinterpretSignedToUnignedAction, "Reinterpret Signed to Unsigned", readInPythonScript("ReinterpretSignedToUnsigned")); new AddPythonTransformReaction( shiftUniformAction, "Shift Volume", readInPythonScript("Shift_Stack_Uniformly"), false, false, readInJSONDescription("Shift_Stack_Uniformly")); new AddPythonTransformReaction(deleteSliceAction, "Delete Slices", readInPythonScript("deleteSlices")); new AddPythonTransformReaction(padVolumeAction, "Pad Volume", readInPythonScript("Pad_Data"), false, false, readInJSONDescription("Pad_Data")); new AddPythonTransformReaction(downsampleByTwoAction, "Bin Volume x2", readInPythonScript("BinVolumeByTwo")); new AddPythonTransformReaction(resampleAction, "Resample", readInPythonScript("Resample"), false, false, readInJSONDescription("Resample")); new AddPythonTransformReaction(rotateAction, "Rotate", readInPythonScript("Rotate3D"), false, false, readInJSONDescription("Rotate3D")); new AddPythonTransformReaction(clearAction, "Clear Volume", readInPythonScript("ClearVolume")); new AddPythonTransformReaction(setNegativeVoxelsToZeroAction, "Set Negative Voxels to Zero", readInPythonScript("SetNegativeVoxelsToZero")); new AddPythonTransformReaction(addConstantAction, "Add a Constant", readInPythonScript("AddConstant"), false, false, readInJSONDescription("AddConstant")); new AddPythonTransformReaction(invertDataAction, "Invert Data", readInPythonScript("InvertData")); new AddPythonTransformReaction(squareRootAction, "Square Root Data", readInPythonScript("Square_Root_Data")); new AddPythonTransformReaction(hannWindowAction, "Hann Window", readInPythonScript("HannWindow3D")); new AddPythonTransformReaction(fftAbsLogAction, "FFT (ABS LOG)", readInPythonScript("FFT_AbsLog")); new AddPythonTransformReaction(gradientMagnitudeSobelAction, "Gradient Magnitude", readInPythonScript("GradientMagnitude_Sobel")); new AddPythonTransformReaction(unsharpMaskAction, "Unsharp Mask", readInPythonScript("UnsharpMask"), false, false, readInJSONDescription("UnsharpMask")); new AddPythonTransformReaction(laplaceFilterAction, "Laplace Filter", readInPythonScript("LaplaceFilter")); new AddPythonTransformReaction(gaussianFilterAction, "Gaussian Filter", readInPythonScript("GaussianFilter"), false, false, readInJSONDescription("GaussianFilter")); new AddPythonTransformReaction( peronaMalikeAnisotropicDiffusionAction, "Perona-Malik Anisotropic Diffusion", readInPythonScript("PeronaMalikAnisotropicDiffusion"), false, false, readInJSONDescription("PeronaMalikAnisotropicDiffusion")); new AddPythonTransformReaction(medianFilterAction, "Median Filter", readInPythonScript("MedianFilter"), false, false, readInJSONDescription("MedianFilter")); new CloneDataReaction(cloneAction); new DeleteDataReaction(deleteDataAction); // TODO - enable/disable menu actions depending on whether the selected // DataSource has // the properties required by the Data Transform } void DataTransformMenu::buildSegmentation() { QMenu* menu = m_segmentationMenu; menu->clear(); auto customPythonITKAction = menu->addAction("Custom ITK Transform"); menu->addSeparator(); auto binaryThresholdAction = menu->addAction("Binary Threshold"); auto otsuMultipleThresholdAction = menu->addAction("Otsu Multiple Threshold"); auto connectedComponentsAction = menu->addAction("Connected Components"); menu->addSeparator(); auto binaryDilateAction = menu->addAction("Binary Dilate"); auto binaryErodeAction = menu->addAction("Binary Erode"); auto binaryOpenAction = menu->addAction("Binary Open"); auto binaryCloseAction = menu->addAction("Binary Close"); auto binaryMinMaxCurvatureFlowAction = menu->addAction("Binary MinMax Curvature Flow"); menu->addSeparator(); auto labelObjectAttributesAction = menu->addAction("Label Object Attributes"); auto labelObjectPrincipalAxesAction = menu->addAction("Label Object Principal Axes"); auto distanceFromAxisAction = menu->addAction("Label Object Distance From Principal Axis"); menu->addSeparator(); auto segmentParticlesAction = menu->addAction("Segment Particles"); auto segmentPoresAction = menu->addAction("Segment Pores"); new AddExpressionReaction(customPythonITKAction); new AddPythonTransformReaction(binaryThresholdAction, "Binary Threshold", readInPythonScript("BinaryThreshold"), false, false, readInJSONDescription("BinaryThreshold")); new AddPythonTransformReaction( otsuMultipleThresholdAction, "Otsu Multiple Threshold", readInPythonScript("OtsuMultipleThreshold"), false, false, readInJSONDescription("OtsuMultipleThreshold")); new AddPythonTransformReaction( connectedComponentsAction, "Connected Components", readInPythonScript("ConnectedComponents"), false, false, readInJSONDescription("ConnectedComponents")); new AddPythonTransformReaction(binaryDilateAction, "Binary Dilate", readInPythonScript("BinaryDilate"), false, false, readInJSONDescription("BinaryDilate")); new AddPythonTransformReaction(binaryErodeAction, "Binary Erode", readInPythonScript("BinaryErode"), false, false, readInJSONDescription("BinaryErode")); new AddPythonTransformReaction(binaryOpenAction, "Binary Open", readInPythonScript("BinaryOpen"), false, false, readInJSONDescription("BinaryOpen")); new AddPythonTransformReaction(binaryCloseAction, "Binary Close", readInPythonScript("BinaryClose"), false, false, readInJSONDescription("BinaryClose")); new AddPythonTransformReaction( binaryMinMaxCurvatureFlowAction, "Binary MinMax Curvature Flow", readInPythonScript("BinaryMinMaxCurvatureFlow"), false, false, readInJSONDescription("BinaryMinMaxCurvatureFlow")); new AddPythonTransformReaction( labelObjectAttributesAction, "Label Object Attributes", readInPythonScript("LabelObjectAttributes"), false, false, readInJSONDescription("LabelObjectAttributes")); new AddPythonTransformReaction( labelObjectPrincipalAxesAction, "Label Object Principal Axes", readInPythonScript("LabelObjectPrincipalAxes"), false, false, readInJSONDescription("LabelObjectPrincipalAxes")); new AddPythonTransformReaction( distanceFromAxisAction, "Label Object Distance From Principal Axis", readInPythonScript("LabelObjectDistanceFromPrincipalAxis"), false, false, readInJSONDescription("LabelObjectDistanceFromPrincipalAxis")); new AddPythonTransformReaction(segmentParticlesAction, "Segment Particles", readInPythonScript("SegmentParticles"), false, false, readInJSONDescription("SegmentParticles")); new AddPythonTransformReaction(segmentPoresAction, "Segment Pores", readInPythonScript("SegmentPores"), false, false, readInJSONDescription("SegmentPores")); } void DataTransformMenu::updateActions() { } } <|endoftext|>
<commit_before>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_ #define G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_ /*===========================================================================*\ author: Matthias W. Smith email: mwsmith2@uw.edu file: field_constants.hh about: A header file for constant parameters used across field team software. \*===========================================================================*/ //--- project includes -----------------------------------------------------// #include <vector> //--- project includes -----------------------------------------------------// #include "field_constants.hh" namespace g2field { // A macro to define nmr structs since they are very similar. #define MAKE_NMR_STRUCT(name, num_ch, len_tr)\ struct name {\ Double_t sys_clock[num_ch];\ Double_t gps_clock[num_ch];\ Double_t dev_clock[num_ch];\ Double_t snr[num_ch];\ Double_t len[num_ch];\ Double_t freq[num_ch];\ Double_t ferr[num_ch];\ Double_t freq_zc[num_ch];\ Double_t ferr_zc[num_ch];\ UShort_t health[num_ch];\ UShort_t method[num_ch];\ UShort_t trace[num_ch][len_tr];\ }; // Might as well define a root branch string for the struct. #define MAKE_NMR_STRING(name, num_ch, len_tr) NMR_HELPER(name, num_ch, len_tr) #define NMR_HELPER(name, num_ch, len_tr) \ const char * const name = "sys_clock["#num_ch"]/D:gps_clock["#num_ch"]/D:"\ "dev_clock["#num_ch"]/D:snr["#num_ch"]/D:len["#num_ch"]/D:freq["#num_ch"]/D:"\ "ferr["#num_ch"]/D:freq_zc["#num_ch"]/D:ferr_zc["#num_ch"]/D:"\ "health["#num_ch"]/s:method["#num_ch"]/s:trace["#num_ch"]["#len_tr"]/s" // NMR structs MAKE_NMR_STRUCT(fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRING(fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRUCT(online_fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); MAKE_NMR_STRING(online_fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); // Flexible struct built from the basic nmr attributes. struct nmr_vector { std::vector<Double_t> sys_clock; std::vector<Double_t> gps_clock; std::vector<Double_t> dev_clock; std::vector<Double_t> snr; std::vector<Double_t> len; std::vector<Double_t> freq; std::vector<Double_t> ferr; std::vector<Double_t> freq_zc; std::vector<Double_t> ferr_zc; std::vector<UShort_t> health; std::vector<UShort_t> method; std::vector< std::array<UShort_t, NMR_FID_LENGTH_ONLINE> > trace; inline void Resize(int size) { sys_clock.resize(size); gps_clock.resize(size); dev_clock.resize(size); snr.resize(size); len.resize(size); freq.resize(size); ferr.resize(size); freq_zc.resize(size); ferr_zc.resize(size); health.resize(size); method.resize(size); trace.resize(size); } }; //Trolley data structs struct trolley_nmr_t{ ULong64_t gps_clock; UShort_t probe_index; UShort_t length; Short_t trace[TRLY_NMR_LENGTH]; }; #define MAKE_TLNMR_STRING(len) HELPER_TLNMR_STRING(len) #define HELPER_TLNMR_STRING(len) \ const char * const trolley_nmr_str = "gps_clock/l:probe_index/s:len/s:trace["#len"]/S" MAKE_TLNMR_STRING(TRLY_NMR_LENGTH); struct trolley_barcode_t{ ULong64_t gps_clock; UShort_t length_per_ch; UShort_t traces[TRLY_BARCODE_LENGTH]; //All channels }; #define MAKE_BARCODE_STRING(len) HELPER_BARCODE_STRING(len) #define HELPER_BARCODE_STRING(len) \ const char * const trolley_barcode_str = "gps_clock/l:len_per_ch/s:traces["#len"]/s" MAKE_BARCODE_STRING(TRLY_BARCODE_LENGTH); struct trolley_monitor_t{ ULong64_t gps_clock_cycle_start; UInt_t PMonitorVal; UInt_t PMonitorTemp; UInt_t RFPower1; UInt_t RFPower2; UInt_t NMRCheckSum; UInt_t FrameCheckSum; UInt_t FrameSum; UInt_t FrameIndex; UShort_t StatusBits; UShort_t TMonitorIn; UShort_t TMonitorExt1; UShort_t TMonitorExt2; UShort_t TMonitorExt3; UShort_t V1Min; UShort_t V1Max; UShort_t V2Min; UShort_t V2Max; UShort_t length_per_ch; UShort_t trace_VMonitor1[TRLY_MONITOR_LENGTH]; UShort_t trace_VMonitor2[TRLY_MONITOR_LENGTH]; }; #define MAKE_MONITOR_STRING(len) HELPER_MONITOR_STRING(len) #define HELPER_MONITOR_STRING(len) \ const char * const trolley_monitor_str = "gps_clock_cycle_start/l:PMonitorVal/i:PMonitorTemp/i:RFPower1/i:RFPower2/i:"\ "NMRCheckSum/i:FrameCheckSum/i:FrameSum/i:StatusBits/s:"\ "TMonitorIn/s:TMonitorExt1/s:TMonitorExt2/s:TMonitorExt3/s:V1Min/s:V1Max/s:V2Min/s:V2Max/s:len_per_ch/s:"\ "trace_VMonitor1["#len"]/s:trace_VMonitor2["#len"]/s" MAKE_MONITOR_STRING(TRLY_MONITOR_LENGTH); //Galil Data structs struct galil_data_t{ ULong64_t TimeStamp; Int_t Tensions[2]; Int_t Positions[3]; Int_t Velocities[3]; Int_t OutputVs[3]; }; const char * const galil_data_str = "TimeStamp/l:Tensions[2]/I:Positions[3]/I:Velocities[3]/I:OutputVs[3]/I"; //This struct is auxiliary struct galil_data_d_t{ Double_t Tensions[2]; Double_t Positions[3]; Double_t Velocities[3]; Double_t OutputVs[3]; }; //Absolute probe data struct struct absolute_nmr_info_t{ ULong64_t time_stamp; UInt_t length; Int_t Pos[4]; //Coordinate X,Y,Z,S UShort_t flay_run_number; UShort_t probe_index; //Because the length of the trace varies too much, it is not included in this struct }; #define MAKE_ABSNMR_STRING() HELPER_ABSNMR_STRING() #define HELPER_ABSNMR_STRING() \ const char * const absolute_nmr_info_str = "time_stamp/l:length/i:Pos[4]/i:flay_run_number/s:probe_index/s" MAKE_ABSNMR_STRING(); // Absolute calibration NMR structs MAKE_NMR_STRUCT(abs_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRING(abs_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRUCT(abs_online_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); MAKE_NMR_STRING(abs_online_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); //Surface coil struct struct surface_coil_t{ Double_t bot_sys_clock[SC_NUM_COILS]; Double_t top_sys_clock[SC_NUM_COILS]; Double_t bot_coil_currents[SC_NUM_COILS]; Double_t top_coil_currents[SC_NUM_COILS]; Double_t bot_coil_temps[SC_NUM_COILS]; Double_t top_coil_temps[SC_NUM_COILS]; }; #define MAKE_SC_STRING(name,num_coils) SC_HELPER(name,num_coils) #define SC_HELPER(name,num_coils)\ const char * const name = "sys_clock["#num_coils"]/D:bot_coil_currents["#num_coils"]/D:top_coil_currents["#num_coils"]/D:bot_coil_temps["#num_coils"]/D:top_coil_temps["#num_coils"]/D" MAKE_SC_STRING(sc_str,SC_NUM_COILS); // Yokogawa struct struct yokogawa_t{ ULong64_t sys_clock; // system clock ULong64_t gps_clock; // GPS clock Int_t mode; // device mode (0 = voltage, 1 = current) Int_t is_enabled; // is the output enabled (0 = false, 1 = true) Double_t current; // current setting (in mA) Double_t voltage; // voltage setting (in V) }; #define MAKE_YOKO_STRING() HELPER_YOKO_STRING() #define HELPER_YOKO_STRING() \ const char * const yokogawa_str = "sys_clock/l:gps_clock/l:is_enabled/i:current/D" MAKE_YOKO_STRING(); } // ::g2field #endif <commit_msg>update trolley structs<commit_after>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_ #define G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_ /*===========================================================================*\ author: Matthias W. Smith email: mwsmith2@uw.edu file: field_constants.hh about: A header file for constant parameters used across field team software. \*===========================================================================*/ //--- project includes -----------------------------------------------------// #include <vector> //--- project includes -----------------------------------------------------// #include "field_constants.hh" namespace g2field { // A macro to define nmr structs since they are very similar. #define MAKE_NMR_STRUCT(name, num_ch, len_tr)\ struct name {\ Double_t sys_clock[num_ch];\ Double_t gps_clock[num_ch];\ Double_t dev_clock[num_ch];\ Double_t snr[num_ch];\ Double_t len[num_ch];\ Double_t freq[num_ch];\ Double_t ferr[num_ch];\ Double_t freq_zc[num_ch];\ Double_t ferr_zc[num_ch];\ UShort_t health[num_ch];\ UShort_t method[num_ch];\ UShort_t trace[num_ch][len_tr];\ }; // Might as well define a root branch string for the struct. #define MAKE_NMR_STRING(name, num_ch, len_tr) NMR_HELPER(name, num_ch, len_tr) #define NMR_HELPER(name, num_ch, len_tr) \ const char * const name = "sys_clock["#num_ch"]/D:gps_clock["#num_ch"]/D:"\ "dev_clock["#num_ch"]/D:snr["#num_ch"]/D:len["#num_ch"]/D:freq["#num_ch"]/D:"\ "ferr["#num_ch"]/D:freq_zc["#num_ch"]/D:ferr_zc["#num_ch"]/D:"\ "health["#num_ch"]/s:method["#num_ch"]/s:trace["#num_ch"]["#len_tr"]/s" // NMR structs MAKE_NMR_STRUCT(fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRING(fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRUCT(online_fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); MAKE_NMR_STRING(online_fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); // Flexible struct built from the basic nmr attributes. struct nmr_vector { std::vector<Double_t> sys_clock; std::vector<Double_t> gps_clock; std::vector<Double_t> dev_clock; std::vector<Double_t> snr; std::vector<Double_t> len; std::vector<Double_t> freq; std::vector<Double_t> ferr; std::vector<Double_t> freq_zc; std::vector<Double_t> ferr_zc; std::vector<UShort_t> health; std::vector<UShort_t> method; std::vector< std::array<UShort_t, NMR_FID_LENGTH_ONLINE> > trace; inline void Resize(int size) { sys_clock.resize(size); gps_clock.resize(size); dev_clock.resize(size); snr.resize(size); len.resize(size); freq.resize(size); ferr.resize(size); freq_zc.resize(size); ferr_zc.resize(size); health.resize(size); method.resize(size); trace.resize(size); } }; //Trolley data structs struct trolley_nmr_t{ ULong64_t gps_clock; UShort_t probe_index; UShort_t length; UShort_t TS_offSet; UShort_t RF_Prescale; UShort_t Probe_Command; UShort_t Preamp_Delay; UShort_t Preamp_Period; UShort_t ADC_Gate_Delay; UShort_t ADC_Gate_Offset; UShort_t ADC_Gate_Period; UShort_t TX_Delay; UShort_t TX_Period; UShort_t UserDefinedData; Short_t trace[TRLY_NMR_LENGTH]; }; #define MAKE_TLNMR_STRING(len) HELPER_TLNMR_STRING(len) #define HELPER_TLNMR_STRING(len) \ const char * const trolley_nmr_str = "gps_clock/l:probe_index/s:len/s:TS_Offset/s:RF_Prescale/s:Probe_Command/s:Preamp_Delay/s:Preamp_Period/s:ADC_Gate_Delay/s:ADC_Gate_Offset/s:ADC_Gate_Period/s:TX_Delay/s:TX_Period/s:UserDefinedData/s:trace["#len"]/S" MAKE_TLNMR_STRING(TRLY_NMR_LENGTH); struct trolley_barcode_t{ ULong64_t gps_clock; UShort_t length_per_ch; UShort_t Sampling_Period; UShort_t Acquisition_Delay; UShort_t DAC_1_Config; UShort_t DAC_2_Config; UShort_t Ref_CM; UShort_t traces[TRLY_BARCODE_LENGTH]; //All channels }; #define MAKE_BARCODE_STRING(len) HELPER_BARCODE_STRING(len) #define HELPER_BARCODE_STRING(len) \ const char * const trolley_barcode_str = "gps_clock/l:len_per_ch/s:Sampling_Period/s:Acquisition_Delay/s:DAC_1_Config/s:DAC_2_Config/s:Ref_CM/s:traces["#len"]/s" MAKE_BARCODE_STRING(TRLY_BARCODE_LENGTH); struct trolley_monitor_t{ ULong64_t gps_clock_cycle_start; UInt_t PMonitorVal; UInt_t PMonitorTemp; UInt_t RFPower1; UInt_t RFPower2; UInt_t NMRCheckSum; UInt_t ConfigCheckSum; UInt_t FrameCheckSum; UInt_t NMRFrameSum; UInt_t ConfigFrameSum; UInt_t FrameSum; UInt_t FrameIndex; UShort_t StatusBits; UShort_t TMonitorIn; UShort_t TMonitorExt1; UShort_t TMonitorExt2; UShort_t TMonitorExt3; UShort_t V1Min; UShort_t V1Max; UShort_t V2Min; UShort_t V2Max; UShort_t length_per_ch; UShort_t Trolley Command; UShort_t TIC_Stop; UShort_t TC_Start; UShort_t TD_Start; UShort_t TC_Stop; UShort_t Switch_RF; UShort_t PowerEnable; UShort_t RF_Enable; UShort_t Switch_Comm; UShort_t TIC_Start; UShort_t Cycle_Length; UShort_t Power_Control_1; UShort_t Power_Control_2; UShort_t trace_VMonitor1[TRLY_MONITOR_LENGTH]; UShort_t trace_VMonitor2[TRLY_MONITOR_LENGTH]; }; #define MAKE_MONITOR_STRING(len) HELPER_MONITOR_STRING(len) #define HELPER_MONITOR_STRING(len) \ const char * const trolley_monitor_str = "gps_clock_cycle_start/l:PMonitorVal/i:PMonitorTemp/i:RFPower1/i:RFPower2/i:"\ "NMRCheckSum/i:ConfigCheckSum/i:FrameCheckSum/i:NMRFrameSum/i:ConfigFrameSum/i:FrameSum/i:FrameIndex/i:StatusBits/s:"\ "TMonitorIn/s:TMonitorExt1/s:TMonitorExt2/s:TMonitorExt3/s:V1Min/s:V1Max/s:V2Min/s:V2Max/s:len_per_ch/s:"\ "Trolley Command/s:TIC_Stop/s:TC_Start/s:TD_Start/s:TC_Stop/s:Switch_RF/s:PowerEnable/s:RF_Enable/s:"\ "Switch_Comm/s:TIC_Start/s:Cycle_Length/s:Power_Control_1/s:Power_Control_2/s:"\ "trace_VMonitor1["#len"]/s:trace_VMonitor2["#len"]/s" MAKE_MONITOR_STRING(TRLY_MONITOR_LENGTH); //Galil Data structs struct galil_data_t{ ULong64_t TimeStamp; Int_t Tensions[2]; Int_t Positions[3]; Int_t Velocities[3]; Int_t OutputVs[3]; }; const char * const galil_data_str = "TimeStamp/l:Tensions[2]/I:Positions[3]/I:Velocities[3]/I:OutputVs[3]/I"; //This struct is auxiliary struct galil_data_d_t{ Double_t Tensions[2]; Double_t Positions[3]; Double_t Velocities[3]; Double_t OutputVs[3]; }; //Absolute probe data struct struct absolute_nmr_info_t{ ULong64_t time_stamp; UInt_t length; Int_t Pos[4]; //Coordinate X,Y,Z,S UShort_t flay_run_number; UShort_t probe_index; //Because the length of the trace varies too much, it is not included in this struct }; #define MAKE_ABSNMR_STRING() HELPER_ABSNMR_STRING() #define HELPER_ABSNMR_STRING() \ const char * const absolute_nmr_info_str = "time_stamp/l:length/i:Pos[4]/i:flay_run_number/s:probe_index/s" MAKE_ABSNMR_STRING(); // Absolute calibration NMR structs MAKE_NMR_STRUCT(abs_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRING(abs_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD); MAKE_NMR_STRUCT(abs_online_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); MAKE_NMR_STRING(abs_online_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE); //Surface coil struct struct surface_coil_t{ Double_t bot_sys_clock[SC_NUM_COILS]; Double_t top_sys_clock[SC_NUM_COILS]; Double_t bot_coil_currents[SC_NUM_COILS]; Double_t top_coil_currents[SC_NUM_COILS]; Double_t bot_coil_temps[SC_NUM_COILS]; Double_t top_coil_temps[SC_NUM_COILS]; }; #define MAKE_SC_STRING(name,num_coils) SC_HELPER(name,num_coils) #define SC_HELPER(name,num_coils)\ const char * const name = "sys_clock["#num_coils"]/D:bot_coil_currents["#num_coils"]/D:top_coil_currents["#num_coils"]/D:bot_coil_temps["#num_coils"]/D:top_coil_temps["#num_coils"]/D" MAKE_SC_STRING(sc_str,SC_NUM_COILS); // Yokogawa struct struct yokogawa_t{ ULong64_t sys_clock; // system clock ULong64_t gps_clock; // GPS clock Int_t mode; // device mode (0 = voltage, 1 = current) Int_t is_enabled; // is the output enabled (0 = false, 1 = true) Double_t current; // current setting (in mA) Double_t voltage; // voltage setting (in V) }; #define MAKE_YOKO_STRING() HELPER_YOKO_STRING() #define HELPER_YOKO_STRING() \ const char * const yokogawa_str = "sys_clock/l:gps_clock/l:is_enabled/i:current/D" MAKE_YOKO_STRING(); } // ::g2field #endif <|endoftext|>
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "GenericHDF5Format.h" #include <DataExchangeFormat.h> #include <DataSource.h> #include <Hdf5SubsampleWidget.h> #include <h5cpp/h5readwrite.h> #include <h5cpp/h5vtktypemaps.h> #include <QDialog> #include <QDialogButtonBox> #include <QInputDialog> #include <QStringList> #include <QVBoxLayout> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <string> #include <vector> #include <iostream> using std::cerr; using std::cout; using std::endl; namespace tomviz { template <typename T> void ReorderArrayC(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(i * dim[1] + j) * dim[2] + k] = in[(k * dim[1] + j) * dim[0] + i]; } } } } template <typename T> void ReorderArrayF(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(k * dim[1] + j) * dim[0] + i] = in[(i * dim[1] + j) * dim[2] + k]; } } } } bool GenericHDF5Format::addScalarArray(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image, const std::string& name) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); // Set up the stride and counts int stride = 1; size_t start[3], counts[3]; if (DataSource::wasSubsampled(image)) { // If the main image was subsampled, we need to use the same // subsampling for the scalars stride = DataSource::subsampleStride(image); int bs[6]; DataSource::subsampleVolumeBounds(image, bs); for (int i = 0; i < 3; ++i) { start[i] = static_cast<size_t>(bs[i * 2]); counts[i] = (bs[i * 2 + 1] - start[i]) / stride; } } else { for (int i = 0; i < 3; ++i) { start[i] = 0; counts[i] = dims[i]; } } // vtk requires the counts to be an int array int vtkCounts[3]; for (int i = 0; i < 3; ++i) vtkCounts[i] = counts[i]; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&vtkCounts[0]); tmp->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride, start, counts)) { std::cerr << "Failed to read the data\n"; return false; } auto* array = vtkAbstractArray::CreateArray(vtkDataType); array->SetNumberOfTuples(counts[0] * counts[1] * counts[2]); array->SetName(name.c_str()); image->GetPointData()->AddArray(array); // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = array->GetVoidPointer(0); switch (vtkDataType) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &vtkCounts[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image, const QVariantMap& options) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // This is the easiest way I could find to get the size of the type int size = vtkDataArray::GetDataTypeSize(vtkDataType); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); int bs[6] = { -1, -1, -1, -1, -1, -1 }; int stride = 1; if (options.contains("subsampleVolumeBounds")) { // Get the subsample volume bounds if the caller specified them QVariantList list = options["subsampleVolumeBounds"].toList(); for (int i = 0; i < list.size() && i < 6; ++i) bs[i] = list[i].toInt(); DataSource::setWasSubsampled(image, true); DataSource::setSubsampleVolumeBounds(image, bs); } else { // Set it to the defaults for (int i = 0; i < 3; ++i) { bs[i * 2] = 0; bs[i * 2 + 1] = dims[i]; } } if (options.contains("subsampleStride")) { // Get the stride if the caller specified it stride = options["subsampleStride"].toInt(); if (stride == 0) stride = 1; DataSource::setWasSubsampled(image, true); DataSource::setSubsampleStride(image, stride); } bool askForSubsample = false; if (options.contains("askForSubsample")) { // If the options specify whether to ask for a subsample, use that askForSubsample = options["askForSubsample"].toBool(); } else { // Otherwise, only ask for a subsample if the data looks large int subsampleDimOverride = 1200; if (options.contains("subsampleDimOverride")) subsampleDimOverride = options["subsampleDimOverride"].toInt(); askForSubsample = std::any_of(dims.cbegin(), dims.cend(), [subsampleDimOverride](int i) { return i >= subsampleDimOverride; }); } if (askForSubsample) { int dimensions[3] = { dims[0], dims[1], dims[2] }; QDialog dialog; dialog.setWindowTitle("Pick Subsample"); QVBoxLayout layout; dialog.setLayout(&layout); Hdf5SubsampleWidget widget(dimensions, size); layout.addWidget(&widget); if (DataSource::wasSubsampled(image)) { // If it was previously subsampled, start with the previous values widget.setStride(DataSource::subsampleStride(image)); DataSource::subsampleVolumeBounds(image, bs); widget.setBounds(bs); } QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); layout.addWidget(&buttons); QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); // Check if the user cancels if (!dialog.exec()) return false; widget.bounds(bs); stride = widget.stride(); DataSource::setWasSubsampled(image, true); DataSource::setSubsampleStride(image, stride); DataSource::setSubsampleVolumeBounds(image, bs); } // Do one final check to make sure none of the bounds are less than 0 if (std::any_of(std::begin(bs), std::end(bs), [](int i) { return i < 0; })) { // Set them to their defaults so we don't seg fault for (int i = 0; i < 3; ++i) { bs[i * 2] = 0; bs[i * 2 + 1] = dims[i]; } } // Set up the stride and counts size_t start[3] = { static_cast<size_t>(bs[0]), static_cast<size_t>(bs[2]), static_cast<size_t>(bs[4]) }; size_t counts[3]; for (size_t i = 0; i < 3; ++i) counts[i] = (bs[i * 2 + 1] - start[i]) / stride; // vtk requires the counts to be an int array int vtkCounts[3]; for (int i = 0; i < 3; ++i) vtkCounts[i] = counts[i]; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&vtkCounts[0]); tmp->AllocateScalars(vtkDataType, 1); image->SetDimensions(&vtkCounts[0]); image->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride, start, counts)) { std::cerr << "Failed to read the data\n"; return false; } // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0); switch (image->GetPointData()->GetScalars()->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &vtkCounts[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image, const QVariantMap& options) { using h5::H5ReadWrite; H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly; H5ReadWrite reader(fileName.c_str(), mode); // If /exchange/data is a dataset, assume this is a DataExchangeFormat if (reader.isDataSet("/exchange/data")) { reader.close(); DataExchangeFormat deFormat; return deFormat.read(fileName, image, options); } // Find all 3D datasets. If there is more than one, have the user choose. std::vector<std::string> datasets = reader.allDataSets(); for (auto it = datasets.begin(); it != datasets.end();) { // Remove all non-3D datasets std::vector<int> dims = reader.getDimensions(*it); if (dims.size() != 3) datasets.erase(it); else ++it; } if (datasets.empty()) { std::cerr << "No 3D datasets found in " << fileName.c_str() << "\n"; return false; } std::string dataNode = datasets[0]; if (datasets.size() != 1) { // If there is more than one dataset, have the user choose one QStringList items; for (auto& d : datasets) items.append(QString::fromStdString(d)); bool ok; QString res = QInputDialog::getItem( nullptr, "Choose volume", "Choose volume to load:", items, 0, false, &ok); // Check if user canceled if (!ok) return false; dataNode = datasets[items.indexOf(res)]; } return readVolume(reader, dataNode, image); } bool GenericHDF5Format::writeVolume(h5::H5ReadWrite& writer, const std::string& path, const std::string& name, vtkImageData* image) { int dim[3]; image->GetDimensions(dim); std::vector<int> dims({ dim[0], dim[1], dim[2] }); // We must allocate a new array, and copy the reordered array into it. auto arrayPtr = image->GetPointData()->GetScalars(); auto dataPtr = arrayPtr->GetVoidPointer(0); vtkNew<vtkImageData> reorderedImageData; reorderedImageData->SetDimensions(dim); reorderedImageData->AllocateScalars(arrayPtr->GetDataType(), 1); auto outPtr = reorderedImageData->GetPointData()->GetScalars()->GetVoidPointer(0); switch (arrayPtr->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayC(reinterpret_cast<VTK_TT*>(dataPtr), reinterpret_cast<VTK_TT*>(outPtr), dim)); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } h5::H5ReadWrite::DataType type = h5::H5VtkTypeMaps::VtkToDataType(arrayPtr->GetDataType()); return writer.writeData(path, name, dims, type, outPtr); } } // namespace tomviz <commit_msg>Added help button to HDF5 subsample widget<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "GenericHDF5Format.h" #include <DataExchangeFormat.h> #include <DataSource.h> #include <Hdf5SubsampleWidget.h> #include <Utilities.h> #include <h5cpp/h5readwrite.h> #include <h5cpp/h5vtktypemaps.h> #include <QDialog> #include <QDialogButtonBox> #include <QInputDialog> #include <QStringList> #include <QVBoxLayout> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <string> #include <vector> #include <iostream> using std::cerr; using std::cout; using std::endl; namespace tomviz { template <typename T> void ReorderArrayC(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(i * dim[1] + j) * dim[2] + k] = in[(k * dim[1] + j) * dim[0] + i]; } } } } template <typename T> void ReorderArrayF(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(k * dim[1] + j) * dim[0] + i] = in[(i * dim[1] + j) * dim[2] + k]; } } } } bool GenericHDF5Format::addScalarArray(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image, const std::string& name) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); // Set up the stride and counts int stride = 1; size_t start[3], counts[3]; if (DataSource::wasSubsampled(image)) { // If the main image was subsampled, we need to use the same // subsampling for the scalars stride = DataSource::subsampleStride(image); int bs[6]; DataSource::subsampleVolumeBounds(image, bs); for (int i = 0; i < 3; ++i) { start[i] = static_cast<size_t>(bs[i * 2]); counts[i] = (bs[i * 2 + 1] - start[i]) / stride; } } else { for (int i = 0; i < 3; ++i) { start[i] = 0; counts[i] = dims[i]; } } // vtk requires the counts to be an int array int vtkCounts[3]; for (int i = 0; i < 3; ++i) vtkCounts[i] = counts[i]; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&vtkCounts[0]); tmp->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride, start, counts)) { std::cerr << "Failed to read the data\n"; return false; } auto* array = vtkAbstractArray::CreateArray(vtkDataType); array->SetNumberOfTuples(counts[0] * counts[1] * counts[2]); array->SetName(name.c_str()); image->GetPointData()->AddArray(array); // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = array->GetVoidPointer(0); switch (vtkDataType) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &vtkCounts[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image, const QVariantMap& options) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // This is the easiest way I could find to get the size of the type int size = vtkDataArray::GetDataTypeSize(vtkDataType); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); int bs[6] = { -1, -1, -1, -1, -1, -1 }; int stride = 1; if (options.contains("subsampleVolumeBounds")) { // Get the subsample volume bounds if the caller specified them QVariantList list = options["subsampleVolumeBounds"].toList(); for (int i = 0; i < list.size() && i < 6; ++i) bs[i] = list[i].toInt(); DataSource::setWasSubsampled(image, true); DataSource::setSubsampleVolumeBounds(image, bs); } else { // Set it to the defaults for (int i = 0; i < 3; ++i) { bs[i * 2] = 0; bs[i * 2 + 1] = dims[i]; } } if (options.contains("subsampleStride")) { // Get the stride if the caller specified it stride = options["subsampleStride"].toInt(); if (stride == 0) stride = 1; DataSource::setWasSubsampled(image, true); DataSource::setSubsampleStride(image, stride); } bool askForSubsample = false; if (options.contains("askForSubsample")) { // If the options specify whether to ask for a subsample, use that askForSubsample = options["askForSubsample"].toBool(); } else { // Otherwise, only ask for a subsample if the data looks large int subsampleDimOverride = 1200; if (options.contains("subsampleDimOverride")) subsampleDimOverride = options["subsampleDimOverride"].toInt(); askForSubsample = std::any_of(dims.cbegin(), dims.cend(), [subsampleDimOverride](int i) { return i >= subsampleDimOverride; }); } if (askForSubsample) { int dimensions[3] = { dims[0], dims[1], dims[2] }; QDialog dialog; dialog.setWindowTitle("Pick Subsample"); QVBoxLayout layout; dialog.setLayout(&layout); Hdf5SubsampleWidget widget(dimensions, size); layout.addWidget(&widget); if (DataSource::wasSubsampled(image)) { // If it was previously subsampled, start with the previous values widget.setStride(DataSource::subsampleStride(image)); DataSource::subsampleVolumeBounds(image, bs); widget.setBounds(bs); } QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Help); layout.addWidget(&buttons); QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); QObject::connect(&buttons, &QDialogButtonBox::helpRequested, []() { QString link = "https://tomviz.readthedocs.io/en/latest/data/#hdf5-subsampling"; openUrl(link); }); // Check if the user cancels if (!dialog.exec()) return false; widget.bounds(bs); stride = widget.stride(); DataSource::setWasSubsampled(image, true); DataSource::setSubsampleStride(image, stride); DataSource::setSubsampleVolumeBounds(image, bs); } // Do one final check to make sure none of the bounds are less than 0 if (std::any_of(std::begin(bs), std::end(bs), [](int i) { return i < 0; })) { // Set them to their defaults so we don't seg fault for (int i = 0; i < 3; ++i) { bs[i * 2] = 0; bs[i * 2 + 1] = dims[i]; } } // Set up the stride and counts size_t start[3] = { static_cast<size_t>(bs[0]), static_cast<size_t>(bs[2]), static_cast<size_t>(bs[4]) }; size_t counts[3]; for (size_t i = 0; i < 3; ++i) counts[i] = (bs[i * 2 + 1] - start[i]) / stride; // vtk requires the counts to be an int array int vtkCounts[3]; for (int i = 0; i < 3; ++i) vtkCounts[i] = counts[i]; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&vtkCounts[0]); tmp->AllocateScalars(vtkDataType, 1); image->SetDimensions(&vtkCounts[0]); image->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride, start, counts)) { std::cerr << "Failed to read the data\n"; return false; } // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0); switch (image->GetPointData()->GetScalars()->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &vtkCounts[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image, const QVariantMap& options) { using h5::H5ReadWrite; H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly; H5ReadWrite reader(fileName.c_str(), mode); // If /exchange/data is a dataset, assume this is a DataExchangeFormat if (reader.isDataSet("/exchange/data")) { reader.close(); DataExchangeFormat deFormat; return deFormat.read(fileName, image, options); } // Find all 3D datasets. If there is more than one, have the user choose. std::vector<std::string> datasets = reader.allDataSets(); for (auto it = datasets.begin(); it != datasets.end();) { // Remove all non-3D datasets std::vector<int> dims = reader.getDimensions(*it); if (dims.size() != 3) datasets.erase(it); else ++it; } if (datasets.empty()) { std::cerr << "No 3D datasets found in " << fileName.c_str() << "\n"; return false; } std::string dataNode = datasets[0]; if (datasets.size() != 1) { // If there is more than one dataset, have the user choose one QStringList items; for (auto& d : datasets) items.append(QString::fromStdString(d)); bool ok; QString res = QInputDialog::getItem( nullptr, "Choose volume", "Choose volume to load:", items, 0, false, &ok); // Check if user canceled if (!ok) return false; dataNode = datasets[items.indexOf(res)]; } return readVolume(reader, dataNode, image); } bool GenericHDF5Format::writeVolume(h5::H5ReadWrite& writer, const std::string& path, const std::string& name, vtkImageData* image) { int dim[3]; image->GetDimensions(dim); std::vector<int> dims({ dim[0], dim[1], dim[2] }); // We must allocate a new array, and copy the reordered array into it. auto arrayPtr = image->GetPointData()->GetScalars(); auto dataPtr = arrayPtr->GetVoidPointer(0); vtkNew<vtkImageData> reorderedImageData; reorderedImageData->SetDimensions(dim); reorderedImageData->AllocateScalars(arrayPtr->GetDataType(), 1); auto outPtr = reorderedImageData->GetPointData()->GetScalars()->GetVoidPointer(0); switch (arrayPtr->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayC(reinterpret_cast<VTK_TT*>(dataPtr), reinterpret_cast<VTK_TT*>(outPtr), dim)); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } h5::H5ReadWrite::DataType type = h5::H5VtkTypeMaps::VtkToDataType(arrayPtr->GetDataType()); return writer.writeData(path, name, dims, type, outPtr); } } // namespace tomviz <|endoftext|>
<commit_before>/* Copyright (c) 2010-2015, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QFileInfo> #include <QDateTime> #include <QTextStream> #include "erbconverter.h" #include "erbparser.h" #include "viewconverter.h" #define VIEW_SOURCE_TEMPLATE \ "#include <QtCore>\n" \ "#include <TreeFrogView>\n" \ "%4" \ "\n" \ "class T_VIEW_EXPORT %1 : public TActionView\n" \ "{\n" \ " Q_OBJECT\n" \ "public:\n" \ " Q_INVOKABLE\n" \ " %1() : TActionView() { }\n" \ " %1(const %1 &) : TActionView() { }\n" \ " QString toString();\n" \ "};\n" \ "\n" \ "QString %1::toString()\n" \ "{\n" \ " responsebody.reserve(%3);\n" \ "%2\n" \ " return responsebody;\n" \ "}\n" \ "\n" \ "Q_DECLARE_METATYPE(%1)\n" \ "T_REGISTER_VIEW(%1)\n" \ "\n" \ "#include \"%1.moc\"\n" const QRegExp RxPartialTag("<%#partial[ \t]+\"([^\"]+)\"[ \t]*%>"); ErbConverter::ErbConverter(const QDir &output, const QDir &helpers, const QDir &partial) : outputDirectory(output), helpersDirectory(helpers), partialDirectory(partial) { } bool ErbConverter::convert(const QString &erbPath, int trimMode) const { QFile erbFile(erbPath); QString className = ViewConverter::getViewClassName(erbPath); QFile outFile(outputDirectory.filePath(className + ".cpp")); // Checks file's timestamp QFileInfo erbFileInfo(erbFile); QFileInfo outFileInfo(outFile); if (!erbFile.open(QIODevice::ReadOnly)) { qCritical("failed to read template.erb file : %s", qPrintable(erbFile.fileName())); return false; } QString erbSrc = QTextStream(&erbFile).readAll(); auto partialList = replacePartialTag(erbSrc, 0); QDateTime latestPartialTs; for (const auto &file : partialList) { auto ts = QFileInfo(partialDirectory.filePath(file)).lastModified(); if (ts.isValid() && ts > latestPartialTs) { latestPartialTs = ts; } } // Checks timestamps if (outFileInfo.exists()) { if ((latestPartialTs.isValid() && latestPartialTs >= outFileInfo.lastModified()) || erbFileInfo.lastModified() >= outFileInfo.lastModified()) { if (outFile.remove()) { printf(" removed %s\n", qPrintable(outFile.fileName())); } } else { //printf(" done %s\n", qPrintable(outFile.fileName())); return true; } } if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qCritical("failed to create file"); return false; } ErbParser parser((ErbParser::TrimMode)trimMode); parser.parse(erbSrc); QString code = parser.sourceCode(); QTextStream ts(&outFile); ts << QString(VIEW_SOURCE_TEMPLATE).arg(className, code, QString::number(code.size()), generateIncludeCode(parser)); if (ts.status() == QTextStream::Ok) { printf(" created %s (trim:%d)\n", qPrintable(outFile.fileName()), trimMode); } return true; } bool ErbConverter::convert(const QString &className, const QString &erb, int trimMode) const { QFile outFile(outputDirectory.filePath(className + ".cpp")); if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qCritical("failed to create file"); return false; } ErbParser parser((ErbParser::TrimMode)trimMode); parser.parse(erb); QString code = parser.sourceCode(); QTextStream ts(&outFile); ts << QString(VIEW_SOURCE_TEMPLATE).arg(className, code, QString::number(code.size()), generateIncludeCode(parser)); if (ts.status() == QTextStream::Ok) { printf(" created %s (trim:%d)\n", qPrintable(outFile.fileName()), trimMode); } return true; } QString ErbConverter::escapeNewline(const QString &string) { QString str; str.reserve(string.length() * 1.1); for (auto &s : string) { if (s == QLatin1Char('\\')) { str += QLatin1String("\\\\"); } else if (s == QLatin1Char('\n')) { str += QLatin1String("\\n"); } else if (s == QLatin1Char('\r')) { str += QLatin1String("\\r"); } else if (s == QLatin1Char('"')) { str += QLatin1String("\\\""); } else { str += s; } } return str; } QString ErbConverter::generateIncludeCode(const ErbParser &parser) const { QString code = parser.includeCode(); QStringList filter; filter << "*.h" << "*.hh" << "*.hpp" << "*.hxx"; foreach (QString f, helpersDirectory.entryList(filter, QDir::Files)) { code += "#include \""; code += f; code += "\"\n"; } return code; } QStringList ErbConverter::replacePartialTag(QString &erbSrc, int depth) const { QStringList ret; // partial files replaced QString erbReplaced; int pos = 0; while (pos < erbSrc.length()) { int idx; if ((idx = RxPartialTag.indexIn(erbSrc, pos)) < 0) { erbReplaced += erbSrc.mid(pos); break; } QString partialFile = RxPartialTag.cap(1); if (QFileInfo(partialFile).suffix().toLower() != "erb") { partialFile += ".erb"; } if (depth > 10) { // no more replace qWarning("Partial template '%s' infinitely recursively included?", partialFile.toLocal8Bit().data()); return ret; } erbReplaced += erbSrc.mid(pos, idx - pos); pos = idx + RxPartialTag.matchedLength(); // Includes the partial QFile partErb(partialDirectory.filePath(partialFile)); if (partErb.open(QIODevice::ReadOnly)) { ret << partialFile; QString part = QTextStream(&partErb).readAll(); ret << replacePartialTag(part, depth + 1); } } erbSrc = erbReplaced; ret.removeDuplicates(); return ret; } <commit_msg>fix a bug of tmake.<commit_after>/* Copyright (c) 2010-2015, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QFileInfo> #include <QDateTime> #include <QTextStream> #include "erbconverter.h" #include "erbparser.h" #include "viewconverter.h" #define VIEW_SOURCE_TEMPLATE \ "#include <QtCore>\n" \ "#include <TreeFrogView>\n" \ "%4" \ "\n" \ "class T_VIEW_EXPORT %1 : public TActionView\n" \ "{\n" \ " Q_OBJECT\n" \ "public:\n" \ " Q_INVOKABLE\n" \ " %1() : TActionView() { }\n" \ " %1(const %1 &) : TActionView() { }\n" \ " QString toString();\n" \ "};\n" \ "\n" \ "QString %1::toString()\n" \ "{\n" \ " responsebody.reserve(%3);\n" \ "%2\n" \ " return responsebody;\n" \ "}\n" \ "\n" \ "Q_DECLARE_METATYPE(%1)\n" \ "T_REGISTER_VIEW(%1)\n" \ "\n" \ "#include \"%1.moc\"\n" const QRegExp RxPartialTag("<%#partial[ \t]+\"([^\"]+)\"[ \t]*%>"); ErbConverter::ErbConverter(const QDir &output, const QDir &helpers, const QDir &partial) : outputDirectory(output), helpersDirectory(helpers), partialDirectory(partial) { } bool ErbConverter::convert(const QString &erbPath, int trimMode) const { QFile erbFile(erbPath); QString className = ViewConverter::getViewClassName(erbPath); QFile outFile(outputDirectory.filePath(className + ".cpp")); // Checks file's timestamp QFileInfo erbFileInfo(erbFile); QFileInfo outFileInfo(outFile); if (!erbFile.open(QIODevice::ReadOnly)) { qCritical("failed to read template.erb file : %s", qPrintable(erbFile.fileName())); return false; } QString erbSrc = QTextStream(&erbFile).readAll(); auto partialList = replacePartialTag(erbSrc, 0); QDateTime latestPartialTs; for (const auto &file : partialList) { auto ts = QFileInfo(partialDirectory.filePath(file)).lastModified(); if (ts.isValid() && ts > latestPartialTs) { latestPartialTs = ts; } } // Checks timestamps if (outFileInfo.exists()) { if ((latestPartialTs.isValid() && latestPartialTs >= outFileInfo.lastModified()) || erbFileInfo.lastModified() >= outFileInfo.lastModified()) { if (outFile.remove()) { printf(" removed %s\n", qPrintable(outFile.fileName())); } } else { //printf(" done %s\n", qPrintable(outFile.fileName())); return true; } } if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qCritical("failed to create file"); return false; } ErbParser parser((ErbParser::TrimMode)trimMode); parser.parse(erbSrc); QString code = parser.sourceCode(); QTextStream ts(&outFile); ts << QString(VIEW_SOURCE_TEMPLATE).arg(className, code, QString::number(code.size()), generateIncludeCode(parser)); if (ts.status() == QTextStream::Ok) { printf(" created %s (trim:%d)\n", qPrintable(outFile.fileName()), trimMode); } return true; } bool ErbConverter::convert(const QString &className, const QString &erb, int trimMode) const { QFile outFile(outputDirectory.filePath(className + ".cpp")); if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qCritical("failed to create file"); return false; } ErbParser parser((ErbParser::TrimMode)trimMode); parser.parse(erb); QString code = parser.sourceCode(); QTextStream ts(&outFile); ts << QString(VIEW_SOURCE_TEMPLATE).arg(className, code, QString::number(code.size()), generateIncludeCode(parser)); if (ts.status() == QTextStream::Ok) { printf(" created %s (trim:%d)\n", qPrintable(outFile.fileName()), trimMode); } return true; } QString ErbConverter::escapeNewline(const QString &string) { QString str; str.reserve(string.length() * 1.1); for (auto &s : string) { if (s == QLatin1Char('\\')) { str += QLatin1String("\\\\"); } else if (s == QLatin1Char('\n')) { str += QLatin1String("\\n"); } else if (s == QLatin1Char('\r')) { str += QLatin1String("\\r"); } else if (s == QLatin1Char('"')) { str += QLatin1String("\\\""); } else { str += s; } } return str; } QString ErbConverter::generateIncludeCode(const ErbParser &parser) const { QString code = parser.includeCode(); QStringList filter; filter << "*.h" << "*.hh" << "*.hpp" << "*.hxx"; foreach (QString f, helpersDirectory.entryList(filter, QDir::Files)) { code += "#include \""; code += f; code += "\"\n"; } return code; } QStringList ErbConverter::replacePartialTag(QString &erbSrc, int depth) const { QStringList ret; // partial files replaced QString erbReplaced; int pos = 0; while (pos < erbSrc.length()) { int idx; if ((idx = RxPartialTag.indexIn(erbSrc, pos)) < 0) { erbReplaced += erbSrc.mid(pos); break; } QString partialFile = RxPartialTag.cap(1); if (QFileInfo(partialFile).suffix().toLower() != "erb") { partialFile += ".erb"; } if (depth > 10) { // no more replace qWarning("Partial template '%s' infinitely recursively included?", partialFile.toLocal8Bit().data()); return ret; } erbReplaced += erbSrc.mid(pos, idx - pos); pos = idx + RxPartialTag.matchedLength(); // Includes the partial QFile partErb(partialDirectory.filePath(partialFile)); if (partErb.open(QIODevice::ReadOnly)) { ret << partialFile; QString part = QTextStream(&partErb).readAll(); ret << replacePartialTag(part, depth + 1); erbReplaced += part; } } erbSrc = erbReplaced; ret.removeDuplicates(); return ret; } <|endoftext|>
<commit_before>// clang -std=c++17 -lstdc++ prod.cpp -o prod && ./prod #include <iostream> #include <functional> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> using namespace std; template<typename T> void print(vector<T>& vec) { for(int i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; } cout << endl; } template<typename S> class Source : public std::enable_shared_from_this<Source<S>> { public: virtual ~Source() {} virtual bool operator()(S& output) = 0; bool next(S& output) { return (*this)(output); } shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); } }; template<typename S> class Gen : public Source<S> { public: int state; bool isAlive; Gen() : state(0), isAlive(true) {} virtual bool step(S& output) = 0; bool operator()(S& output) { while(!step(output)); return isAlive; } }; #define GEN_BEG \ switch(state) { \ case BEG: {} #define GEN_END \ default: { isAlive = false; return true; } } #define BEG(name) BEG_##name #define ELSE(name) ELSE_##name #define END(name) END_##name #define IF(name,c,a,b) \ case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \ case ELSE(name): { b; } \ case END(name): { state = END(name); } #define LOOP(name,s) \ case BEG(name): { {s;} state = BEG(name); return false; } \ case END(name): { state = END(name); } #define WHILE(name,c,s) \ case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \ case END(name): { state = END(name); } #define YIELD(name) \ case BEG(name): { state = END(name); isAlive = true; return true; } \ case END(name): {} #define BREAK(loop) { state = END(loop); return false; } #define DEC_BEG enum { BEG, #define DEC_IF(name) BEG(name), ELSE(name), END(name) #define DEC_LOOP(name) BEG(name), END(name) #define DEC_YIELD(name) BEG(name), END(name) #define DEC_END }; /* L: def prod_iter(s): 0: if len(s) == 0: 1: yield [] 2: else: 3: x = 0 4: while true: 5: xs = [] 6: iter = generator.create(prod_iter(s[1:])) 7: while true: 8: xs, isAlive = iter.resume() 9: if !isAlive: 10 break 11 yield [x] + xs 12 x += 1 13 if x >= s[0]: 14 break -1 return */ class OneMoreProdGen : public Gen<vector<int> > { public: vector<unsigned int> s; int x; shared_ptr<Source<vector<int> > > iter; vector<int> xs; OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {} bool step(vector<int>& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_IF(if3), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG IF(if1, s.size()==0, { output.clear(); YIELD(y1); }, { x = 0; WHILE(loop1, true, { IF(if3, x >= s[0], BREAK(loop1), {}); { vector<unsigned int> ss(s.begin() + 1, s.end()); iter = make_shared<OneMoreProdGen>(ss); } WHILE(loop2, iter->next(xs), { output.clear(); output.push_back(x); output.insert(output.end(), xs.begin(), xs.end()); YIELD(y2); }); x += 1; }) }); GEN_END } }; /* def hanoi(n, a, b, c): if n == 1: s = str(a) + ' --> ' + str(c) yield s else: for s in hanoi(n - 1, a, c, b): yield s for s in hanoi(1 , a, b, c): yield s for s in hanoi(n - 1, b, a, c): yield s */ class OneMoreHanoiGen : public Gen<string> { public: int n; string a, b, c; shared_ptr<Gen<string> > iter; OneMoreHanoiGen(int _n, string _a, string _b, string _c) : n(_n), a(_a), b(_b), c(_c) {} bool step(string& output) { DEC_BEG DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3), DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4) DEC_END GEN_BEG IF(if1, n == 1, { output = a + " --> " + c; YIELD(y1); }, { iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b); WHILE(loop1, iter->next(output), YIELD(y2)); iter = make_shared<OneMoreHanoiGen>(1, a, b, c); WHILE(loop2, iter->next(output), YIELD(y3)); iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c); WHILE(loop3, iter->next(output), YIELD(y4)); }); GEN_END } }; int main() { cout << "HanoiGen" << endl; string s; OneMoreHanoiGen hanoiGen(3, "A", "B", "C"); while(hanoiGen(s)) cout << s << endl; cout << "CartesianProduct" << endl; vector<unsigned int> dimSize({2,3,4}); vector<int> output(dimSize.size()); OneMoreProdGen prodGen(dimSize); while(prodGen(output)) print(output); return 0; } <commit_msg>Update macro_yield.cpp<commit_after>// clang -std=c++17 -lstdc++ prod.cpp -o prod && ./prod #include <iostream> #include <functional> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> using namespace std; template<typename T> void print(vector<T>& vec) { for(int i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; } cout << endl; } template<typename S> class Source : public std::enable_shared_from_this<Source<S>> { public: virtual ~Source() {} virtual bool operator()(S& output) = 0; bool next(S& output) { return (*this)(output); } shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); } }; template<typename S> class Gen : public Source<S> { public: int state; bool isAlive; Gen() : state(0), isAlive(true) {} virtual bool step(S& output) = 0; bool operator()(S& output) { while(!step(output)); return isAlive; } }; #define GEN_BEG \ switch(state) { \ case BEG: {} #define GEN_END \ default: { isAlive = false; return true; } } #define BEG(name) BEG_##name #define ELSE(name) ELSE_##name #define END(name) END_##name #define IF(name,c,a,b) \ case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \ case ELSE(name): { b; } \ case END(name): {} #define LOOP(name,s) \ case BEG(name): { {s;} state = BEG(name); return false; } \ case END(name): {} #define WHILE(name,c,s) \ case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \ case END(name): {} #define YIELD(name) \ case BEG(name): { state = END(name); isAlive = true; return true; } \ case END(name): {} #define CONTINUE(loop) { state = BEG(loop); return false; } #define BREAK(loop) { state = END(loop); return false; } #define GOTO(label) { state = label; return false; } #define DEC_BEG enum { BEG = 0, #define DEC_IF(name) BEG(name), ELSE(name), END(name) #define DEC_LOOP(name) BEG(name), END(name) #define DEC_YIELD(name) BEG(name), END(name) #define DEC_END }; /* L: def prod_iter(s): 0: if len(s) == 0: 1: yield [] 2: else: 3: x = 0 4: while true: 5: xs = [] 6: iter = generator.create(prod_iter(s[1:])) 7: while true: 8: xs, isAlive = iter.resume() 9: if !isAlive: 10 break 11 yield [x] + xs 12 x += 1 13 if x >= s[0]: 14 break -1 return */ class OneMoreProdGen : public Gen<vector<int> > { public: vector<unsigned int> s; int x; shared_ptr<Source<vector<int> > > iter; vector<int> xs; OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {} bool step(vector<int>& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_IF(if3), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1), DEC_YIELD(y2) DEC_END GEN_BEG IF(if1, s.size()==0, { output.clear(); YIELD(y1); }, { x = 0; WHILE(loop1, true, { IF(if3, x >= s[0], BREAK(loop1), {}); { vector<unsigned int> ss(s.begin() + 1, s.end()); iter = make_shared<OneMoreProdGen>(ss); } WHILE(loop2, iter->next(xs), { output.clear(); output.push_back(x); output.insert(output.end(), xs.begin(), xs.end()); YIELD(y2); }); x += 1; }) }); GEN_END } }; /* def hanoi(n, a, b, c): if n == 1: s = str(a) + ' --> ' + str(c) yield s else: for s in hanoi(n - 1, a, c, b): yield s for s in hanoi(1 , a, b, c): yield s for s in hanoi(n - 1, b, a, c): yield s */ class OneMoreHanoiGen : public Gen<string> { public: int n; string a, b, c; shared_ptr<Gen<string> > iter; OneMoreHanoiGen(int _n, string _a, string _b, string _c): n(_n), a(_a), b(_b), c(_c) {} bool step(string& output) { DEC_BEG DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3), DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4) DEC_END GEN_BEG IF(if1, n == 1, { output = a + " --> " + c; YIELD(y1); }, { iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b); WHILE(loop1, iter->next(output), YIELD(y2)); iter = make_shared<OneMoreHanoiGen>(1, a, b, c); WHILE(loop2, iter->next(output), YIELD(y3)); iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c); WHILE(loop3, iter->next(output), YIELD(y4)); }); GEN_END } }; class PrimeGen : public Gen<int> { public: vector<int> primes; int i, j; PrimeGen() {} bool step(int& output) { DEC_BEG DEC_IF(if1), DEC_IF(if2), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_YIELD(y1) DEC_END GEN_BEG i = 2; WHILE(loop1, true, { j = 0; WHILE(loop2, j < primes.size(), { IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++); }); primes.push_back(i); output = i; YIELD(y1); }); GEN_END } }; int main() { cout << "HanoiGen" << endl; string s; OneMoreHanoiGen hanoiGen(3, "A", "B", "C"); while(hanoiGen(s)) cout << s << endl; cout << "CartesianProduct" << endl; vector<unsigned int> dimSize({2,3,4}); vector<int> output(dimSize.size()); OneMoreProdGen prodGen(dimSize); while(prodGen(output)) print(output); cout << "Prime numbers" << endl; PrimeGen primeGen; int p; for(int i = 0; i < 30; ++i) { primeGen(p); cout << p << " "; } cout << endl; return 0; } <|endoftext|>
<commit_before>#include <coffee/CCore> #include <coffee/asio/include/rest-client.h> using namespace Coffee; int32 coffee_main(int32, byte_t**) { RestClient::InitService(); RestClient::RestResponse t = RestClient::RestRequest(RestClient::HTTP, "tmi.twitch.tv", "/group/user/esl/chatters"); cDebug("Status: {0}",t.status); fprintf(stderr,"Header: \n%s\n",t.header.c_str()); cDebug("Message: {0}",t.message); cDebug("Payload: {0}",t.payload); return 0; } COFFEE_APPLICATION_MAIN(coffee_main) <commit_msg> - Print header again<commit_after>#include <coffee/CCore> #include <coffee/asio/include/rest-client.h> using namespace Coffee; int32 coffee_main(int32, byte_t**) { RestClient::InitService(); RestClient::RestResponse t = RestClient::RestRequest(RestClient::HTTP, "tmi.twitch.tv", "/group/user/esl/chatters"); cDebug("Status: {0}",t.status); cDebug("Header: {0}",t.header); cDebug("Message: {0}",t.message); cDebug("Payload: {0}",t.payload); return 0; } COFFEE_APPLICATION_MAIN(coffee_main) <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiChannelExtractROI.h" #include "otbExtractROI.h" #include "otbStreamingStatisticsImageFilter.h" #include "otbSystem.h" #include "itkChangeLabelImageFilter.h" #include "otbTileImageFilter.h" #include <time.h> #include <vcl_algorithm.h> #include <climits> #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbStandardWriterWatcher.h" namespace otb { namespace Wrapper { class LSMSMerging : public Application { public: typedef LSMSMerging Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef FloatVectorImageType ImageType; typedef ImageType::InternalPixelType ImagePixelType; typedef UInt32ImageType LabelImageType; typedef LabelImageType::InternalPixelType LabelImagePixelType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType; typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType; typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType; typedef otb::ExtractROI<LabelImagePixelType,LabelImagePixelType> ExtractROIFilterType; typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType; typedef itk::ImageRegionConstIterator<LabelImageType> LabelImageIterator; typedef itk::ImageRegionConstIterator<ImageType> ImageIterator; typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType> ChangeLabelImageFilterType; typedef otb::TileImageFilter<LabelImageType> TileImageFilterType; itkNewMacro(Self); itkTypeMacro(Merging, otb::Application); private: ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter; void DoInit() { SetName("LSMSMerging"); SetDescription("Performs the small region pruning by merging of a segmentation."); SetDocName("Merging"); SetDocLongDescription("This application performs the small region pruning by merging of a segmentation. Regions are merged by increasing sizes, starting with regions of size 1, until regions of the minimal acceptable size."); SetDocLimitations(""); SetDocAuthors("David Youssefi"); SetDocSeeAlso(" "); AddDocTag(Tags::Segmentation); AddParameter(ParameterType_InputImage, "in", "Input image"); SetParameterDescription( "in", "The input image." ); AddParameter(ParameterType_InputImage, "seg", "Segmented image"); SetParameterDescription( "seg", " The segmented image input. Segmented image input is the segmentation of the input image." ); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "The output image. The output image is the input image where the minimal regions have been merged." ); AddParameter(ParameterType_Int, "minsize", "Minimum Region Size"); SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is merged with the \"nearest\" region (radiometrically)."); SetDefaultParameterInt("minsize", 50); SetMinimumParameterIntValue("minsize", 0); MandatoryOff("minsize"); AddParameter(ParameterType_Int, "nbtilesx", "Number of Tiles (X-axis)"); SetParameterDescription("nbtilesx", "Number of Tiles along the X-axis."); SetDefaultParameterInt("nbtilesx", 10); SetMinimumParameterIntValue("nbtilesx", 1); MandatoryOff("nbtilesx"); AddParameter(ParameterType_Int, "nbtilesy", "Number of Tiles (Y-axis)"); SetParameterDescription("nbtilesy", "Number of Tiles along the Y-axis."); SetDefaultParameterInt("nbtilesy", 10); SetMinimumParameterIntValue("nbtilesy", 1); MandatoryOff("nbtilesy"); // Doc example parameter settings SetDocExampleParameterValue("in","smooth.tif"); SetDocExampleParameterValue("seg","segmentation.tif"); SetDocExampleParameterValue("out","merged.tif"); SetDocExampleParameterValue("minsize","20"); SetDocExampleParameterValue("nbtilesx","4"); SetDocExampleParameterValue("nbtilesy","4"); } void DoUpdateParameters() { } void DoExecute() { clock_t tic = clock(); unsigned int minSize = GetParameterInt("minsize"); unsigned int nbTilesX = GetParameterInt("nbtilesx"); unsigned int nbTilesY = GetParameterInt("nbtilesy"); //Acquisition of the input image dimensions ImageType::Pointer imageIn = GetParameterImage("in"); imageIn->UpdateOutputInformation(); unsigned long sizeImageX = imageIn->GetLargestPossibleRegion().GetSize()[0], sizeImageY = imageIn->GetLargestPossibleRegion().GetSize()[1]; unsigned int numberOfComponentsPerPixel = imageIn->GetNumberOfComponentsPerPixel(); LabelImageType::Pointer labelIn = GetParameterUInt32Image("seg"); StatisticsImageFilterType::Pointer stats = StatisticsImageFilterType::New(); stats->SetInput(labelIn); stats->Update(); unsigned int regionCount=stats->GetMaximum(); std::vector<unsigned int>nbPixels; nbPixels.clear(); nbPixels.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) nbPixels[curLabel] = 0; ImageType::PixelType defaultValue(numberOfComponentsPerPixel); defaultValue.Fill(0); std::vector<ImageType::PixelType>sum(regionCount+1,defaultValue); //Sums calculation per label otbAppLogINFO(<<"Sums calculation ..."); unsigned long sizeTilesX = (sizeImageX+nbTilesX-1)/nbTilesX; unsigned long sizeTilesY = (sizeImageY+nbTilesY-1)/nbTilesY; for(unsigned int row = 0; row < nbTilesY ; row++) for(unsigned int column = 0; column < nbTilesX ; column++) { unsigned long startX = column*sizeTilesX; unsigned long startY = row*sizeTilesY; unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX); unsigned long sizeY = vcl_min(sizeTilesY,sizeImageY-startY); //Tiles extraction of the input image MultiChannelExtractROIFilterType::Pointer imageROI = MultiChannelExtractROIFilterType::New(); imageROI->SetInput(imageIn); imageROI->SetStartX(startX); imageROI->SetStartY(startY); imageROI->SetSizeX(sizeX); imageROI->SetSizeY(sizeY); imageROI->Update(); //Tiles extraction of the segmented image ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New(); labelImageROI->SetInput(labelIn); labelImageROI->SetStartX(startX); labelImageROI->SetStartY(startY); labelImageROI->SetSizeX(sizeX); labelImageROI->SetSizeY(sizeY); labelImageROI->Update(); //Sums calculation for the mean calculation per label LabelImageIterator itLabel( labelImageROI->GetOutput(), labelImageROI->GetOutput()->GetLargestPossibleRegion()); ImageIterator itImage( imageROI->GetOutput(), imageROI->GetOutput()->GetLargestPossibleRegion()); for (itLabel.GoToBegin(), itImage.GoToBegin(); !itLabel.IsAtEnd(); ++itLabel, ++itImage) { nbPixels[itLabel.Value()]++; for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { sum[itLabel.Value()][comp]+=itImage.Get()[comp]; } } } //LUT creation for the final relabelling std::vector<LabelImagePixelType> LUT; LUT.clear(); LUT.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) { LUT[curLabel] = curLabel; } //Minimal size region suppression otbAppLogINFO(<<"Building LUT for small regions merging ..."); for (unsigned int size=1;size<minSize;size++) { // LUTtmp creation in order to modify the LUT only at the end of the pass std::vector<LabelImagePixelType> LUTtmp; LUTtmp.clear(); LUTtmp.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) { LUTtmp[curLabel] = LUT[curLabel]; } for(unsigned int row = 0; row < nbTilesY ; row++) { for(unsigned int column = 0; column < nbTilesX ; column++) { std::set<int> minLabel, edgeLabel, labelMerged; std::map<int,std::set<int> > adjMap; unsigned long startX = column*sizeTilesX, startY = row*sizeTilesY; unsigned long sizeX = vcl_min(sizeTilesX+size+1,sizeImageX-startX), sizeY = vcl_min(sizeTilesY+size+1,sizeImageY-startY); ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New(); labelImageROI->SetInput(labelIn); labelImageROI->SetStartX(startX); labelImageROI->SetStartY(startY); labelImageROI->SetSizeX(sizeX); labelImageROI->SetSizeY(sizeY); labelImageROI->Update(); LabelImageType::IndexType pixelIndex; //"Adjacency map" creation for the region with nbPixels=="size" for(pixelIndex[0]=0;pixelIndex[0]<static_cast<long>(sizeX);++pixelIndex[0]) for(pixelIndex[1]=0;pixelIndex[1]<static_cast<long>(sizeY);++pixelIndex[1]) { LabelImagePixelType curLabel = labelImageROI->GetOutput()->GetPixel(pixelIndex); if(labelMerged.count(LUT[curLabel])) { edgeLabel.insert(LUT[curLabel]); } if((pixelIndex[0]==0)&&(startX!=0)) { edgeLabel.insert(LUT[curLabel]); } if((pixelIndex[1]==0)&&(startY!=0)) { edgeLabel.insert(LUT[curLabel]); } if(pixelIndex[0]==static_cast<long>(sizeX)-1) { if(startX!=(nbTilesX-1)*sizeTilesX) edgeLabel.insert(LUT[curLabel]); } else { ++pixelIndex[0]; LabelImagePixelType adjLabelX = labelImageROI->GetOutput()->GetPixel(pixelIndex); --pixelIndex[0]; if(LUT[adjLabelX]!=LUT[curLabel]) { if((nbPixels[LUT[curLabel]]>0)&&(nbPixels[LUT[curLabel]]==size)) { adjMap[LUT[curLabel]].insert(LUT[adjLabelX]); minLabel.insert(LUT[curLabel]); } if((nbPixels[LUT[adjLabelX]]>0)&&(nbPixels[LUT[adjLabelX]]==size)) { adjMap[LUT[adjLabelX]].insert(LUT[curLabel]); minLabel.insert(LUT[adjLabelX]); } } } if(pixelIndex[1]==static_cast<long>(sizeY)-1) { if(startY!=(nbTilesY-1)*sizeTilesY) edgeLabel.insert(LUT[curLabel]); } else { ++pixelIndex[1]; LabelImagePixelType adjLabelY = labelImageROI->GetOutput()->GetPixel(pixelIndex); --pixelIndex[1]; if(LUT[adjLabelY]!=LUT[curLabel]) { if((nbPixels[LUT[curLabel]]>0)&&(nbPixels[LUT[curLabel]]==size)) { adjMap[LUT[curLabel]].insert(LUT[adjLabelY]); minLabel.insert(LUT[curLabel]); } if((nbPixels[LUT[adjLabelY]]>0)&&(nbPixels[LUT[adjLabelY]]==size)) { adjMap[LUT[adjLabelY]].insert(LUT[curLabel]); minLabel.insert(LUT[adjLabelY]);} } } } //Searching the "nearest" region for(std::set<int>::iterator itMinLabel=minLabel.begin(); itMinLabel!=minLabel.end(); ++itMinLabel) { LabelImagePixelType curLabel = *itMinLabel, adjLabel; double err = itk::NumericTraits<double>::max(); if(edgeLabel.count(curLabel)==0) { if(nbPixels[curLabel]==size) { edgeLabel.insert(curLabel); for(std::set<int>::iterator itAdjLabel=adjMap[curLabel].begin(); itAdjLabel!=adjMap[curLabel].end(); ++itAdjLabel) { double tmpError = 0; LabelImagePixelType tmpLabel = *itAdjLabel; if(tmpLabel!=curLabel) { for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { double curComp = static_cast<double>(sum[curLabel][comp])/nbPixels[curLabel]; int tmpComp = static_cast<double>(sum[tmpLabel][comp])/nbPixels[tmpLabel]; tmpError += (curComp-tmpComp)*(curComp-tmpComp); } if(tmpError<err) { err = tmpError; adjLabel = tmpLabel; } } } //Fusion of the two regions if(adjLabel!=curLabel) { unsigned int curLabelLUT = curLabel, adjLabelLUT = adjLabel; while(LUTtmp[curLabelLUT] != curLabelLUT) { curLabelLUT = LUTtmp[curLabelLUT]; } while(LUTtmp[adjLabelLUT] != adjLabelLUT) { adjLabelLUT = LUTtmp[adjLabelLUT]; } if(curLabelLUT < adjLabelLUT) { LUTtmp[adjLabelLUT] = curLabelLUT; } else { LUTtmp[LUTtmp[curLabelLUT]] = adjLabelLUT; LUTtmp[curLabelLUT] = adjLabelLUT; } } } } } for(LabelImagePixelType label = 1; label < regionCount+1; ++label) { LabelImagePixelType can = label; while(LUTtmp[can] != can) { can = LUTtmp[can]; } LUTtmp[label] = can; } } } for(LabelImagePixelType label = 1; label < regionCount+1; ++label) { LUT[label]=LUTtmp[label]; if((nbPixels[label]!=0)&&(LUT[label]!=label)) { nbPixels[LUT[label]]+=nbPixels[label]; nbPixels[label]=0; for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { sum[LUT[label]][comp]+=sum[label][comp]; } } } } //Relabelling m_ChangeLabelFilter = ChangeLabelImageFilterType::New(); m_ChangeLabelFilter->SetInput(labelIn); for(LabelImagePixelType label = 1;label<regionCount+1; ++label) { if(label!=LUT[label]) { m_ChangeLabelFilter->SetChange(label,LUT[label]); } } SetParameterOutputImage("out", m_ChangeLabelFilter->GetOutput()); clock_t toc = clock(); otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds"); } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSMerging) <commit_msg>LSMS integration (more doc on merging app)<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiChannelExtractROI.h" #include "otbExtractROI.h" #include "otbStreamingStatisticsImageFilter.h" #include "otbSystem.h" #include "itkChangeLabelImageFilter.h" #include "otbTileImageFilter.h" #include <time.h> #include <vcl_algorithm.h> #include <climits> #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbStandardWriterWatcher.h" namespace otb { namespace Wrapper { class LSMSMerging : public Application { public: typedef LSMSMerging Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef FloatVectorImageType ImageType; typedef ImageType::InternalPixelType ImagePixelType; typedef UInt32ImageType LabelImageType; typedef LabelImageType::InternalPixelType LabelImagePixelType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType; typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType; typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType; typedef otb::ExtractROI<LabelImagePixelType,LabelImagePixelType> ExtractROIFilterType; typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType; typedef itk::ImageRegionConstIterator<LabelImageType> LabelImageIterator; typedef itk::ImageRegionConstIterator<ImageType> ImageIterator; typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType> ChangeLabelImageFilterType; typedef otb::TileImageFilter<LabelImageType> TileImageFilterType; itkNewMacro(Self); itkTypeMacro(Merging, otb::Application); private: ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter; void DoInit() { SetName("LSMSSmallRegionMerging"); SetDescription("Third (optional) step of the exact Large-Scale Mean-Shift segmentation workflow."); SetDocName("Exact Large-Scale Mean-Shift segmentation, step 3 (optional)"); SetDocLongDescription("This application performs the second step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image) and the original image, it will merge regions whose size in pixels is lower than minsize parameter with the adjacent regions with the adjacent region with closest radiometry and acceptable size. Small regions will be processed by size: first all regions of size 1 will be merged, then all regions of size 2, until regions of size minsize. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results."); SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose."); SetDocAuthors("David Youssefi"); SetDocSeeAlso("LSMSSegmentation, LSMSVectorization, MeanShiftSmoothing"); AddDocTag(Tags::Segmentation); AddDocTag("LSMS"); AddParameter(ParameterType_InputImage, "in", "Input image"); SetParameterDescription( "in", "The input image." ); AddParameter(ParameterType_InputImage, "inseg", "Segmented image"); SetParameterDescription( "inseg", " The segmented image input. Segmented image input is the segmentation of the input image." ); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "The output image. The output image is the input image where the minimal regions have been merged." ); AddParameter(ParameterType_Int, "minsize", "Minimum Region Size"); SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is merged with the \"nearest\" region (radiometrically)."); SetDefaultParameterInt("minsize", 50); SetMinimumParameterIntValue("minsize", 0); MandatoryOff("minsize"); AddParameter(ParameterType_Int, "nbtilesx", "Number of Tiles (X-axis)"); SetParameterDescription("nbtilesx", "Number of Tiles along the X-axis."); SetDefaultParameterInt("nbtilesx", 10); SetMinimumParameterIntValue("nbtilesx", 1); MandatoryOff("nbtilesx"); AddParameter(ParameterType_Int, "nbtilesy", "Number of Tiles (Y-axis)"); SetParameterDescription("nbtilesy", "Number of Tiles along the Y-axis."); SetDefaultParameterInt("nbtilesy", 10); SetMinimumParameterIntValue("nbtilesy", 1); MandatoryOff("nbtilesy"); // Doc example parameter settings SetDocExampleParameterValue("in","smooth.tif"); SetDocExampleParameterValue("inseg","segmentation.tif"); SetDocExampleParameterValue("out","merged.tif"); SetDocExampleParameterValue("minsize","20"); SetDocExampleParameterValue("nbtilesx","4"); SetDocExampleParameterValue("nbtilesy","4"); } void DoUpdateParameters() { } void DoExecute() { clock_t tic = clock(); unsigned int minSize = GetParameterInt("minsize"); unsigned int nbTilesX = GetParameterInt("nbtilesx"); unsigned int nbTilesY = GetParameterInt("nbtilesy"); //Acquisition of the input image dimensions ImageType::Pointer imageIn = GetParameterImage("in"); imageIn->UpdateOutputInformation(); unsigned long sizeImageX = imageIn->GetLargestPossibleRegion().GetSize()[0], sizeImageY = imageIn->GetLargestPossibleRegion().GetSize()[1]; unsigned int numberOfComponentsPerPixel = imageIn->GetNumberOfComponentsPerPixel(); LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg"); StatisticsImageFilterType::Pointer stats = StatisticsImageFilterType::New(); stats->SetInput(labelIn); stats->Update(); unsigned int regionCount=stats->GetMaximum(); std::vector<unsigned int>nbPixels; nbPixels.clear(); nbPixels.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) nbPixels[curLabel] = 0; ImageType::PixelType defaultValue(numberOfComponentsPerPixel); defaultValue.Fill(0); std::vector<ImageType::PixelType>sum(regionCount+1,defaultValue); //Sums calculation per label otbAppLogINFO(<<"Sums calculation ..."); unsigned long sizeTilesX = (sizeImageX+nbTilesX-1)/nbTilesX; unsigned long sizeTilesY = (sizeImageY+nbTilesY-1)/nbTilesY; for(unsigned int row = 0; row < nbTilesY ; row++) for(unsigned int column = 0; column < nbTilesX ; column++) { unsigned long startX = column*sizeTilesX; unsigned long startY = row*sizeTilesY; unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX); unsigned long sizeY = vcl_min(sizeTilesY,sizeImageY-startY); //Tiles extraction of the input image MultiChannelExtractROIFilterType::Pointer imageROI = MultiChannelExtractROIFilterType::New(); imageROI->SetInput(imageIn); imageROI->SetStartX(startX); imageROI->SetStartY(startY); imageROI->SetSizeX(sizeX); imageROI->SetSizeY(sizeY); imageROI->Update(); //Tiles extraction of the segmented image ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New(); labelImageROI->SetInput(labelIn); labelImageROI->SetStartX(startX); labelImageROI->SetStartY(startY); labelImageROI->SetSizeX(sizeX); labelImageROI->SetSizeY(sizeY); labelImageROI->Update(); //Sums calculation for the mean calculation per label LabelImageIterator itLabel( labelImageROI->GetOutput(), labelImageROI->GetOutput()->GetLargestPossibleRegion()); ImageIterator itImage( imageROI->GetOutput(), imageROI->GetOutput()->GetLargestPossibleRegion()); for (itLabel.GoToBegin(), itImage.GoToBegin(); !itLabel.IsAtEnd(); ++itLabel, ++itImage) { nbPixels[itLabel.Value()]++; for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { sum[itLabel.Value()][comp]+=itImage.Get()[comp]; } } } //LUT creation for the final relabelling std::vector<LabelImagePixelType> LUT; LUT.clear(); LUT.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) { LUT[curLabel] = curLabel; } //Minimal size region suppression otbAppLogINFO(<<"Building LUT for small regions merging ..."); for (unsigned int size=1;size<minSize;size++) { // LUTtmp creation in order to modify the LUT only at the end of the pass std::vector<LabelImagePixelType> LUTtmp; LUTtmp.clear(); LUTtmp.resize(regionCount+1); for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel) { LUTtmp[curLabel] = LUT[curLabel]; } for(unsigned int row = 0; row < nbTilesY ; row++) { for(unsigned int column = 0; column < nbTilesX ; column++) { std::set<int> minLabel, edgeLabel, labelMerged; std::map<int,std::set<int> > adjMap; unsigned long startX = column*sizeTilesX, startY = row*sizeTilesY; unsigned long sizeX = vcl_min(sizeTilesX+size+1,sizeImageX-startX), sizeY = vcl_min(sizeTilesY+size+1,sizeImageY-startY); ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New(); labelImageROI->SetInput(labelIn); labelImageROI->SetStartX(startX); labelImageROI->SetStartY(startY); labelImageROI->SetSizeX(sizeX); labelImageROI->SetSizeY(sizeY); labelImageROI->Update(); LabelImageType::IndexType pixelIndex; //"Adjacency map" creation for the region with nbPixels=="size" for(pixelIndex[0]=0;pixelIndex[0]<static_cast<long>(sizeX);++pixelIndex[0]) for(pixelIndex[1]=0;pixelIndex[1]<static_cast<long>(sizeY);++pixelIndex[1]) { LabelImagePixelType curLabel = labelImageROI->GetOutput()->GetPixel(pixelIndex); if(labelMerged.count(LUT[curLabel])) { edgeLabel.insert(LUT[curLabel]); } if((pixelIndex[0]==0)&&(startX!=0)) { edgeLabel.insert(LUT[curLabel]); } if((pixelIndex[1]==0)&&(startY!=0)) { edgeLabel.insert(LUT[curLabel]); } if(pixelIndex[0]==static_cast<long>(sizeX)-1) { if(startX!=(nbTilesX-1)*sizeTilesX) edgeLabel.insert(LUT[curLabel]); } else { ++pixelIndex[0]; LabelImagePixelType adjLabelX = labelImageROI->GetOutput()->GetPixel(pixelIndex); --pixelIndex[0]; if(LUT[adjLabelX]!=LUT[curLabel]) { if((nbPixels[LUT[curLabel]]>0)&&(nbPixels[LUT[curLabel]]==size)) { adjMap[LUT[curLabel]].insert(LUT[adjLabelX]); minLabel.insert(LUT[curLabel]); } if((nbPixels[LUT[adjLabelX]]>0)&&(nbPixels[LUT[adjLabelX]]==size)) { adjMap[LUT[adjLabelX]].insert(LUT[curLabel]); minLabel.insert(LUT[adjLabelX]); } } } if(pixelIndex[1]==static_cast<long>(sizeY)-1) { if(startY!=(nbTilesY-1)*sizeTilesY) edgeLabel.insert(LUT[curLabel]); } else { ++pixelIndex[1]; LabelImagePixelType adjLabelY = labelImageROI->GetOutput()->GetPixel(pixelIndex); --pixelIndex[1]; if(LUT[adjLabelY]!=LUT[curLabel]) { if((nbPixels[LUT[curLabel]]>0)&&(nbPixels[LUT[curLabel]]==size)) { adjMap[LUT[curLabel]].insert(LUT[adjLabelY]); minLabel.insert(LUT[curLabel]); } if((nbPixels[LUT[adjLabelY]]>0)&&(nbPixels[LUT[adjLabelY]]==size)) { adjMap[LUT[adjLabelY]].insert(LUT[curLabel]); minLabel.insert(LUT[adjLabelY]);} } } } //Searching the "nearest" region for(std::set<int>::iterator itMinLabel=minLabel.begin(); itMinLabel!=minLabel.end(); ++itMinLabel) { LabelImagePixelType curLabel = *itMinLabel, adjLabel; double err = itk::NumericTraits<double>::max(); if(edgeLabel.count(curLabel)==0) { if(nbPixels[curLabel]==size) { edgeLabel.insert(curLabel); for(std::set<int>::iterator itAdjLabel=adjMap[curLabel].begin(); itAdjLabel!=adjMap[curLabel].end(); ++itAdjLabel) { double tmpError = 0; LabelImagePixelType tmpLabel = *itAdjLabel; if(tmpLabel!=curLabel) { for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { double curComp = static_cast<double>(sum[curLabel][comp])/nbPixels[curLabel]; int tmpComp = static_cast<double>(sum[tmpLabel][comp])/nbPixels[tmpLabel]; tmpError += (curComp-tmpComp)*(curComp-tmpComp); } if(tmpError<err) { err = tmpError; adjLabel = tmpLabel; } } } //Fusion of the two regions if(adjLabel!=curLabel) { unsigned int curLabelLUT = curLabel, adjLabelLUT = adjLabel; while(LUTtmp[curLabelLUT] != curLabelLUT) { curLabelLUT = LUTtmp[curLabelLUT]; } while(LUTtmp[adjLabelLUT] != adjLabelLUT) { adjLabelLUT = LUTtmp[adjLabelLUT]; } if(curLabelLUT < adjLabelLUT) { LUTtmp[adjLabelLUT] = curLabelLUT; } else { LUTtmp[LUTtmp[curLabelLUT]] = adjLabelLUT; LUTtmp[curLabelLUT] = adjLabelLUT; } } } } } for(LabelImagePixelType label = 1; label < regionCount+1; ++label) { LabelImagePixelType can = label; while(LUTtmp[can] != can) { can = LUTtmp[can]; } LUTtmp[label] = can; } } } for(LabelImagePixelType label = 1; label < regionCount+1; ++label) { LUT[label]=LUTtmp[label]; if((nbPixels[label]!=0)&&(LUT[label]!=label)) { nbPixels[LUT[label]]+=nbPixels[label]; nbPixels[label]=0; for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp) { sum[LUT[label]][comp]+=sum[label][comp]; } } } } //Relabelling m_ChangeLabelFilter = ChangeLabelImageFilterType::New(); m_ChangeLabelFilter->SetInput(labelIn); for(LabelImagePixelType label = 1;label<regionCount+1; ++label) { if(label!=LUT[label]) { m_ChangeLabelFilter->SetChange(label,LUT[label]); } } SetParameterOutputImage("out", m_ChangeLabelFilter->GetOutput()); clock_t toc = clock(); otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds"); } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSMerging) <|endoftext|>
<commit_before><?hh //partial use typesafety\Result; use stdClass; describe('Result', function() { beforeEach(function() { $message = new stdClass(); $message->code = 2055; $message->descr = "error message"; $message->path = "/foo/var/example.hh"; $message->line = 38; $message->end = 26; $message->start = 26; $errorObject = new stdClass(); $errorObject->messages = [ $message ]; $resultObject = new stdClass(); $resultObject->passed = true; $resultObject->version = "817b3a0 Nov 15 2014 13:25:51"; $resultObject->errors = [ $error ]; $this->resultObject = $resultObject; $this->result = Result::fromObject($resultObject); }); describe('#getVersion', function() { it('return version text', function() { expect($this->result->getVersion())->toBe("817b3a0 Nov 15 2014 13:25:51"); }); }); describe('#isPassed', function() { context('when passed', function() { it('return true', function() { expect($this->result->isPassed())->toBeTrue(); }); }); context('when failed', function() { beforeEach(function() { $this->resultObject->passed = false; $this->failedResult = Result::fromObject($this->resultObject); }); it('return true', function() { expect($this->failedResult->isPassed())->toBeFalse(); }); }); }); describe('#getErrors', function() { it('return Iterator<Error> instance', function() { expect($this->result->getErrors())->toBeAnInstanceOf(Iterator::class); }); }); }); <commit_msg>fix text<commit_after><?hh //partial use typesafety\Result; use stdClass; describe('Result', function() { beforeEach(function() { $message = new stdClass(); $message->code = 2055; $message->descr = "error message"; $message->path = "/foo/var/example.hh"; $message->line = 38; $message->end = 26; $message->start = 26; $errorObject = new stdClass(); $errorObject->messages = [ $message ]; $resultObject = new stdClass(); $resultObject->passed = true; $resultObject->version = "817b3a0 Nov 15 2014 13:25:51"; $resultObject->errors = [ $error ]; $this->resultObject = $resultObject; $this->result = Result::fromObject($resultObject); }); describe('#getVersion', function() { it('return version text', function() { expect($this->result->getVersion())->toBe("817b3a0 Nov 15 2014 13:25:51"); }); }); describe('#isPassed', function() { context('when passed', function() { it('return true', function() { expect($this->result->isPassed())->toBeTrue(); }); }); context('when failed', function() { beforeEach(function() { $this->resultObject->passed = false; $this->failedResult = Result::fromObject($this->resultObject); }); it('return false', function() { expect($this->failedResult->isPassed())->toBeFalse(); }); }); }); describe('#getErrors', function() { it('return Iterator<Error> instance', function() { expect($this->result->getErrors())->toBeAnInstanceOf(Iterator::class); }); }); }); <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 * *****************************************************************************/ #include <iostream> #include <vector> #include <string> #include <mapnik/util/fs.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop const int DEFAULT_DEPTH = 8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; using std::endl; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (std::exception const& ex) { clog << "Error: " << ex.what() << endl; return -1; } clog << "max tree depth:" << depth << endl; clog << "split ratio:" << ratio << endl; vector<string>::const_iterator itr = shape_files.begin(); if (itr == shape_files.end()) { clog << "no shape files to index" << endl; return 0; } while (itr != shape_files.end()) { clog << "processing " << *itr << endl; std::string shapename (*itr++); boost::algorithm::ireplace_last(shapename,".shp",""); std::string shapename_full (shapename+".shp"); if (! mapnik::util::exists (shapename_full)) { clog << "Error : file " << shapename_full << " does not exist" << endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { clog << "Error : cannot open " << shapename_full << endl; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 clog << code << endl; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); box2d<double> extent; shp.read_envelope(extent); clog << "length=" << file_length << endl; clog << "version=" << version << endl; clog << "type=" << shape_type << endl; clog << "extent:" << extent << endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); shape_type = shp.read_ndr_integer(); box2d<double> item_ext; if (shape_type==shape_io::shape_null) { // still need to increment pos, or the pos counter // won't indicate EOF until too late. pos+=4+content_length; continue; } else if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); // skip m shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); // skip z shp.read_double(); // According to ESRI shapefile doc // A PointZ consists of a triplet of double-precision coordinates in the order X, Y, Z plus a // measure. // PointZ // { // Double X // X coordinate // Double Y // Y coordinate // Double Z // Z coordinate // Double M // Measure // } // But OGR creates shapefiles with M missing so we need skip M only if present // NOTE: content_length is in 16-bit words if ( content_length == 18) { shp.read_double(); } item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { clog << "record number " << record_number << " box=" << item_ext << endl; } pos+=4+content_length; ++count; if (pos >= file_length) break; } clog << " number shapes=" << count << endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } clog << "done!" << endl; return 0; } <commit_msg>avoid inf loop on empty point3d shapefile<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 * *****************************************************************************/ #include <iostream> #include <vector> #include <string> #include <mapnik/util/fs.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop const int DEFAULT_DEPTH = 8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; using std::endl; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (std::exception const& ex) { clog << "Error: " << ex.what() << endl; return -1; } clog << "max tree depth:" << depth << endl; clog << "split ratio:" << ratio << endl; vector<string>::const_iterator itr = shape_files.begin(); if (itr == shape_files.end()) { clog << "no shape files to index" << endl; return 0; } while (itr != shape_files.end()) { clog << "processing " << *itr << endl; std::string shapename (*itr++); boost::algorithm::ireplace_last(shapename,".shp",""); std::string shapename_full (shapename+".shp"); if (! mapnik::util::exists (shapename_full)) { clog << "Error : file " << shapename_full << " does not exist" << endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { clog << "Error : cannot open " << shapename_full << endl; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 clog << code << endl; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); box2d<double> extent; shp.read_envelope(extent); clog << "length=" << file_length << endl; clog << "version=" << version << endl; clog << "type=" << shape_type << endl; clog << "extent:" << extent << endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); shape_type = shp.read_ndr_integer(); box2d<double> item_ext; if (shape_type==shape_io::shape_null) { if (pos >= file_length) { break; } else { // still need to increment pos, or the pos counter // won't indicate EOF until too late. pos+=4+content_length; continue; } } else if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); // skip m shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); // skip z shp.read_double(); // According to ESRI shapefile doc // A PointZ consists of a triplet of double-precision coordinates in the order X, Y, Z plus a // measure. // PointZ // { // Double X // X coordinate // Double Y // Y coordinate // Double Z // Z coordinate // Double M // Measure // } // But OGR creates shapefiles with M missing so we need skip M only if present // NOTE: content_length is in 16-bit words if ( content_length == 18) { shp.read_double(); } item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { clog << "record number " << record_number << " box=" << item_ext << endl; } pos+=4+content_length; ++count; if (pos >= file_length) break; } clog << " number shapes=" << count << endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } clog << "done!" << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017-2019 ARM Limited. * * SPDX-License-Identifier: MIT * * 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 "pmu_profiler.h" #include "hwcpipe_log.h" namespace hwcpipe { const std::unordered_map<CpuCounter, uint64_t, CpuCounterHash> pmu_mappings{ {CpuCounter::Cycles, PERF_COUNT_HW_CPU_CYCLES}, {CpuCounter::Instructions, PERF_COUNT_HW_INSTRUCTIONS}, {CpuCounter::CacheReferences, PERF_COUNT_HW_CACHE_REFERENCES}, {CpuCounter::CacheMisses, PERF_COUNT_HW_CACHE_MISSES}, {CpuCounter::BranchInstructions, PERF_COUNT_HW_BRANCH_INSTRUCTIONS}, {CpuCounter::BranchMisses, PERF_COUNT_HW_BRANCH_MISSES}, }; PmuProfiler::PmuProfiler(const CpuCounterSet &enabled_counters) : enabled_counters_(enabled_counters) { // Set up PMU counters for (const auto &counter : enabled_counters) { const auto &pmu_config = pmu_mappings.find(counter); if (pmu_config != pmu_mappings.end()) { try { // Create a PMU counter with the specified configuration auto pmu_counter_res = pmu_counters_.emplace(counter, PmuCounter{pmu_config->second}); // Try reading a value from the counter to check that it opened correctly auto &pmu_counter = pmu_counter_res.first->second; pmu_counter.get_value<long long>(); // PMU counter is created and can retrieve values available_counters_.insert(counter); } catch (const std::runtime_error &e) { // PMU counter initialization failed HWCPIPE_LOG("%s", e.what()); } } } if (available_counters_.size() == 0) { throw std::runtime_error("PMU counters not available."); } } void PmuProfiler::run() { for (auto &pmu_counter : pmu_counters_) { pmu_counter.second.reset(); prev_measurements_[pmu_counter->first] = 0; } } const CpuMeasurements &PmuProfiler::sample() { for (const auto &counter : enabled_counters_) { const auto &pmu_counter = pmu_counters_.find(counter); if (pmu_counter == pmu_counters_.end()) { continue; } try { measurements_[pmu_counter->first] = pmu_counter->second.get_value<long long>(); pmu_counter->second.reset(); } catch (const std::runtime_error &e) { HWCPIPE_LOG("Failed to get value from PMU: %s.", e.what()); } } return measurements_; } void PmuProfiler::stop() { // We don't need to do anything on stop() } } // namespace hwcpipe <commit_msg>Implement differential reading of PMU counter<commit_after>/* * Copyright (c) 2017-2019 ARM Limited. * * SPDX-License-Identifier: MIT * * 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 "pmu_profiler.h" #include "hwcpipe_log.h" namespace hwcpipe { const std::unordered_map<CpuCounter, uint64_t, CpuCounterHash> pmu_mappings{ {CpuCounter::Cycles, PERF_COUNT_HW_CPU_CYCLES}, {CpuCounter::Instructions, PERF_COUNT_HW_INSTRUCTIONS}, {CpuCounter::CacheReferences, PERF_COUNT_HW_CACHE_REFERENCES}, {CpuCounter::CacheMisses, PERF_COUNT_HW_CACHE_MISSES}, {CpuCounter::BranchInstructions, PERF_COUNT_HW_BRANCH_INSTRUCTIONS}, {CpuCounter::BranchMisses, PERF_COUNT_HW_BRANCH_MISSES}, }; PmuProfiler::PmuProfiler(const CpuCounterSet &enabled_counters) : enabled_counters_(enabled_counters) { // Set up PMU counters for (const auto &counter : enabled_counters) { const auto &pmu_config = pmu_mappings.find(counter); if (pmu_config != pmu_mappings.end()) { try { // Create a PMU counter with the specified configuration auto pmu_counter_res = pmu_counters_.emplace(counter, PmuCounter{pmu_config->second}); // Try reading a value from the counter to check that it opened correctly auto &pmu_counter = pmu_counter_res.first->second; pmu_counter.get_value<long long>(); // PMU counter is created and can retrieve values available_counters_.insert(counter); } catch (const std::runtime_error &e) { // PMU counter initialization failed HWCPIPE_LOG("%s", e.what()); } } } if (available_counters_.size() == 0) { throw std::runtime_error("PMU counters not available."); } } void PmuProfiler::run() { for (auto &pmu_counter : pmu_counters_) { pmu_counter.second.reset(); prev_measurements_[pmu_counter->first] = 0; } } const CpuMeasurements &PmuProfiler::sample() { for (const auto &counter : enabled_counters_) { const auto &pmu_counter = pmu_counters_.find(counter); if (pmu_counter == pmu_counters_.end()) { continue; } try { auto value = pmu_counter->second.get_value<long long>(); // Resetting the PMU counter every frame seems to alter the data, // so we make a differential reading. measurements_[pmu_counter->first] = value - prev_measurements_[pmu_counter->first].get<long long>(); prev_measurements_[pmu_counter->first] = value; } catch (const std::runtime_error &e) { HWCPIPE_LOG("Failed to get value from PMU: %s.", e.what()); } } return measurements_; } void PmuProfiler::stop() { // We don't need to do anything on stop() } } // namespace hwcpipe <|endoftext|>