<commit_before>/*
 *
 * Copyright 2018 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/port.h"

#ifdef GRPC_CFSTREAM
#import <CoreFoundation/CoreFoundation.h>
#import "src/core/lib/iomgr/cfstream_handle.h"

#include <grpc/support/atm.h>
#include <grpc/support/sync.h>

#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/exec_ctx.h"

extern grpc_core::TraceFlag grpc_tcp_trace;

void* CFStreamHandle::Retain(void* info) {
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
  CFSTREAM_HANDLE_REF(handle, "retain");
  return info;
}

void CFStreamHandle::Release(void* info) {
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
  CFSTREAM_HANDLE_UNREF(handle, "release");
}

CFStreamHandle* CFStreamHandle::CreateStreamHandle(
    CFReadStreamRef read_stream, CFWriteStreamRef write_stream) {
  return new CFStreamHandle(read_stream, write_stream);
}

void CFStreamHandle::ReadCallback(CFReadStreamRef stream,
                                  CFStreamEventType type,
                                  void* client_callback_info) {
  grpc_core::ExecCtx exec_ctx;
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle,
            stream, type, client_callback_info);
  }
  switch (type) {
    case kCFStreamEventOpenCompleted:
      handle->open_event_.SetReady();
      break;
    case kCFStreamEventHasBytesAvailable:
    case kCFStreamEventEndEncountered:
      handle->read_event_.SetReady();
      break;
    case kCFStreamEventErrorOccurred:
      handle->open_event_.SetReady();
      handle->read_event_.SetReady();
      break;
    default:
      GPR_UNREACHABLE_CODE(return );
  }
}
void CFStreamHandle::WriteCallback(CFWriteStreamRef stream,
                                   CFStreamEventType type,
                                   void* clientCallBackInfo) {
  grpc_core::ExecCtx exec_ctx;
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);
  printf("** CFStreamHandle::WriteCallback\n");
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle,
            stream, type, clientCallBackInfo);
  }
  switch (type) {
    case kCFStreamEventOpenCompleted:
      handle->open_event_.SetReady();
      break;
    case kCFStreamEventCanAcceptBytes:
    case kCFStreamEventEndEncountered:
      handle->write_event_.SetReady();
      break;
    case kCFStreamEventErrorOccurred:
      handle->open_event_.SetReady();
      handle->write_event_.SetReady();
      break;
    default:
      GPR_UNREACHABLE_CODE(return );
  }
}

CFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream,
                               CFWriteStreamRef write_stream) {
  gpr_ref_init(&refcount_, 1);
  open_event_.InitEvent();
  read_event_.InitEvent();
  write_event_.InitEvent();
  dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);
  CFStreamClientContext ctx = {0, static_cast<void*>(this),
                               CFStreamHandle::Retain, CFStreamHandle::Release,
                               nil};
  CFReadStreamSetClient(
      read_stream,
      kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable |
          kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
      CFStreamHandle::ReadCallback, &ctx);
  CFWriteStreamSetClient(
      write_stream,
      kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes |
          kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
      CFStreamHandle::WriteCallback, &ctx);
  CFReadStreamSetDispatchQueue(read_stream, dispatch_queue_);
  CFWriteStreamSetDispatchQueue(write_stream, dispatch_queue_);
}

CFStreamHandle::~CFStreamHandle() {
  open_event_.DestroyEvent();
  read_event_.DestroyEvent();
  write_event_.DestroyEvent();
}

void CFStreamHandle::NotifyOnOpen(grpc_closure* closure) {
  open_event_.NotifyOn(closure);
}

void CFStreamHandle::NotifyOnRead(grpc_closure* closure) {
  read_event_.NotifyOn(closure);
}

void CFStreamHandle::NotifyOnWrite(grpc_closure* closure) {
  write_event_.NotifyOn(closure);
}

void CFStreamHandle::Shutdown(grpc_error* error) {
  open_event_.SetShutdown(GRPC_ERROR_REF(error));
  read_event_.SetShutdown(GRPC_ERROR_REF(error));
  write_event_.SetShutdown(GRPC_ERROR_REF(error));
  GRPC_ERROR_UNREF(error);
}

void CFStreamHandle::Ref(const char* file, int line, const char* reason) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
    gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
            "CFStream Handle ref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
            reason, val, val + 1);
  }
  gpr_ref(&refcount_);
}

void CFStreamHandle::Unref(const char* file, int line, const char* reason) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
    gpr_log(GPR_ERROR,
            "CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
            reason, val, val - 1);
  }
  if (gpr_unref(&refcount_)) {
    delete this;
  }
}

#endif
<commit_msg>remove debug information<commit_after>/*
 *
 * Copyright 2018 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/port.h"

#ifdef GRPC_CFSTREAM
#import <CoreFoundation/CoreFoundation.h>
#import "src/core/lib/iomgr/cfstream_handle.h"

#include <grpc/support/atm.h>
#include <grpc/support/sync.h>

#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/exec_ctx.h"

extern grpc_core::TraceFlag grpc_tcp_trace;

void* CFStreamHandle::Retain(void* info) {
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
  CFSTREAM_HANDLE_REF(handle, "retain");
  return info;
}

void CFStreamHandle::Release(void* info) {
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
  CFSTREAM_HANDLE_UNREF(handle, "release");
}

CFStreamHandle* CFStreamHandle::CreateStreamHandle(
    CFReadStreamRef read_stream, CFWriteStreamRef write_stream) {
  return new CFStreamHandle(read_stream, write_stream);
}

void CFStreamHandle::ReadCallback(CFReadStreamRef stream,
                                  CFStreamEventType type,
                                  void* client_callback_info) {
  grpc_core::ExecCtx exec_ctx;
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle,
            stream, type, client_callback_info);
  }
  switch (type) {
    case kCFStreamEventOpenCompleted:
      handle->open_event_.SetReady();
      break;
    case kCFStreamEventHasBytesAvailable:
    case kCFStreamEventEndEncountered:
      handle->read_event_.SetReady();
      break;
    case kCFStreamEventErrorOccurred:
      handle->open_event_.SetReady();
      handle->read_event_.SetReady();
      break;
    default:
      GPR_UNREACHABLE_CODE(return );
  }
}
void CFStreamHandle::WriteCallback(CFWriteStreamRef stream,
                                   CFStreamEventType type,
                                   void* clientCallBackInfo) {
  grpc_core::ExecCtx exec_ctx;
  CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle,
            stream, type, clientCallBackInfo);
  }
  switch (type) {
    case kCFStreamEventOpenCompleted:
      handle->open_event_.SetReady();
      break;
    case kCFStreamEventCanAcceptBytes:
    case kCFStreamEventEndEncountered:
      handle->write_event_.SetReady();
      break;
    case kCFStreamEventErrorOccurred:
      handle->open_event_.SetReady();
      handle->write_event_.SetReady();
      break;
    default:
      GPR_UNREACHABLE_CODE(return );
  }
}

CFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream,
                               CFWriteStreamRef write_stream) {
  gpr_ref_init(&refcount_, 1);
  open_event_.InitEvent();
  read_event_.InitEvent();
  write_event_.InitEvent();
  dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);
  CFStreamClientContext ctx = {0, static_cast<void*>(this),
                               CFStreamHandle::Retain, CFStreamHandle::Release,
                               nil};
  CFReadStreamSetClient(
      read_stream,
      kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable |
          kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
      CFStreamHandle::ReadCallback, &ctx);
  CFWriteStreamSetClient(
      write_stream,
      kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes |
          kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
      CFStreamHandle::WriteCallback, &ctx);
  CFReadStreamSetDispatchQueue(read_stream, dispatch_queue_);
  CFWriteStreamSetDispatchQueue(write_stream, dispatch_queue_);
}

CFStreamHandle::~CFStreamHandle() {
  open_event_.DestroyEvent();
  read_event_.DestroyEvent();
  write_event_.DestroyEvent();
}

void CFStreamHandle::NotifyOnOpen(grpc_closure* closure) {
  open_event_.NotifyOn(closure);
}

void CFStreamHandle::NotifyOnRead(grpc_closure* closure) {
  read_event_.NotifyOn(closure);
}

void CFStreamHandle::NotifyOnWrite(grpc_closure* closure) {
  write_event_.NotifyOn(closure);
}

void CFStreamHandle::Shutdown(grpc_error* error) {
  open_event_.SetShutdown(GRPC_ERROR_REF(error));
  read_event_.SetShutdown(GRPC_ERROR_REF(error));
  write_event_.SetShutdown(GRPC_ERROR_REF(error));
  GRPC_ERROR_UNREF(error);
}

void CFStreamHandle::Ref(const char* file, int line, const char* reason) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
    gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
            "CFStream Handle ref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
            reason, val, val + 1);
  }
  gpr_ref(&refcount_);
}

void CFStreamHandle::Unref(const char* file, int line, const char* reason) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
    gpr_log(GPR_ERROR,
            "CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
            reason, val, val - 1);
  }
  if (gpr_unref(&refcount_)) {
    delete this;
  }
}

#endif
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/util/volumevectorsampler.h>

namespace inviwo {

VolumeVectorSampler::VolumeVectorSampler(std::shared_ptr<const std::vector<std::shared_ptr<Volume>>> volumeVector) {
    for (const auto &vol : (*volumeVector.get())) {
        samplers_.push_back(VolumeSampler(vol.get()));
    }
}

VolumeVectorSampler::~VolumeVectorSampler()  {

}

dvec4 VolumeVectorSampler::sample(const dvec4 &pos) const
{
    dvec3 spatialPos = pos.xyz;
    double t = pos.w;

    int tIndex = static_cast<int>(t);
    double tInterpolant = t - static_cast<float>(tIndex);

    dvec4 v0, v1;
    v0 = getVoxel(spatialPos, tIndex);
    v1 = getVoxel(spatialPos, tIndex + 1);

    return Interpolation<dvec4>::linear(v0, v1, tInterpolant);
}

dvec4 VolumeVectorSampler::getVoxel(const dvec3 &pos, int T) const
{
    T = glm::clamp(T, 0, static_cast<int>(samplers_.size()) - 1);
    return samplers_[T].sample(pos);
}

} // namespace

<commit_msg>Core: Volume Vector Sampler unix compile fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/util/volumevectorsampler.h>

namespace inviwo {

VolumeVectorSampler::VolumeVectorSampler(std::shared_ptr<const std::vector<std::shared_ptr<Volume>>> volumeVector) {
    for (const auto &vol : (*volumeVector.get())) {
        samplers_.push_back(VolumeSampler(vol.get()));
    }
}

VolumeVectorSampler::~VolumeVectorSampler()  {

}

dvec4 VolumeVectorSampler::sample(const dvec4 &pos) const
{
    dvec3 spatialPos = pos.xyz();
    double t = pos.w;

    int tIndex = static_cast<int>(t);
    double tInterpolant = t - static_cast<float>(tIndex);

    dvec4 v0, v1;
    v0 = getVoxel(spatialPos, tIndex);
    v1 = getVoxel(spatialPos, tIndex + 1);

    return Interpolation<dvec4>::linear(v0, v1, tInterpolant);
}

dvec4 VolumeVectorSampler::getVoxel(const dvec3 &pos, int T) const
{
    T = glm::clamp(T, 0, static_cast<int>(samplers_.size()) - 1);
    return samplers_[T].sample(pos);
}

} // namespace

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlinfo.h"
#include <private/qmldeclarativedata_p.h>
#include <QtDeclarative/qmlcontext.h>
#include <QtGui/qapplication.h>

QT_BEGIN_NAMESPACE

/*!
    \fn void qmlInfo(const QString& message, QObject *object)

    \brief Prints warnings messages that include the file and line number for QML types.

    When QML types display warning messages, it improves tracibility
    if they include the QML file and line number on which the
    particular instance was instantiated.

    To include the file and line number, an object must be passed.  If
    the file and line number is not available for that instance
    (either it was not instantiated by the QML engine or location
    information is disabled), "unknown location" will be used instead.

    For example,

    \code
    qmlInfo(object, tr("component property is a write-once property"));
    \endcode

    prints

    \code
    QML ComponentInstance (unknown location): component property is a write-once property
    \endcode
*/

void qmlInfo(const QString& msg, QObject* object)
{
    QString pos = QLatin1String("QML");
    if (object) {
        pos += " ";
        pos += QLatin1String(object->metaObject()->className());
    }
    QmlDeclarativeData *ddata = QmlDeclarativeData::get(object);
    pos += QLatin1String(" (");
    if (ddata) {
        if (ddata->outerContext) {
            pos += ddata->outerContext->baseUrl().toString();
        } else {
            pos += qApp->translate("QmlInfo","unknown");
        }
        pos += QLatin1String(":");
        pos += QString::number(ddata->lineNumber);
        pos += QLatin1String(":");
        pos += QString::number(ddata->columnNumber);
    } else {
        pos += qApp->translate("QmlInfo","unknown location");
    }
    pos += QLatin1String(") ");
    qWarning((pos + msg).toLocal8Bit()); // XXX allow other processing?
}

QT_END_NAMESPACE
<commit_msg>Minor fixes for qmlInfo.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlinfo.h"
#include <private/qmldeclarativedata_p.h>
#include <QtDeclarative/qmlcontext.h>
#include <QtGui/qapplication.h>

QT_BEGIN_NAMESPACE

/*!
    \fn void qmlInfo(const QString& message, QObject *object)

    \brief Prints warnings messages that include the file and line number for QML types.

    When QML types display warning messages, it improves tracibility
    if they include the QML file and line number on which the
    particular instance was instantiated.

    To include the file and line number, an object must be passed.  If
    the file and line number is not available for that instance
    (either it was not instantiated by the QML engine or location
    information is disabled), "unknown location" will be used instead.

    For example,

    \code
    qmlInfo(tr("component property is a write-once property"), object);
    \endcode

    prints

    \code
    QML ComponentInstance (unknown location): component property is a write-once property
    \endcode
*/

void qmlInfo(const QString& msg, QObject* object)
{
    QString pos = QLatin1String("QML");
    if (object) {
        pos += QLatin1Char(' ');
        pos += QLatin1String(object->metaObject()->className());
    }
    QmlDeclarativeData *ddata = QmlDeclarativeData::get(object);
    pos += QLatin1String(" (");
    if (ddata) {
        if (ddata->outerContext) {
            pos += ddata->outerContext->baseUrl().toString();
        } else {
            pos += qApp->translate("QmlInfo","unknown");
        }
        pos += QLatin1String(":");
        pos += QString::number(ddata->lineNumber);
        pos += QLatin1String(":");
        pos += QString::number(ddata->columnNumber);
    } else {
        pos += qApp->translate("QmlInfo","unknown location");
    }
    pos += QLatin1String(") ");
    qWarning((pos + msg).toLocal8Bit()); // XXX allow other processing?
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		07/2012
*/
#include "Precompiled.h"
#include "ListBoxItemControl.h"

namespace tools
{
	void ListBoxItemControl::getCellDimension(MyGUI::Widget* _sender, MyGUI::IntCoord& _coord, bool _drop)
	{
		int height = MyGUI::utility::parseValue<int>(_sender->getUserString("CellHeight"));
		_coord.set(0, 0, _sender->getClientCoord().width, height);
	}

	ListBoxItemControl::ListBoxItemControl(MyGUI::Widget* _parent) :
		wraps::BaseCellView<SkinItem*>("ListBoxItemControl.layout", _parent)
	{
		mMainWidget->setCoord(0, 0, _parent->getWidth(), _parent->getHeight());
		mMainWidget->setAlign(MyGUI::Align::Stretch);
		mMainWidget->setNeedMouseFocus(false);
	}

	void ListBoxItemControl::update(const MyGUI::IBDrawItemInfo& _info, SkinItem* _data)
	{
		if (_data == nullptr)
			return;

		if (_info.update)
		{
			mMainWidget->castType<MyGUI::Button>()->setCaption(_data->getName());
		}

		std::string state = "";
		if (_info.select)
		{
			if (_info.active)
			{
				state = "highlighted_checked";
			}
			else
			{
				state = "normal_checked";
			}
		}
		else
		{
			if (_info.active)
			{
				state = "highlighted";
			}
			else
			{
				state = "normal";
			}
		}

		if (_info.drag)
		{
			if (_info.drop_accept)
				state = "highlighted_checked";
			else if (_info.drop_refuse)
				state = "normal";
		}

		mMainWidget->_setWidgetState(state);
	}
}
<commit_msg>update states<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		07/2012
*/
#include "Precompiled.h"
#include "ListBoxItemControl.h"

namespace tools
{
	void ListBoxItemControl::getCellDimension(MyGUI::Widget* _sender, MyGUI::IntCoord& _coord, bool _drop)
	{
		int height = MyGUI::utility::parseValue<int>(_sender->getUserString("CellHeight"));
		_coord.set(0, 0, _sender->getClientCoord().width, height);
	}

	ListBoxItemControl::ListBoxItemControl(MyGUI::Widget* _parent) :
		wraps::BaseCellView<SkinItem*>("ListBoxItemControl.layout", _parent)
	{
		mMainWidget->setCoord(0, 0, _parent->getWidth(), _parent->getHeight());
		mMainWidget->setAlign(MyGUI::Align::Stretch);
		mMainWidget->setNeedMouseFocus(false);
	}

	void ListBoxItemControl::update(const MyGUI::IBDrawItemInfo& _info, SkinItem* _data)
	{
		if (_data == nullptr)
			return;

		if (_info.update)
		{
			mMainWidget->castType<MyGUI::Button>()->setCaption(_data->getName());
		}

		std::string state = "";
		if (_info.select)
		{
			if (_info.active)
			{
				state = "highlighted_checked";
			}
			else
			{
				state = "normal_checked";
			}
		}
		else
		{
			if (_info.active)
			{
				state = "highlighted";
			}
			else
			{
				state = "normal";
			}
		}

		if (_info.drag)
		{
			if (_info.drop_accept)
				state = "highlighted_checked";
			else if (_info.drop_refuse)
				state = "normal";
		}
		else
		{
			if (!_info.active)
			{
				if (_info.drop_accept)
					state = "highlighted";
				else if (_info.drop_refuse)
					state = "normal";
			}
		}

		mMainWidget->_setWidgetState(state);
	}
}
<|endoftext|>


<commit_before>int test() {
    int y, m, d;
    assert_equal(2451545, dateToInt(2000, 1, 1));
    intToDate(2451545, y, m, d);
    assert_equal(2000, y);
    assert_equal(1, m);
    assert_equal(1, d);

    for (int i = 1; i <= 31; i++) assert_equal((6 + i - 1) % 7, dateToInt(2012, 1, i) % 7);
    for (int i = 1; i <= 29; i++) assert_equal((2 + i - 1) % 7, dateToInt(2012, 2, i) % 7);

    for (int i = 1; i <= 31; i++) assert_equal((6 + i - 1) % 7, dateToInt(2908, 1, i) % 7);
    for (int i = 1; i <= 29; i++) assert_equal((2 + i - 1) % 7, dateToInt(2908, 2, i) % 7);

    for (int i = 1; i <= 30; i++) assert_equal((1 + i - 1) % 7, dateToInt(2320, 6, i) % 7);
    for (int i = 1; i <= 31; i++) assert_equal((2 + i - 1) % 7, dateToInt(2320, 12, i) % 7);

    intToDate(dateToInt(2320, 1, 1) + 4*7 + 9, y, m, d);
    assert_equal(2320, y);
    assert_equal(2, m);
    assert_equal(7, d);

    intToDate(dateToInt(2320, 1, 1) + 4*7 + 9 + 3*7 + 2, y, m, d);
    assert_equal(2320, y);
    assert_equal(3, m);
    assert_equal(1, d);
}
<commit_msg>Added some field testing for dates.<commit_after>int test() {
    /* Field testing: UVa 11356, UVa 12019, UVa 893 (had to use long long) */

    int y, m, d;
    assert_equal(2451545, dateToInt(2000, 1, 1));
    intToDate(2451545, y, m, d);
    assert_equal(2000, y);
    assert_equal(1, m);
    assert_equal(1, d);

    for (int i = 1; i <= 31; i++) assert_equal((6 + i - 1) % 7, dateToInt(2012, 1, i) % 7);
    for (int i = 1; i <= 29; i++) assert_equal((2 + i - 1) % 7, dateToInt(2012, 2, i) % 7);

    for (int i = 1; i <= 31; i++) assert_equal((6 + i - 1) % 7, dateToInt(2908, 1, i) % 7);
    for (int i = 1; i <= 29; i++) assert_equal((2 + i - 1) % 7, dateToInt(2908, 2, i) % 7);

    for (int i = 1; i <= 30; i++) assert_equal((1 + i - 1) % 7, dateToInt(2320, 6, i) % 7);
    for (int i = 1; i <= 31; i++) assert_equal((2 + i - 1) % 7, dateToInt(2320, 12, i) % 7);

    intToDate(dateToInt(2320, 1, 1) + 4*7 + 9, y, m, d);
    assert_equal(2320, y);
    assert_equal(2, m);
    assert_equal(7, d);

    intToDate(dateToInt(2320, 1, 1) + 4*7 + 9 + 3*7 + 2, y, m, d);
    assert_equal(2320, y);
    assert_equal(3, m);
    assert_equal(1, d);
}
<|endoftext|>


<commit_before>#include "BinaryFileStorageDriver.h"

bool BinaryFileStorageDriver::openConnection(const std::string path, bool withTrunc)
{
	if (!file.is_open())
	{
		if (withTrunc)
		{
			file.open(path.c_str(),
				std::fstream::in | std::fstream::out | std::fstream::trunc);
		}
		else
		{
			file.open(path.c_str(),
				std::fstream::in | std::fstream::out);
		}
		return file.is_open();
	}

	return true;
}

void BinaryFileStorageDriver::closeConnection()
{
	if (file.is_open())
	{
		file.close();
	}
}

bool BinaryFileStorageDriver::saveGestureFrame(GestureFrame gestureFrame)
{
	if (file.is_open())
	{
		file<<gestureFrame.getTimestamp();
		for (int i=0; i<gestureFrame.getHandCount(); i++)
		{
			GestureHand *gHand = gestureFrame.getHand(i);
			file<<"#"<<gHand->getId();
			file<<" "<<gHand->getPalmPosition();
			file<<" "<<gHand->getStabilizedPalmPosition();
			file<<" "<<gHand->getPalmNormal();
			file<<" "<<gHand->getDirection();

			for (int j=0; j<gHand->getFingerCount(); j++)
			{
				GestureFinger *gFinger = gHand->getFinger(j);
				file<<"f"<<gFinger->getId();
				file<<" "<<gFinger->getTipPosition();
				file<<" "<<gFinger->getStabilizedTipPosition();
				file<<" "<<gFinger->getDirection();
				file<<" "<<gFinger->getLength();
				file<<" "<<gFinger->getWidth();
			}
		}
		file<<std::endl;

		return true;
	}

	return false;
}

bool BinaryFileStorageDriver::loadGestureFrame(GestureFrame &gestureFrame)
{
	if (file.is_open() && !file.eof())
	{
		std::string gFrameLine;
		std::getline(file, gFrameLine);
		gFrameLine += '\n';

		bool isEnd = false;

		this->currState = TIMESTAMP_STATE;

		for (int i=0; i<gFrameLine.size() && !isEnd; i++)
		{
			char currSign = gFrameLine[i];
			try
			{
				switch(currState)
				{
					case TIMESTAMP_STATE:
					    if (tryChangeState(currSign, '#', HAND_ID_STATE)
					    	|| tryChangeState(currSign, '\n', END_PARSE))
					    {
					    	gestureFrame.setTimestamp(strToFloat(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_ID_STATE:
					    if (tryChangeState(currSign, ' ', HAND_PALM_POSITION_STATE))
					    {
					    	gestureHand.clear();
					    	gestureHand.setId(strToInt(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_PALM_POSITION_STATE:
					    if (tryChangeState(currSign, ' ', HAND_STABILIZED_PALM_POSITION_STATE))
					    {
					    	gestureHand.setPalmPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_STABILIZED_PALM_POSITION_STATE:
					    if (tryChangeState(currSign, ' ', HAND_PALM_NORMAL))
					    {
					    	gestureHand.setStabilizedPalmPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_PALM_NORMAL:
					    if (tryChangeState(currSign, ' ', HAND_DIRECTION))
					    {
					    	gestureHand.setPalmNormal(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_DIRECTION:
					    if (tryChangeState(currSign, '\n', END_PARSE)
					    	|| tryChangeState(currSign, '#', HAND_ID_STATE))
					    {
					    	gestureHand.setDirection(getVertexParameter());
					    	gestureFrame.addHand(gestureHand);
					    	clearParameters();
					    	break;
					    }
					    if (tryChangeState(currSign, 'f', HAND_FINGER_ID))
					    {
					    	gestureHand.setDirection(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_ID:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_TIP_POSITION))
					    {
					    	gestureFinger.clear();
					    	gestureFinger.setId(strToInt(parameter.c_str()));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_FINGER_TIP_POSITION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_STABILIZED_TIP_POSITION))
					    {
					    	gestureFinger.setTipPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_STABILIZED_TIP_POSITION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_DIRECTION))
					    {
					    	gestureFinger.setStabilizedTipPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_DIRECTION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_LENGTH))
					    {
					    	gestureFinger.setDirection(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_LENGTH:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_WIDTH))
					    {
					    	gestureFinger.setLength(strToFloat(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_FINGER_WIDTH:
					    if (tryChangeState(currSign, '\n', END_PARSE)
					    	|| tryChangeState(currSign, '#', HAND_ID_STATE))
					    {
					    	gestureFinger.setWidth(strToFloat(parameter));
					    	gestureHand.addFinger(gestureFinger);
					    	gestureFrame.addHand(gestureHand);
					    	clearParameters();
					    	break;
					    }
					    if (tryChangeState(currSign, 'f', HAND_FINGER_ID))
					    {
					    	gestureFinger.setWidth(strToFloat(parameter));
					    	gestureHand.addFinger(gestureFinger);
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case END_PARSE:
					    isEnd = true;
					    break;
				}
			}
			catch(std::string e)
			{
				std::cout<<e;
				return false;
			}
		}

		return true;
	}

	return false;
}

bool BinaryFileStorageDriver::tryChangeState(char currSign, char endSign, ParseState nextState)
{
	if (currSign == endSign)
	{
		currState = nextState;
		return true;
	}

	return false;
}

void BinaryFileStorageDriver::parameterStateAction(char currSign)
{
	parameter += currSign;
}

void BinaryFileStorageDriver::vertexParameterStateAction(char currSign, char separatorSign)
{
	if (currSign == separatorSign)
	{
		vertexParameterIndex++;
		return;
	}

	vertexParameter[vertexParameterIndex] += currSign;
}

void BinaryFileStorageDriver::clearParameters()
{
	this->parameter.clear();
	this->vertexParameter[0].clear();
	this->vertexParameter[1].clear();
	this->vertexParameter[2].clear();
	this->vertexParameterIndex = 0;
}

int BinaryFileStorageDriver::strToInt(std::string value)
{
	std::istringstream ss(value);
	int result;
	if (!(ss >> result))
	{
		throw std::string("Cannot convert to int value: ") + value;
	}

	return result;
}

float BinaryFileStorageDriver::strToFloat(std::string value)
{
	std::istringstream ss(value);
	float result;
	if (!(ss >> result))
	{
		throw std::string("Cannot convert to float value: ") + value;
	}

	return result;
}
<commit_msg>Change loading gesture file<commit_after>#include "BinaryFileStorageDriver.h"

bool BinaryFileStorageDriver::openConnection(const std::string path, bool withTrunc)
{
	if (!file.is_open())
	{
		if (withTrunc)
		{
			file.open(path.c_str(),
				std::fstream::in | std::fstream::out | std::fstream::trunc);
		}
		else
		{
			file.open(path.c_str(),
				std::fstream::in | std::fstream::out);
		}
		return file.is_open();
	}

	return true;
}

void BinaryFileStorageDriver::closeConnection()
{
	if (file.is_open())
	{
		file.close();
	}
}

bool BinaryFileStorageDriver::saveGestureFrame(GestureFrame gestureFrame)
{
	if (file.is_open())
	{
		file<<gestureFrame.getTimestamp();
		for (int i=0; i<gestureFrame.getHandCount(); i++)
		{
			GestureHand *gHand = gestureFrame.getHand(i);
			file<<"#"<<gHand->getId();
			file<<" "<<gHand->getPalmPosition();
			file<<" "<<gHand->getStabilizedPalmPosition();
			file<<" "<<gHand->getPalmNormal();
			file<<" "<<gHand->getDirection();

			for (int j=0; j<gHand->getFingerCount(); j++)
			{
				GestureFinger *gFinger = gHand->getFinger(j);
				file<<"f"<<gFinger->getId();
				file<<" "<<gFinger->getTipPosition();
				file<<" "<<gFinger->getStabilizedTipPosition();
				file<<" "<<gFinger->getDirection();
				file<<" "<<gFinger->getLength();
				file<<" "<<gFinger->getWidth();
			}
		}
		file<<std::endl;

		return true;
	}

	return false;
}

bool BinaryFileStorageDriver::loadGestureFrame(GestureFrame &gestureFrame)
{
	if (file.is_open())
	{
		std::string gFrameLine;
		std::getline(file, gFrameLine);

		if (file.eof())
			return false;

		gFrameLine += '\n';

		bool isEnd = false;

		this->currState = TIMESTAMP_STATE;

		for (int i=0; i<gFrameLine.size() && !isEnd; i++)
		{
			char currSign = gFrameLine[i];
			try
			{
				switch(currState)
				{
					case TIMESTAMP_STATE:
					    if (tryChangeState(currSign, '#', HAND_ID_STATE)
					    	|| tryChangeState(currSign, '\n', END_PARSE))
					    {
					    	gestureFrame.setTimestamp(strToFloat(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_ID_STATE:
					    if (tryChangeState(currSign, ' ', HAND_PALM_POSITION_STATE))
					    {
					    	gestureHand.clear();
					    	gestureHand.setId(strToInt(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_PALM_POSITION_STATE:
					    if (tryChangeState(currSign, ' ', HAND_STABILIZED_PALM_POSITION_STATE))
					    {
					    	gestureHand.setPalmPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_STABILIZED_PALM_POSITION_STATE:
					    if (tryChangeState(currSign, ' ', HAND_PALM_NORMAL))
					    {
					    	gestureHand.setStabilizedPalmPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_PALM_NORMAL:
					    if (tryChangeState(currSign, ' ', HAND_DIRECTION))
					    {
					    	gestureHand.setPalmNormal(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_DIRECTION:
					    if (tryChangeState(currSign, '\n', END_PARSE)
					    	|| tryChangeState(currSign, '#', HAND_ID_STATE))
					    {
					    	gestureHand.setDirection(getVertexParameter());
					    	gestureFrame.addHand(gestureHand);
					    	clearParameters();
					    	break;
					    }
					    if (tryChangeState(currSign, 'f', HAND_FINGER_ID))
					    {
					    	gestureHand.setDirection(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_ID:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_TIP_POSITION))
					    {
					    	gestureFinger.clear();
					    	gestureFinger.setId(strToInt(parameter.c_str()));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_FINGER_TIP_POSITION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_STABILIZED_TIP_POSITION))
					    {
					    	gestureFinger.setTipPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_STABILIZED_TIP_POSITION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_DIRECTION))
					    {
					    	gestureFinger.setStabilizedTipPosition(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_DIRECTION:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_LENGTH))
					    {
					    	gestureFinger.setDirection(getVertexParameter());
					    	clearParameters();
					    	break;
					    }
					    vertexParameterStateAction(currSign, ';');
					    break;
					case HAND_FINGER_LENGTH:
					    if (tryChangeState(currSign, ' ', HAND_FINGER_WIDTH))
					    {
					    	gestureFinger.setLength(strToFloat(parameter));
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case HAND_FINGER_WIDTH:
					    if (tryChangeState(currSign, '\n', END_PARSE)
					    	|| tryChangeState(currSign, '#', HAND_ID_STATE))
					    {
					    	gestureFinger.setWidth(strToFloat(parameter));
					    	gestureHand.addFinger(gestureFinger);
					    	gestureFrame.addHand(gestureHand);
					    	clearParameters();
					    	break;
					    }
					    if (tryChangeState(currSign, 'f', HAND_FINGER_ID))
					    {
					    	gestureFinger.setWidth(strToFloat(parameter));
					    	gestureHand.addFinger(gestureFinger);
					    	clearParameters();
					    	break;
					    }
					    parameterStateAction(currSign);
					    break;
					case END_PARSE:
					    isEnd = true;
					    break;
				}
			}
			catch(std::string & e)
			{
				std::cout<<e<<std::endl;
				return false;
			}
		}

		return true;
	}

	return false;
}

bool BinaryFileStorageDriver::tryChangeState(char currSign, char endSign, ParseState nextState)
{
	if (currSign == endSign)
	{
		currState = nextState;
		return true;
	}

	return false;
}

void BinaryFileStorageDriver::parameterStateAction(char currSign)
{
	parameter += currSign;
}

void BinaryFileStorageDriver::vertexParameterStateAction(char currSign, char separatorSign)
{
	if (currSign == separatorSign)
	{
		vertexParameterIndex++;
		return;
	}

	vertexParameter[vertexParameterIndex] += currSign;
}

void BinaryFileStorageDriver::clearParameters()
{
	this->parameter.clear();
	this->vertexParameter[0].clear();
	this->vertexParameter[1].clear();
	this->vertexParameter[2].clear();
	this->vertexParameterIndex = 0;
}

int BinaryFileStorageDriver::strToInt(std::string value)
{
	std::istringstream ss(value);
	int result;
	if (!(ss >> result))
	{
		throw std::string("Cannot convert to int value: \"") + value + "\"";
	}

	return result;
}

float BinaryFileStorageDriver::strToFloat(std::string value)
{
	std::istringstream ss(value);
	float result;
	if (!(ss >> result))
	{
		throw std::string("Cannot convert to float value: \"") + value + "\"";
	}

	return result;
}
<|endoftext|>


<commit_before>#include "SPlotFit2.h"

// from STL
#include <string>

// from ROOT
#include "TIterator.h"

// from RooFit
#include "RooAbsArg.h"
#include "RooCategory.h"
#include "RooCmdArg.h"
#include "RooDataHist.h"
#include "RooDataSet.h"
#include "RooLinkedListIter.h"
#include "RooRealVar.h"
#include "RooArgList.h"
#include "RooFitResult.h"

// from RooFit PDFs
#include "RooAbsPdf.h"
#include "RooAddPdf.h"
#include "RooExtendPdf.h"
#include "RooHistPdf.h"
#include "RooKeysPdf.h"
#include "RooProdPdf.h"

// from RooStats
#include "RooStats/SPlot.h"

// from DooCore
#include <doocore/io/MsgStream.h>

// from Project
#include "doofit/fitter/easyfit/EasyFit.h"

using std::cout;
using std::endl;
using std::map;
using std::pair;

using namespace RooFit;

using namespace doocore::io;

namespace doofit {
namespace fitter {
namespace splot {

SPlotFit2::SPlotFit2(doofit::fitter::easyfit::EasyFit& easyfit, RooDataSet& data, RooArgSet yields) :
  pdf_(NULL),
  pdf_owned_(false),
  yields_(yields),
  parameters_(NULL),
  num_cpu_(1),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(&easyfit)
{

}

SPlotFit2::SPlotFit2() :
  pdf_(NULL),
  pdf_owned_(false),
  yields_(NULL),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;
}

SPlotFit2::SPlotFit2(RooAbsPdf& pdf, RooDataSet& data, RooArgSet yields) :
  pdf_(&pdf),
  pdf_owned_(false),
  yields_(yields),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(RooAbsPdf&, RooDataSet&, RooArgSet): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;
}

SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs, RooDataSet& data, std::vector<RooRealVar*> yields) :
  pdf_(NULL),
  pdf_owned_(true),
  yields_(),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>, RooDataSet&, std::vector<RooRealVar*>): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;

  RooArgList pdfs_list;

  if (yields.size() != pdfs.size()) {
    if (yields.size() > 0) {
      serr << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>, RooDataSet&, std::vector<RooRealVar*>): yields are set, but number of yields does not match number of PDFs. Will ignore yields." << endmsg;
    }

    for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
         it != pdfs.end(); ++it) {
      pdfs_list.add(**it);
      RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield",
                                       TString()+(*it)->GetName()+"_yield",
                                       input_data_->sumEntries()/pdfs.size(), 0.0,
                                       input_data_->sumEntries()*10);
      yields_.addOwned(*var);
    }
  } else {
    for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
         it != pdfs.end(); ++it) {
      pdfs_list.add(**it);
    }
    for (std::vector<RooRealVar*>::const_iterator it = yields.begin();
         it != yields.end(); ++it) {
      yields_.add(**it);
    }
  }
  pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_);
//  pdf_->Print("v");
}

SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs) :
  pdf_(NULL),
  pdf_owned_(true),
  yields_(),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(NULL),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL)
{
  swarn << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;

  RooArgList pdfs_list;
  for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
       it != pdfs.end(); ++it) {
    pdfs_list.add(**it);
    RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield",
                                     TString()+(*it)->GetName()+"_yield",
                                     1e7, 0.0, 1e10);
    yields_.addOwned(*var);
  }
  pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_);
}

SPlotFit2::~SPlotFit2(){
  if (pdf_owned_ && pdf_ != NULL) delete pdf_;
  if (parameters_ != NULL) delete parameters_;
}

void SPlotFit2::Fit(RooLinkedList* ext_fit_args) {
  //=========================================================================
  // merge our and external fitting arguments

  if (easyfitter_ != NULL) {
    sinfo << "SPlotFit2::Fit(): Using EasyFit for fitting!" << endmsg;

    easyfitter_->SetSave(true);

    easyfitter_->Fit();

    const RooFitResult* fit_result = easyfitter_->GetFitResult();

    if (fit_result != NULL) {
      fit_result->Print("v");
    } else {
      serr << "Error in SPlotFit2::Fit(RooLinkedList*): Fit result not available." << endmsg;
    }
  } else {
    swarn << "SPlotFit2::Fit(): Not using EasyFit for fitting! This will be deprecated in the near future." << endmsg;
    swarn << "SPlotFit2::Fit(): Seriously, switch to EasyFit ASAP! It's much good and beautiful." << endmsg;

    RooLinkedList fitting_args;
    fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_))));
    fitting_args.Add((TObject*)(new RooCmdArg(Extended())));
    fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_))));
    fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2))));
    fitting_args.Add((TObject*)(new RooCmdArg(Save(true))));
    fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false))));
    fitting_args.Add((TObject*)(new RooCmdArg(Timer(true))));
    fitting_args.Add((TObject*)(new RooCmdArg(Minimizer("Minuit2","minimize"))));
    if (ext_fit_args != NULL) {
      RooLinkedListIter it = ext_fit_args->iterator();
      TObject* arg = NULL;

      while ((arg = it.Next())) {
        //arg->Print();
        fitting_args.Add(arg);
      }
    }

    //=========================================================================
    pdf_->getParameters(*input_data_)->readFromFile(starting_values_);
    // fit discriminating pdf
    RooFitResult* fit_result = pdf_->fitTo(*input_data_, fitting_args);
    fit_result->Print("v");
    delete fit_result;
  }

  parameters_ = pdf().getParameters(*input_data_);

  //=========================================================================
  // create sPlot
  // get all parameters
  RooArgSet* par_disc_set = pdf_->getParameters(*input_data_);

  // remove yields from parameter set
  par_disc_set->remove(yields_);

  // Helper pointers
  RooRealVar* var_iter1 = NULL;

  // iterate over left over parameters of full disc pdf and set constant
  RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator();
  while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) {
    var_iter1->setConstant();
  }
  delete par_disc_set_iterator;

  // create datasets
  RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_,yields_);

  //=========================================================================
  // create sweighted datasets
  sweighted_data_ = sData->GetSDataSet();

  // iterate over yields
  RooLinkedListIter* yield_iterator = (RooLinkedListIter*)yields_.createIterator();
  while (var_iter1=(RooRealVar*)yield_iterator->Next()) {
    std::string comp_name = var_iter1->GetName();

    sinfo << "SPlotFit2: Adding sweighted dataset with name " << comp_name << endmsg;
    sweighted_data_map_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+var_iter1->GetName()+"_sw");
  }
  delete yield_iterator;
}

std::pair<RooHistPdf*,RooDataHist*> SPlotFit2::GetHistPdf(const std::string& pdf_name, const RooArgSet& vars_set, const std::string& comp_name, const std::string& binningName){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  RooHistPdf*  pdf_hist  = new RooHistPdf(pdf_name.c_str(),pdf_name.c_str(),vars_set,*data_hist);

  return std::pair<RooHistPdf*,RooDataHist*>(pdf_hist,data_hist);
}

RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, const std::string& binningName ){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  return data_hist;
}

RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, RooRealVar * var, const std::string& binningName ){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name+var->GetName(),TString("sDataHist")+comp_name+var->GetName(),RooArgList(*var), TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  return data_hist;
}

RooKeysPdf& SPlotFit2::GetKeysPdf(const std::string& pdf_name, RooRealVar& var, const std::string& comp_name){
  RooKeysPdf* pdf_keys = new RooKeysPdf(pdf_name.c_str(),pdf_name.c_str(),var,*sweighted_data_map_[comp_name]);
  return *pdf_keys;
}

RooDataSet* SPlotFit2::GetSwDataSet(const std::string& comp_name){
  if (comp_name==""){
    return sweighted_data_;
  }
  else{
    return sweighted_data_map_[comp_name];
  }
}

void SPlotFit2::WriteParametersFile(std::string filename) {
  parameters_->writeToFile(filename.c_str());
}

} //namespace splot
} //namespace fitter
} //namespace doofit
<commit_msg>SPlotFit2: resolved bug while getting fit parameters after fit using EasyFit<commit_after>#include "SPlotFit2.h"

// from STL
#include <string>

// from ROOT
#include "TIterator.h"

// from RooFit
#include "RooAbsArg.h"
#include "RooCategory.h"
#include "RooCmdArg.h"
#include "RooDataHist.h"
#include "RooDataSet.h"
#include "RooLinkedListIter.h"
#include "RooRealVar.h"
#include "RooArgList.h"
#include "RooFitResult.h"

// from RooFit PDFs
#include "RooAbsPdf.h"
#include "RooAddPdf.h"
#include "RooExtendPdf.h"
#include "RooHistPdf.h"
#include "RooKeysPdf.h"
#include "RooProdPdf.h"

// from RooStats
#include "RooStats/SPlot.h"

// from DooCore
#include <doocore/io/MsgStream.h>

// from Project
#include "doofit/fitter/easyfit/EasyFit.h"

using std::cout;
using std::endl;
using std::map;
using std::pair;

using namespace RooFit;

using namespace doocore::io;

namespace doofit {
namespace fitter {
namespace splot {

SPlotFit2::SPlotFit2(doofit::fitter::easyfit::EasyFit& easyfit, RooDataSet& data, RooArgSet yields) :
  pdf_(NULL),
  pdf_owned_(false),
  yields_(yields),
  parameters_(NULL),
  num_cpu_(1),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(&easyfit)
{

}

SPlotFit2::SPlotFit2() :
  pdf_(NULL),
  pdf_owned_(false),
  yields_(NULL),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;
}

SPlotFit2::SPlotFit2(RooAbsPdf& pdf, RooDataSet& data, RooArgSet yields) :
  pdf_(&pdf),
  pdf_owned_(false),
  yields_(yields),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(RooAbsPdf&, RooDataSet&, RooArgSet): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;
}

SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs, RooDataSet& data, std::vector<RooRealVar*> yields) :
  pdf_(NULL),
  pdf_owned_(true),
  yields_(),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(&data),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL),
  starting_values_("")
{
  swarn << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>, RooDataSet&, std::vector<RooRealVar*>): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;

  RooArgList pdfs_list;

  if (yields.size() != pdfs.size()) {
    if (yields.size() > 0) {
      serr << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>, RooDataSet&, std::vector<RooRealVar*>): yields are set, but number of yields does not match number of PDFs. Will ignore yields." << endmsg;
    }

    for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
         it != pdfs.end(); ++it) {
      pdfs_list.add(**it);
      RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield",
                                       TString()+(*it)->GetName()+"_yield",
                                       input_data_->sumEntries()/pdfs.size(), 0.0,
                                       input_data_->sumEntries()*10);
      yields_.addOwned(*var);
    }
  } else {
    for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
         it != pdfs.end(); ++it) {
      pdfs_list.add(**it);
    }
    for (std::vector<RooRealVar*>::const_iterator it = yields.begin();
         it != yields.end(); ++it) {
      yields_.add(**it);
    }
  }
  pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_);
//  pdf_->Print("v");
}

SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs) :
  pdf_(NULL),
  pdf_owned_(true),
  yields_(),
  parameters_(NULL),
  num_cpu_(4),
  input_data_(NULL),
  disc_vars_(),
  cont_vars_(),
  disc_pdfs_(),
  cont_pdfs_(),
  disc_pdfs_extend_(),
  sweighted_data_map_(),
  sweighted_hist_map_(),
  use_minos_(true),
  easyfitter_(NULL)
{
  swarn << "SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*>): Using deprecated constructor without EasyFit. This functionality will go away in a future version. Please switch to EasyFit ASAP!" << endmsg;

  RooArgList pdfs_list;
  for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin();
       it != pdfs.end(); ++it) {
    pdfs_list.add(**it);
    RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield",
                                     TString()+(*it)->GetName()+"_yield",
                                     1e7, 0.0, 1e10);
    yields_.addOwned(*var);
  }
  pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_);
}

SPlotFit2::~SPlotFit2(){
  if (pdf_owned_ && pdf_ != NULL) delete pdf_;
  if (parameters_ != NULL) delete parameters_;
}

void SPlotFit2::Fit(RooLinkedList* ext_fit_args) {
  //=========================================================================
  // merge our and external fitting arguments

  if (easyfitter_ != NULL) {
    sinfo << "SPlotFit2::Fit(): Using EasyFit for fitting!" << endmsg;

    easyfitter_->SetSave(true);

    easyfitter_->Fit();

    const RooFitResult* fit_result = easyfitter_->GetFitResult();
    parameters_ = easyfitter_->ParameterArgSet();

    if (fit_result != NULL) {
      fit_result->Print("v");
    } else {
      serr << "Error in SPlotFit2::Fit(RooLinkedList*): Fit result not available." << endmsg;
    }
  } else {
    swarn << "SPlotFit2::Fit(): Not using EasyFit for fitting! This will be deprecated in the near future." << endmsg;
    swarn << "SPlotFit2::Fit(): Seriously, switch to EasyFit ASAP! It's much good and beautiful." << endmsg;

    RooLinkedList fitting_args;
    fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_))));
    fitting_args.Add((TObject*)(new RooCmdArg(Extended())));
    fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_))));
    fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2))));
    fitting_args.Add((TObject*)(new RooCmdArg(Save(true))));
    fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false))));
    fitting_args.Add((TObject*)(new RooCmdArg(Timer(true))));
    fitting_args.Add((TObject*)(new RooCmdArg(Minimizer("Minuit2","minimize"))));
    if (ext_fit_args != NULL) {
      RooLinkedListIter it = ext_fit_args->iterator();
      TObject* arg = NULL;

      while ((arg = it.Next())) {
        //arg->Print();
        fitting_args.Add(arg);
      }
    }

    //=========================================================================
    pdf_->getParameters(*input_data_)->readFromFile(starting_values_);
    // fit discriminating pdf
    RooFitResult* fit_result = pdf_->fitTo(*input_data_, fitting_args);
    fit_result->Print("v");
    delete fit_result;

    parameters_ = pdf().getParameters(*input_data_);
  }

  //=========================================================================
  // create sPlot
  // get all parameters
  RooArgSet* par_disc_set = pdf_->getParameters(*input_data_);

  // remove yields from parameter set
  par_disc_set->remove(yields_);

  // Helper pointers
  RooRealVar* var_iter1 = NULL;

  // iterate over left over parameters of full disc pdf and set constant
  RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator();
  while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) {
    var_iter1->setConstant();
  }
  delete par_disc_set_iterator;

  // create datasets
  RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_,yields_);

  //=========================================================================
  // create sweighted datasets
  sweighted_data_ = sData->GetSDataSet();

  // iterate over yields
  RooLinkedListIter* yield_iterator = (RooLinkedListIter*)yields_.createIterator();
  while (var_iter1=(RooRealVar*)yield_iterator->Next()) {
    std::string comp_name = var_iter1->GetName();

    sinfo << "SPlotFit2: Adding sweighted dataset with name " << comp_name << endmsg;
    sweighted_data_map_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+var_iter1->GetName()+"_sw");
  }
  delete yield_iterator;
}

std::pair<RooHistPdf*,RooDataHist*> SPlotFit2::GetHistPdf(const std::string& pdf_name, const RooArgSet& vars_set, const std::string& comp_name, const std::string& binningName){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  RooHistPdf*  pdf_hist  = new RooHistPdf(pdf_name.c_str(),pdf_name.c_str(),vars_set,*data_hist);

  return std::pair<RooHistPdf*,RooDataHist*>(pdf_hist,data_hist);
}

RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, const std::string& binningName ){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  return data_hist;
}

RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, RooRealVar * var, const std::string& binningName ){
  RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name+var->GetName(),TString("sDataHist")+comp_name+var->GetName(),RooArgList(*var), TString(binningName));
  data_hist->add(*(sweighted_data_map_[comp_name]));
  return data_hist;
}

RooKeysPdf& SPlotFit2::GetKeysPdf(const std::string& pdf_name, RooRealVar& var, const std::string& comp_name){
  RooKeysPdf* pdf_keys = new RooKeysPdf(pdf_name.c_str(),pdf_name.c_str(),var,*sweighted_data_map_[comp_name]);
  return *pdf_keys;
}

RooDataSet* SPlotFit2::GetSwDataSet(const std::string& comp_name){
  if (comp_name==""){
    return sweighted_data_;
  }
  else{
    return sweighted_data_map_[comp_name];
  }
}

void SPlotFit2::WriteParametersFile(std::string filename) {
  parameters_->writeToFile(filename.c_str());
}

} //namespace splot
} //namespace fitter
} //namespace doofit
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDICOMITKSeriesGDCMReader.h"
#include "mitkDICOMFileReaderTestHelper.h"
#include "mitkDICOMFilenameSorter.h"
#include "mitkDICOMTagBasedSorter.h"
#include "mitkDICOMSortByTag.h"

#include "mitkTestingMacros.h"

#include <unordered_map>
#include "mitkStringProperty.h"

using mitk::DICOMTag;

int mitkDICOMITKSeriesGDCMReaderBasicsTest(int argc, char* argv[])
{
  MITK_TEST_BEGIN("mitkDICOMITKSeriesGDCMReaderBasicsTest");

  mitk::DICOMITKSeriesGDCMReader::Pointer gdcmReader = mitk::DICOMITKSeriesGDCMReader::New();
  MITK_TEST_CONDITION_REQUIRED(gdcmReader.IsNotNull(), "DICOMITKSeriesGDCMReader can be instantiated.");

  mitk::DICOMFileReaderTestHelper::SetTestInputFilenames( argc,argv );

  std::unordered_map<const char*, const char*> expectedPropertyTypes;
  std::unordered_map<const char*, mitk::DICOMTag> additionalTags;
  additionalTags.insert( { "Test1", DICOMTag(0x0008, 0x005)} );
  expectedPropertyTypes.insert( { "Test1", "StringProperty" } );

  additionalTags.insert( { "Test2", DICOMTag(0x0008, 0x008)} );
  expectedPropertyTypes.insert( { "Test2", "StringProperty" } );

  additionalTags.insert( { "Test3", DICOMTag(0x0008, 0x0060)} );
  expectedPropertyTypes.insert( { "Test3", "StringProperty" } );

  additionalTags.insert( { "Test4" ,DICOMTag(0x0008, 0x1070)} );
  expectedPropertyTypes.insert( { "Test4", "StringProperty" } );

  additionalTags.insert( { "Test5" ,DICOMTag(0x0020, 0x1041)} );
  expectedPropertyTypes.insert( { "Test5", "StringLookupTableProperty" } );

  gdcmReader->SetAdditionalTagsOfInterest( additionalTags );

  // check the Set/GetInput function
  mitk::DICOMFileReaderTestHelper::TestInputFilenames( gdcmReader );

  // check that output is a good reproduction of input (no duplicates, no new elements)
  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  // repeat test with filename based sorter in-between
  mitk::DICOMFilenameSorter::Pointer filenameSorter = mitk::DICOMFilenameSorter::New();
  gdcmReader->AddSortingElement( filenameSorter );
  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  // repeat test with some more realistic sorting
  gdcmReader = mitk::DICOMITKSeriesGDCMReader::New(); // this also tests destruction
  mitk::DICOMTagBasedSorter::Pointer tagSorter = mitk::DICOMTagBasedSorter::New();

  // all the things that split by tag in DicomSeriesReader
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0010) ); // Number of Rows
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0011) ); // Number of Columns
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0030) ); // Pixel Spacing
  tagSorter->AddDistinguishingTag( DICOMTag(0x0018, 0x1164) ); // Imager Pixel Spacing
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x0037), new mitk::DICOMTagBasedSorter::CutDecimalPlaces(5) ); // Image Orientation (Patient)
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x000e) ); // Series Instance UID
  tagSorter->AddDistinguishingTag( DICOMTag(0x0018, 0x0050) ); // Slice Thickness
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0008) ); // Number of Frames
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x0052) ); // Frame of Reference UID

  // a sorter...
  mitk::DICOMSortCriterion::ConstPointer sorting =
    mitk::DICOMSortByTag::New( DICOMTag(0x0020, 0x0013), // instance number
      mitk::DICOMSortByTag::New( DICOMTag(0x0020, 0x0012), // aqcuisition number
        mitk::DICOMSortByTag::New( DICOMTag(0x0008, 0x0032), // aqcuisition time
          mitk::DICOMSortByTag::New( DICOMTag(0x0018, 0x1060), // trigger time
            mitk::DICOMSortByTag::New( DICOMTag(0x0008, 0x0018) // SOP instance UID (last resort, not really meaningful but decides clearly)
            ).GetPointer()
          ).GetPointer()
        ).GetPointer()
      ).GetPointer()
    ).GetPointer();
  tagSorter->SetSortCriterion( sorting );

  gdcmReader->AddSortingElement( tagSorter );

  gdcmReader->SetAdditionalTagsOfInterest( additionalTags );

  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  gdcmReader->PrintOutputs(std::cout, true);

  // really load images
  mitk::DICOMFileReaderTestHelper::TestMitkImagesAreLoaded( gdcmReader, additionalTags, expectedPropertyTypes );

  //////////////////////////////////////////////////////////////////////////
  //
  // Load the images again with another TagLookupTableToPropertyFunctor
  //
  //////////////////////////////////////////////////////////////////////////

  gdcmReader->SetTagLookupTableToPropertyFunctor( []( const mitk::StringLookupTable& table )
  {
    return static_cast<mitk::BaseProperty::Pointer>( mitk::StringProperty::New( table.GetTableValue(0) ) );
  } );

  expectedPropertyTypes["Test5"] = "StringLProperty";

  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  gdcmReader->PrintOutputs(std::cout, true);

  // really load images
  mitk::DICOMFileReaderTestHelper::TestMitkImagesAreLoaded( gdcmReader, additionalTags, expectedPropertyTypes );

  MITK_TEST_END();
}
<commit_msg>COMP: Merge branch 'bug-19452-specify-DICOM-tags-in-image'<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDICOMITKSeriesGDCMReader.h"
#include "mitkDICOMFileReaderTestHelper.h"
#include "mitkDICOMFilenameSorter.h"
#include "mitkDICOMTagBasedSorter.h"
#include "mitkDICOMSortByTag.h"

#include "mitkTestingMacros.h"

#include <unordered_map>
#include "mitkStringProperty.h"

using mitk::DICOMTag;

int mitkDICOMITKSeriesGDCMReaderBasicsTest(int argc, char* argv[])
{
  MITK_TEST_BEGIN("mitkDICOMITKSeriesGDCMReaderBasicsTest");

  mitk::DICOMITKSeriesGDCMReader::Pointer gdcmReader = mitk::DICOMITKSeriesGDCMReader::New();
  MITK_TEST_CONDITION_REQUIRED(gdcmReader.IsNotNull(), "DICOMITKSeriesGDCMReader can be instantiated.");

  mitk::DICOMFileReaderTestHelper::SetTestInputFilenames( argc,argv );

  std::unordered_map<const char*, const char*> expectedPropertyTypes;
  std::unordered_map<const char*, mitk::DICOMTag> additionalTags;
  additionalTags.insert( std::make_pair( "Test1", DICOMTag( 0x0008, 0x005 ) ) );
  expectedPropertyTypes.insert( std::make_pair( "Test1", "StringProperty" ) );

  additionalTags.insert( std::make_pair( "Test2", DICOMTag( 0x0008, 0x008 ) ) );
  expectedPropertyTypes.insert( std::make_pair( "Test2", "StringProperty" ) );

  additionalTags.insert( std::make_pair( "Test3", DICOMTag( 0x0008, 0x0060 ) ) );
  expectedPropertyTypes.insert( std::make_pair( "Test3", "StringProperty" ) );

  additionalTags.insert( std::make_pair( "Test4", DICOMTag( 0x0008, 0x1070 ) ) );
  expectedPropertyTypes.insert( std::make_pair( "Test4", "StringProperty" ) );

  additionalTags.insert( std::make_pair( "Test5", DICOMTag( 0x0020, 0x1041 ) ) );
  expectedPropertyTypes.insert( std::make_pair( "Test5", "StringLookupTableProperty" ) );

  gdcmReader->SetAdditionalTagsOfInterest( additionalTags );

  // check the Set/GetInput function
  mitk::DICOMFileReaderTestHelper::TestInputFilenames( gdcmReader );

  // check that output is a good reproduction of input (no duplicates, no new elements)
  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  // repeat test with filename based sorter in-between
  mitk::DICOMFilenameSorter::Pointer filenameSorter = mitk::DICOMFilenameSorter::New();
  gdcmReader->AddSortingElement( filenameSorter );
  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  // repeat test with some more realistic sorting
  gdcmReader = mitk::DICOMITKSeriesGDCMReader::New(); // this also tests destruction
  mitk::DICOMTagBasedSorter::Pointer tagSorter = mitk::DICOMTagBasedSorter::New();

  // all the things that split by tag in DicomSeriesReader
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0010) ); // Number of Rows
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0011) ); // Number of Columns
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0030) ); // Pixel Spacing
  tagSorter->AddDistinguishingTag( DICOMTag(0x0018, 0x1164) ); // Imager Pixel Spacing
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x0037), new mitk::DICOMTagBasedSorter::CutDecimalPlaces(5) ); // Image Orientation (Patient)
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x000e) ); // Series Instance UID
  tagSorter->AddDistinguishingTag( DICOMTag(0x0018, 0x0050) ); // Slice Thickness
  tagSorter->AddDistinguishingTag( DICOMTag(0x0028, 0x0008) ); // Number of Frames
  tagSorter->AddDistinguishingTag( DICOMTag(0x0020, 0x0052) ); // Frame of Reference UID

  // a sorter...
  mitk::DICOMSortCriterion::ConstPointer sorting =
    mitk::DICOMSortByTag::New( DICOMTag(0x0020, 0x0013), // instance number
      mitk::DICOMSortByTag::New( DICOMTag(0x0020, 0x0012), // aqcuisition number
        mitk::DICOMSortByTag::New( DICOMTag(0x0008, 0x0032), // aqcuisition time
          mitk::DICOMSortByTag::New( DICOMTag(0x0018, 0x1060), // trigger time
            mitk::DICOMSortByTag::New( DICOMTag(0x0008, 0x0018) // SOP instance UID (last resort, not really meaningful but decides clearly)
            ).GetPointer()
          ).GetPointer()
        ).GetPointer()
      ).GetPointer()
    ).GetPointer();
  tagSorter->SetSortCriterion( sorting );

  gdcmReader->AddSortingElement( tagSorter );

  gdcmReader->SetAdditionalTagsOfInterest( additionalTags );

  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  gdcmReader->PrintOutputs(std::cout, true);

  // really load images
  mitk::DICOMFileReaderTestHelper::TestMitkImagesAreLoaded( gdcmReader, additionalTags, expectedPropertyTypes );

  //////////////////////////////////////////////////////////////////////////
  //
  // Load the images again with another TagLookupTableToPropertyFunctor
  //
  //////////////////////////////////////////////////////////////////////////

  gdcmReader->SetTagLookupTableToPropertyFunctor( []( const mitk::StringLookupTable& table )
  {
    return static_cast<mitk::BaseProperty::Pointer>( mitk::StringProperty::New( table.GetTableValue(0) ) );
  } );

  expectedPropertyTypes["Test5"] = "StringLProperty";

  mitk::DICOMFileReaderTestHelper::TestOutputsContainInputs( gdcmReader );

  gdcmReader->PrintOutputs(std::cout, true);

  // really load images
  mitk::DICOMFileReaderTestHelper::TestMitkImagesAreLoaded( gdcmReader, additionalTags, expectedPropertyTypes );

  MITK_TEST_END();
}
<|endoftext|>


<commit_before>#include "ga_callbacks.h"

#include "gate_helper.h"
#include "gpu_task.h"
#include "EACglobals.h"
#include "evaluators/IEvaluator.h"

#include "circuit/gate/GateInterpreter.h"

float ga_callbacks::evaluator(GAGenome& genome)
{
    static const size_t vec_count = pGlobals->settings->testVectors.setSize;

    static gpu_task::circuit_type circuit;
    circuit.in_size = pGlobals->settings->testVectors.inputLength;
    circuit.out_size = pGlobals->settings->testVectors.outputLength;

    circuit.layer_size = pGlobals->settings->gateCircuit.sizeLayer;
    circuit.layer_num = pGlobals->settings->gateCircuit.numLayers;

    circuit.genome_width = pGlobals->settings->gateCircuit.genomeWidth;

    static gpu_task task(circuit, vec_count, 128);
    static gate_helper<GENOME_ITEM_TYPE, gpu_task::genome_item_t> helper;

    if (pGlobals->testVectors.newSet) {
        task.update_inputs(const_cast<const byte**>(pGlobals->testVectors.inputs), vec_count);
        pGlobals->testVectors.newSet = false;
    }

    helper.transform((const GAGenome*)&genome);
    task.update_circuit(helper.get_nodes());
    task.run();
    byte* outs = task.receive_outputs();

    GA1DArrayGenome<GENOME_ITEM_TYPE>  &genome2 = (GA1DArrayGenome<GENOME_ITEM_TYPE>&) genome;

    for (size_t testVector = 0; testVector < vec_count; testVector++) {
        GateInterpreter::executeCircuit(&genome2, pGlobals->testVectors.inputs[testVector], pGlobals->testVectors.circuitOutputs[testVector]);
    }

    for (size_t testVector = 0; testVector < vec_count; testVector++) {
        byte* out_offset = outs + (testVector * pGlobals->settings->testVectors.outputLength);
        for ( int i = 0; i < pGlobals->settings->testVectors.outputLength; ++i ) {
            if ( out_offset[i] !=  pGlobals->testVectors.circuitOutputs[testVector][i] ) {
                std::cout << std::endl << "mismatch: " << testVector << ": " << std::endl;
                //printf("%u %u\n", out_offset[i], pGlobals->testVectors.circuitOutputs[testVector][i]);
                exit(EXIT_FAILURE);
            }
        }
    }

    pGlobals->evaluator->resetEvaluator();
    for ( size_t i = 0; i < vec_count; i++ ) {
        auto out_offset = outs + (i * circuit.out_size);
        pGlobals->evaluator->evaluateCircuit( out_offset, pGlobals->testVectors.outputs[i] );
    }
    return pGlobals->evaluator->getFitness();
}
<commit_msg>CUDA block_size is set from settings and disabled the running of the CPU circuit<commit_after>#include "ga_callbacks.h"

#include "gate_helper.h"
#include "gpu_task.h"
#include "EACglobals.h"
#include "evaluators/IEvaluator.h"

float ga_callbacks::evaluator(GAGenome& genome)
{
    static const size_t vec_count = pGlobals->settings->testVectors.setSize;

    static gpu_task::circuit_type circuit;
    circuit.in_size = pGlobals->settings->testVectors.inputLength;
    circuit.out_size = pGlobals->settings->testVectors.outputLength;

    circuit.layer_size = pGlobals->settings->gateCircuit.sizeLayer;
    circuit.layer_num = pGlobals->settings->gateCircuit.numLayers;

    circuit.genome_width = pGlobals->settings->gateCircuit.genomeWidth;

    const size_t block_size = pGlobals->settings->cuda.block_size;

    static gpu_task task(circuit, vec_count, block_size);
    static gate_helper<GENOME_ITEM_TYPE, gpu_task::genome_item_t> helper;

    if (pGlobals->testVectors.newSet) {
        task.update_inputs(const_cast<const byte**>(pGlobals->testVectors.inputs), vec_count);
        pGlobals->testVectors.newSet = false;
    }

    helper.transform((const GAGenome*)&genome);

    task.update_circuit(helper.get_nodes());
    task.run();
    byte* outs = task.receive_outputs();

    pGlobals->evaluator->resetEvaluator();
    for ( size_t i = 0; i < vec_count; i++ ) {
        auto out_offset = outs + (i * circuit.out_size);
        pGlobals->evaluator->evaluateCircuit( out_offset, pGlobals->testVectors.outputs[i] );
    }
    return pGlobals->evaluator->getFitness();
}
<|endoftext|>


<commit_before>#include "PackRegularRect.h"
#include "check_params.h"

#include <drag2d.h>
#include <easypacker.h>

namespace edb
{

std::string PackRegularRect::Command() const
{
	return "pack-rect";
}

std::string PackRegularRect::Description() const
{
	return "pack regular rects which edge are times of 4";
}

std::string PackRegularRect::Usage() const
{
	return Command() + " [src dir] [dst dir]";
}

void PackRegularRect::Run(int argc, char *argv[])
{
	// pack-rect e:\debug\cut e:\debug\pack

	if (!check_number(this, argc, 4)) return;
	if (!check_folder(argv[2])) return;
	if (!check_folder(argv[3])) return;

	Trigger(argv[2], argv[3]);
}

void PackRegularRect::Trigger(const std::string& src_dir, const std::string& dst_dir)
{
	wxArrayString files;
	d2d::FilenameTools::fetchAllFiles(src_dir, files);
	libpacker::RegularRectPack rrp(files);
<<<<<<< HEAD
=======
	rrp.Pack();
	rrp.PrintStatics();
>>>>>>> [ADDED] regular rect pack to easydb
}

}<commit_msg>[FIXED] 冲突没解决<commit_after>#include "PackRegularRect.h"
#include "check_params.h"

#include <drag2d.h>
#include <easypacker.h>

namespace edb
{

std::string PackRegularRect::Command() const
{
	return "pack-rect";
}

std::string PackRegularRect::Description() const
{
	return "pack regular rects which edge are times of 4";
}

std::string PackRegularRect::Usage() const
{
	return Command() + " [src dir] [dst dir]";
}

void PackRegularRect::Run(int argc, char *argv[])
{
	// pack-rect e:\debug\cut e:\debug\pack

	if (!check_number(this, argc, 4)) return;
	if (!check_folder(argv[2])) return;
	if (!check_folder(argv[3])) return;

	Trigger(argv[2], argv[3]);
}

void PackRegularRect::Trigger(const std::string& src_dir, const std::string& dst_dir)
{
	wxArrayString files;
	d2d::FilenameTools::fetchAllFiles(src_dir, files);
	libpacker::RegularRectPack rrp(files);
	rrp.Pack();
	rrp.PrintStatics();
}

}<|endoftext|>


<commit_before>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "elang/optimizer/transforms/clean_pass.h"

#include "elang/api/pass_controller.h"
#include "elang/optimizer/depth_first_traversal.h"
#include "elang/optimizer/editor.h"
#include "elang/optimizer/formatters/graphviz_formatter.h"
#include "elang/optimizer/formatters/text_formatter.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/opcode.h"

namespace elang {
namespace optimizer {

namespace {

// Collects nodes ending block.
class NodeCollector final : public NodeVisitor {
 public:
  NodeCollector() {}
  ~NodeCollector() = default;

  const std::vector<Node*>& nodes() const { return nodes_; }

 private:
  void DoDefaultVisit(Node* node) final {
    auto const opcode = node->opcode();
    if (opcode != Opcode::If && opcode != Opcode::Jump)
      return;
    nodes_.push_back(node);
  }

  std::vector<Node*> nodes_;

  DISALLOW_COPY_AND_ASSIGN(NodeCollector);
};

struct PostOrderControlFlow {
  static const UseEdges& AdjacentEdgesOf(const Function* function,
                                            Node* node) {
    return node->use_edges();
  }

  static Node* EdgeTo(UseEdge* edge) { return edge->from(); }

  static bool ShouldVisit(const Function* function, Node* node) {
    return node->IsControl();
  }

  static Node* StartNodeOf(const Function* function) {
    return function->entry_node();
  }
};

bool IsEmptyBlock(const Node* last_node) {
  DCHECK(last_node->IsBlockEnd()) << *last_node;
  auto const merge_node = last_node->input(0)->as<PhiOwnerNode>();
  if (!merge_node)
    return false;
  return !merge_node->effect_phi() && merge_node->phi_nodes().empty();
}

// Returns true if a block is empty and ends with |IfNode|.
bool CanHoistBranch(const Node* first_node) {
  DCHECK(first_node->IsBlockStart()) << *first_node;
  auto const last_node = first_node->SelectUserIfOne();
  if (!last_node || !last_node->IsBlockEnd())
    return false;
  return last_node->opcode() == Opcode::If && IsEmptyBlock(last_node);
}

}  // namespace

CleanPass::CleanPass(Editor* editor)
    : api::Pass(editor->pass_controller()), changed_(false), editor_(*editor) {
}

CleanPass::~CleanPass() {
}

void CleanPass::Clean() {
  DepthFirstTraversal<PostOrderControlFlow, const Function> walker;
  NodeCollector collector;
  walker.Traverse(editor_.function(), &collector);
  DVLOG(1) << "# of control nodes is " << collector.nodes().size();

  // Process successors before processing |Node|.
  for (auto const& node : collector.nodes()) {
    switch (node->opcode()) {
      case Opcode::If:
        CleanIf(node);
        break;
      case Opcode::Jump:
        CleanJump(node);
        break;
    }
  }
  DCHECK(editor_.Validate()) << editor_;
}

void CleanPass::CleanIf(Node* if_node) {
  auto const true_start = if_node->SelectUser(Opcode::IfTrue);
  auto const true_end = true_start->SelectUserIfOne();
  if (!true_end || !true_end->IsBlockEnd())
    return;
  auto const false_start = if_node->SelectUser(Opcode::IfFalse);
  auto const false_end = false_start->SelectUserIfOne()->as<Control>();
  if (!false_end || !false_end->IsBlockEnd() ||
      false_end->opcode() != true_end->opcode()) {
    return;
  }

  if (true_end->opcode() == Opcode::Jump) {
    // Fold a redundant branch
    auto const merge_node = true_end->SelectUserIfOne()->as<PhiOwnerNode>();
    if (!merge_node || merge_node != false_end->SelectUserIfOne())
      return;
    WillChangeControlFlow("Fold a branch", if_node);
    editor_.ChangeInput(true_end, 0, if_node->input(0));
    editor_.RemoveControlInput(merge_node, false_end);
    DidChangeControlFlow("Fold a branch", if_node);
    CleanJump(true_end);
    return;
  }

  if (true_end->opcode() != Opcode::Ret ||
      true_end->input(1) != false_end->input(1)) {
    return;
  }
  // TODO(eval1749) We should have |SelectUser| for conditional assignment.
  if (true_end->input(2) != false_end->input(2))
    return;
  // True and false blocks return same value.
  WillChangeControlFlow("Combine ret", if_node);
  editor_.ChangeInput(true_end, 0, if_node->input(0));
  DidChangeControlFlow("Combine ret", if_node);
}

void CleanPass::CleanJump(Node* jump_node) {
  auto const target = jump_node->SelectUserIfOne()->as<PhiOwnerNode>();
  if (!target)
    return;
  auto const control = jump_node->input(0);
  if (IsEmptyBlock(jump_node)) {
    // Remove an empty block
    DCHECK(control->is<PhiOwnerNode>()) << *control;
    WillChangeControlFlow("Remove an empty block", control);
    for (auto const predecessor : control->inputs()) {
      auto const it = std::find(target->inputs().begin(),
                                target->inputs().end(), predecessor);
      if (it != target->inputs().end())
        continue;
      editor_.AppendInput(target, predecessor);
    }
    DidChangeControlFlow("Remove an empty block", target);
  }
  if (target->CountInputs() != 1)
    return;

  // Combine blocks
  WillChangeControlFlow("Combine blocks", target);
  if (auto const effect_phi = target->effect_phi()) {
    editor_.ReplaceAllUses(effect_phi->input(0), effect_phi);
    editor_.Discard(effect_phi);
  }
  for (auto const phi : target->phi_nodes()) {
    editor_.ReplaceAllUses(phi->input(0), phi);
    editor_.Discard(phi);
  }
  editor_.ReplaceAllUses(control, target);
  editor_.Discard(target);
  editor_.Discard(jump_node);
  DidChangeControlFlow("Combine blocks", control);
}

void CleanPass::DidChangeControlFlow(base::StringPiece message,
                                     const Node* node) {
  DVLOG(1) << "After " << message << ": " << *node;
  changed_ = true;
}

void CleanPass::Run() {
  RunScope scope(this);
  if (scope.IsStop())
    return;
  do {
    pass_controller()->DidStartPass(this);
    changed_ = false;
    Clean();
    pass_controller()->DidEndPass(this);
  } while (changed_);
}

void CleanPass::WillChangeControlFlow(base::StringPiece message,
                                      const Node* node) {
  DVLOG(1) << "Before " << message << ": " << *node;
  changed_ = true;
}

// api::Pass
base::StringPiece CleanPass::name() const {
  return "clean";
}

void CleanPass::DumpBeforePass(const api::PassDumpContext& context) {
  auto& ostream = *context.ostream;
  if (context.IsGraph()) {
    ostream << AsGraphviz(editor_.function());
    return;
  }
  ostream << AsReversePostOrder(editor_.function());
}

void CleanPass::DumpAfterPass(const api::PassDumpContext& context) {
  auto& ostream = *context.ostream;
  if (context.IsGraph()) {
    ostream << AsGraphviz(editor_.function());
    return;
  }
  ostream << AsReversePostOrder(editor_.function());
}

}  // namespace optimizer
}  // namespace elang
<commit_msg>elang/optimizer/transforms: Get rid of unused function |CanHostBranch()| in |CleanPass|.<commit_after>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "elang/optimizer/transforms/clean_pass.h"

#include "elang/api/pass_controller.h"
#include "elang/optimizer/depth_first_traversal.h"
#include "elang/optimizer/editor.h"
#include "elang/optimizer/formatters/graphviz_formatter.h"
#include "elang/optimizer/formatters/text_formatter.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/opcode.h"

namespace elang {
namespace optimizer {

namespace {

// Collects nodes ending block.
class NodeCollector final : public NodeVisitor {
 public:
  NodeCollector() {}
  ~NodeCollector() = default;

  const std::vector<Node*>& nodes() const { return nodes_; }

 private:
  void DoDefaultVisit(Node* node) final {
    auto const opcode = node->opcode();
    if (opcode != Opcode::If && opcode != Opcode::Jump)
      return;
    nodes_.push_back(node);
  }

  std::vector<Node*> nodes_;

  DISALLOW_COPY_AND_ASSIGN(NodeCollector);
};

struct PostOrderControlFlow {
  static const UseEdges& AdjacentEdgesOf(const Function* function,
                                            Node* node) {
    return node->use_edges();
  }

  static Node* EdgeTo(UseEdge* edge) { return edge->from(); }

  static bool ShouldVisit(const Function* function, Node* node) {
    return node->IsControl();
  }

  static Node* StartNodeOf(const Function* function) {
    return function->entry_node();
  }
};

bool IsEmptyBlock(const Node* last_node) {
  DCHECK(last_node->IsBlockEnd()) << *last_node;
  auto const merge_node = last_node->input(0)->as<PhiOwnerNode>();
  if (!merge_node)
    return false;
  return !merge_node->effect_phi() && merge_node->phi_nodes().empty();
}

}  // namespace

CleanPass::CleanPass(Editor* editor)
    : api::Pass(editor->pass_controller()), changed_(false), editor_(*editor) {
}

CleanPass::~CleanPass() {
}

void CleanPass::Clean() {
  DepthFirstTraversal<PostOrderControlFlow, const Function> walker;
  NodeCollector collector;
  walker.Traverse(editor_.function(), &collector);
  DVLOG(1) << "# of control nodes is " << collector.nodes().size();

  // Process successors before processing |Node|.
  for (auto const& node : collector.nodes()) {
    switch (node->opcode()) {
      case Opcode::If:
        CleanIf(node);
        break;
      case Opcode::Jump:
        CleanJump(node);
        break;
    }
  }
  DCHECK(editor_.Validate()) << editor_;
}

void CleanPass::CleanIf(Node* if_node) {
  auto const true_start = if_node->SelectUser(Opcode::IfTrue);
  auto const true_end = true_start->SelectUserIfOne();
  if (!true_end || !true_end->IsBlockEnd())
    return;
  auto const false_start = if_node->SelectUser(Opcode::IfFalse);
  auto const false_end = false_start->SelectUserIfOne()->as<Control>();
  if (!false_end || !false_end->IsBlockEnd() ||
      false_end->opcode() != true_end->opcode()) {
    return;
  }

  if (true_end->opcode() == Opcode::Jump) {
    // Fold a redundant branch
    auto const merge_node = true_end->SelectUserIfOne()->as<PhiOwnerNode>();
    if (!merge_node || merge_node != false_end->SelectUserIfOne())
      return;
    WillChangeControlFlow("Fold a branch", if_node);
    editor_.ChangeInput(true_end, 0, if_node->input(0));
    editor_.RemoveControlInput(merge_node, false_end);
    DidChangeControlFlow("Fold a branch", if_node);
    CleanJump(true_end);
    return;
  }

  if (true_end->opcode() != Opcode::Ret ||
      true_end->input(1) != false_end->input(1)) {
    return;
  }
  // TODO(eval1749) We should have |SelectUser| for conditional assignment.
  if (true_end->input(2) != false_end->input(2))
    return;
  // True and false blocks return same value.
  WillChangeControlFlow("Combine ret", if_node);
  editor_.ChangeInput(true_end, 0, if_node->input(0));
  DidChangeControlFlow("Combine ret", if_node);
}

void CleanPass::CleanJump(Node* jump_node) {
  auto const target = jump_node->SelectUserIfOne()->as<PhiOwnerNode>();
  if (!target)
    return;
  auto const control = jump_node->input(0);
  if (IsEmptyBlock(jump_node)) {
    // Remove an empty block
    DCHECK(control->is<PhiOwnerNode>()) << *control;
    WillChangeControlFlow("Remove an empty block", control);
    for (auto const predecessor : control->inputs()) {
      auto const it = std::find(target->inputs().begin(),
                                target->inputs().end(), predecessor);
      if (it != target->inputs().end())
        continue;
      editor_.AppendInput(target, predecessor);
    }
    DidChangeControlFlow("Remove an empty block", target);
  }
  if (target->CountInputs() != 1)
    return;

  // Combine blocks
  WillChangeControlFlow("Combine blocks", target);
  if (auto const effect_phi = target->effect_phi()) {
    editor_.ReplaceAllUses(effect_phi->input(0), effect_phi);
    editor_.Discard(effect_phi);
  }
  for (auto const phi : target->phi_nodes()) {
    editor_.ReplaceAllUses(phi->input(0), phi);
    editor_.Discard(phi);
  }
  editor_.ReplaceAllUses(control, target);
  editor_.Discard(target);
  editor_.Discard(jump_node);
  DidChangeControlFlow("Combine blocks", control);
}

void CleanPass::DidChangeControlFlow(base::StringPiece message,
                                     const Node* node) {
  DVLOG(1) << "After " << message << ": " << *node;
  changed_ = true;
}

void CleanPass::Run() {
  RunScope scope(this);
  if (scope.IsStop())
    return;
  do {
    pass_controller()->DidStartPass(this);
    changed_ = false;
    Clean();
    pass_controller()->DidEndPass(this);
  } while (changed_);
}

void CleanPass::WillChangeControlFlow(base::StringPiece message,
                                      const Node* node) {
  DVLOG(1) << "Before " << message << ": " << *node;
  changed_ = true;
}

// api::Pass
base::StringPiece CleanPass::name() const {
  return "clean";
}

void CleanPass::DumpBeforePass(const api::PassDumpContext& context) {
  auto& ostream = *context.ostream;
  if (context.IsGraph()) {
    ostream << AsGraphviz(editor_.function());
    return;
  }
  ostream << AsReversePostOrder(editor_.function());
}

void CleanPass::DumpAfterPass(const api::PassDumpContext& context) {
  auto& ostream = *context.ostream;
  if (context.IsGraph()) {
    ostream << AsGraphviz(editor_.function());
    return;
  }
  ostream << AsReversePostOrder(editor_.function());
}

}  // namespace optimizer
}  // namespace elang
<|endoftext|>


<commit_before>#ifndef _VERTEX_HPP_
#define _VERTEX_HPP_
#include <iostream>
#include "Arc.hpp"

template<class T, class C>
class Graph;

template<class T, class C>
class Arc;

template<class T, class C>
class Vertex
{
    private:
        friend class Graph<T,C>;
        T key;
        Arc<T,C>* ady;
        Vertex* next;

    public:
        Vertex() : ady(NULL), next(NULL) { };
        Vertex(T info) : key(info), ady(NULL), next(NULL) { };
        ~Vertex();

        T getKey() const { return key; };
        Vertex* getNext() const { return next; };

        void setKey(T k) { key = k; };
        void setNext(Vertex* p) { next = p; };

        void insertArc(Vertex*, C);

};

template<class T, class C>
void Vertex<T,C>::insertArc(Vertex *w, C cost)
{
    if (this != w)
    {
        Arc<T,C> *pivot = this->ady;
        Arc<T,C> *pivotL = NULL;
        bool connected = false;

        while (pivot != NULL && !connected)
        {
            connected = (pivot->getKey() == w->getKey());
            pivotL = pivot;
            pivot = pivot->getNext();
        }

        if (!connected)
        {
            if (!pivotL && !pivot)
            {
                pivot = this->ady;
                Arc<T,C> *v;
                v = new Arc<T,C>();
                v->setCost(cost);
                v->setVertex(w);
                v->setNext(pivot);
                this->ady = v;
            }
            else
                pivotL->setNext(new Arc<T,C>(cost, w, NULL));
        }
    }
}

#endif
<commit_msg>Destructor<commit_after>#ifndef _VERTEX_HPP_
#define _VERTEX_HPP_
#include <iostream>
#include "Arc.hpp"

template<class T, class C>
class Graph;

template<class T, class C>
class Arc;

template<class T, class C>
class Vertex
{
    private:
        friend class Graph<T,C>;
        T key;
        Arc<T,C>* ady;
        Vertex* next;

    public:
        Vertex() : ady(NULL), next(NULL) { };
        Vertex(T info) : key(info), ady(NULL), next(NULL) { };
        ~Vertex();

        T getKey() const { return key; };
        Vertex* getNext() const { return next; };

        void setKey(T k) { key = k; };
        void setNext(Vertex* p) { next = p; };

        void insertArc(Vertex*, C);

};

template<class T, class C>
Vertex<T,C>::~Vertex()
{
    Arc<T,C> *p;
    while (ady)
    {
        p = ady;
        ayd = p->getNext();
        delete p;

    }
}

template<class T, class C>
void Vertex<T,C>::insertArc(Vertex *w, C cost)
{
    if (this != w)
    {
        Arc<T,C> *pivot = this->ady;
        Arc<T,C> *pivotL = NULL;
        bool connected = false;

        while (pivot != NULL && !connected)
        {
            connected = (pivot->getKey() == w->getKey());
            pivotL = pivot;
            pivot = pivot->getNext();
        }

        if (!connected)
        {
            if (!pivotL && !pivot)
            {
                pivot = this->ady;
                Arc<T,C> *v;
                v = new Arc<T,C>();
                v->setCost(cost);
                v->setVertex(w);
                v->setNext(pivot);
                this->ady = v;
            }
            else
                pivotL->setNext(new Arc<T,C>(cost, w, NULL));
        }
    }
}

#endif
<|endoftext|>