<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "nextpnr.h"

NEXTPNR_NAMESPACE_BEGIN

class Ecp5GlobalRouter
{
  public:
    Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};

    PipId find_tap_pip(WireId tile_glb)
    {
        std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
        std::string glbName = wireName.substr(2);
        TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
        WireId tap_wire;
        Location tap_loc;
        tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
        tap_loc.y = tile_glb.location.y;
        if (td == TAP_DIR_LEFT) {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
        } else {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
        }
        return *(ctx->getPipsUphill(tap_wire).begin());
    }

  private:
    Context *ctx;
};

void route_ecp5_globals(Context *ctx);

NEXTPNR_NAMESPACE_END
<commit_msg>ecp5: Clock usage counter function<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "nextpnr.h"
#include <algorithm>

NEXTPNR_NAMESPACE_BEGIN

class Ecp5GlobalRouter
{
  public:
    Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};
  private:

    bool is_clock_port(const PortRef &user) {
        if (user.cell->type == ctx->id("TRELLIS_LC") && user.port == ctx->id("CLK"))
            return true;
        return false;
    }

    std::vector<NetInfo*> get_clocks()
    {
        std::unordered_map<IdString, int> clockCount;
        for (auto &net : ctx->nets) {
            NetInfo *ni = net.second.get();
            clockCount[ni->name] = 0;
            for (const auto &user : ni->users) {
                if (is_clock_port(user))
                    clockCount[ni->name]++;
            }
        }
        std::vector<NetInfo*> clocks;
        while (clocks.size() < 16) {
            auto max = std::max_element(clockCount.begin(), clockCount.end(), [](
                    const decltype(clockCount)::value_type &a, const decltype(clockCount)::value_type &b
                    ) {
                return a.second < b.second;
            });
            if (max == clockCount.end() || max->second < 3)
                break;
            clocks.push_back(ctx->nets.at(max->first).get());
            clockCount.erase(max->first);
        }
        return clocks;
    }

    PipId find_tap_pip(WireId tile_glb)
    {
        std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
        std::string glbName = wireName.substr(2);
        TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
        WireId tap_wire;
        Location tap_loc;
        tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
        tap_loc.y = tile_glb.location.y;
        if (td == TAP_DIR_LEFT) {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
        } else {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
        }
        return *(ctx->getPipsUphill(tap_wire).begin());
    }

    Context *ctx;
};

void route_ecp5_globals(Context *ctx);

NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsReceiverControlBlock class implementation
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-20
 */

#include "distortos/synchronization/SignalsReceiverControlBlock.hpp"

#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

#include "distortos/SignalsCatcher.hpp"
#include "distortos/SignalInformationQueueWrapper.hpp"

#include <cerrno>

namespace distortos
{

namespace synchronization
{

/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/

SignalsReceiverControlBlock::SignalsReceiverControlBlock(SignalInformationQueueWrapper* const
		signalInformationQueueWrapper, SignalsCatcher* const signalsCatcher) :
		pendingSignalSet_{SignalSet::empty},
		waitingSignalSet_{},
		signalsCatcherControlBlock_{signalsCatcher != nullptr ? &signalsCatcher->signalsCatcherControlBlock_ : nullptr},
		signalInformationQueue_
		{
				signalInformationQueueWrapper != nullptr ? &signalInformationQueueWrapper->signalInformationQueue_ :
						nullptr
		}
{

}

std::pair<int, SignalInformation> SignalsReceiverControlBlock::acceptPendingSignal(const uint8_t signalNumber)
{
	if (signalInformationQueue_ != nullptr)
	{
		const auto acceptQueuedSignalResult = signalInformationQueue_->acceptQueuedSignal(signalNumber);
		if (acceptQueuedSignalResult.first != EAGAIN)	// signal was accepted or fatal error?
			return acceptQueuedSignalResult;
	}

	const auto testResult = pendingSignalSet_.test(signalNumber);
	if (testResult.first != 0)
		return {testResult.first, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}};
	if (testResult.second == false)
		return {EAGAIN, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}};
	const auto ret = pendingSignalSet_.remove(signalNumber);
	return {ret, SignalInformation{signalNumber, SignalInformation::Code::Generated, sigval{}}};
}

int SignalsReceiverControlBlock::generateSignal(const uint8_t signalNumber,
		const scheduler::ThreadControlBlock& threadControlBlock)
{
	architecture::InterruptMaskingLock interruptMaskingLock;

	const auto ret = pendingSignalSet_.add(signalNumber);
	if (ret != 0)
		return ret;

	return postGenerate(signalNumber, threadControlBlock);
}

SignalSet SignalsReceiverControlBlock::getPendingSignalSet() const
{
	const auto pendingSignalSet = pendingSignalSet_;
	if (signalInformationQueue_ == nullptr)
		return pendingSignalSet;

	const auto queuedSignalSet = signalInformationQueue_->getQueuedSignalSet();
	return SignalSet{pendingSignalSet.getBitset() | queuedSignalSet.getBitset()};
}

SignalSet SignalsReceiverControlBlock::getSignalMask() const
{
	if (signalsCatcherControlBlock_ == nullptr)
		return SignalSet{SignalSet::full};

	return signalsCatcherControlBlock_->getSignalMask();
}

int SignalsReceiverControlBlock::queueSignal(const uint8_t signalNumber, const sigval value,
		const scheduler::ThreadControlBlock& threadControlBlock) const
{
	if (signalInformationQueue_ == nullptr)
		return ENOTSUP;

	architecture::InterruptMaskingLock interruptMaskingLock;

	const auto ret = signalInformationQueue_->queueSignal(signalNumber, value);
	if (ret != 0)
		return ret;

	return postGenerate(signalNumber, threadControlBlock);
}

int SignalsReceiverControlBlock::setSignalMask(const SignalSet signalMask)
{
	if (signalsCatcherControlBlock_ == nullptr)
		return ENOTSUP;

	signalsCatcherControlBlock_->setSignalMask(signalMask);
	return 0;
}

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

int SignalsReceiverControlBlock::postGenerate(const uint8_t signalNumber,
		const scheduler::ThreadControlBlock& threadControlBlock) const
{
	if (waitingSignalSet_ == nullptr)
		return 0;

	const auto testResult = waitingSignalSet_->test(signalNumber);
	if (testResult.first != 0)
		return testResult.first;
	if (testResult.second == false)	// signalNumber is not "waited for"?
		return 0;

	scheduler::getScheduler().unblock(threadControlBlock.getIterator());
	return 0;
}

}	// namespace synchronization

}	// namespace distortos
<commit_msg>SignalsReceiverControlBlock::postGenerate(): remove the check for validity of signalNumber argument - it is checked by all callers of this function<commit_after>/**
 * \file
 * \brief SignalsReceiverControlBlock class implementation
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-23
 */

#include "distortos/synchronization/SignalsReceiverControlBlock.hpp"

#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

#include "distortos/SignalsCatcher.hpp"
#include "distortos/SignalInformationQueueWrapper.hpp"

#include <cerrno>

namespace distortos
{

namespace synchronization
{

/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/

SignalsReceiverControlBlock::SignalsReceiverControlBlock(SignalInformationQueueWrapper* const
		signalInformationQueueWrapper, SignalsCatcher* const signalsCatcher) :
		pendingSignalSet_{SignalSet::empty},
		waitingSignalSet_{},
		signalsCatcherControlBlock_{signalsCatcher != nullptr ? &signalsCatcher->signalsCatcherControlBlock_ : nullptr},
		signalInformationQueue_
		{
				signalInformationQueueWrapper != nullptr ? &signalInformationQueueWrapper->signalInformationQueue_ :
						nullptr
		}
{

}

std::pair<int, SignalInformation> SignalsReceiverControlBlock::acceptPendingSignal(const uint8_t signalNumber)
{
	if (signalInformationQueue_ != nullptr)
	{
		const auto acceptQueuedSignalResult = signalInformationQueue_->acceptQueuedSignal(signalNumber);
		if (acceptQueuedSignalResult.first != EAGAIN)	// signal was accepted or fatal error?
			return acceptQueuedSignalResult;
	}

	const auto testResult = pendingSignalSet_.test(signalNumber);
	if (testResult.first != 0)
		return {testResult.first, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}};
	if (testResult.second == false)
		return {EAGAIN, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}};
	const auto ret = pendingSignalSet_.remove(signalNumber);
	return {ret, SignalInformation{signalNumber, SignalInformation::Code::Generated, sigval{}}};
}

int SignalsReceiverControlBlock::generateSignal(const uint8_t signalNumber,
		const scheduler::ThreadControlBlock& threadControlBlock)
{
	architecture::InterruptMaskingLock interruptMaskingLock;

	const auto ret = pendingSignalSet_.add(signalNumber);
	if (ret != 0)
		return ret;

	return postGenerate(signalNumber, threadControlBlock);
}

SignalSet SignalsReceiverControlBlock::getPendingSignalSet() const
{
	const auto pendingSignalSet = pendingSignalSet_;
	if (signalInformationQueue_ == nullptr)
		return pendingSignalSet;

	const auto queuedSignalSet = signalInformationQueue_->getQueuedSignalSet();
	return SignalSet{pendingSignalSet.getBitset() | queuedSignalSet.getBitset()};
}

SignalSet SignalsReceiverControlBlock::getSignalMask() const
{
	if (signalsCatcherControlBlock_ == nullptr)
		return SignalSet{SignalSet::full};

	return signalsCatcherControlBlock_->getSignalMask();
}

int SignalsReceiverControlBlock::queueSignal(const uint8_t signalNumber, const sigval value,
		const scheduler::ThreadControlBlock& threadControlBlock) const
{
	if (signalInformationQueue_ == nullptr)
		return ENOTSUP;

	architecture::InterruptMaskingLock interruptMaskingLock;

	const auto ret = signalInformationQueue_->queueSignal(signalNumber, value);
	if (ret != 0)
		return ret;

	return postGenerate(signalNumber, threadControlBlock);
}

int SignalsReceiverControlBlock::setSignalMask(const SignalSet signalMask)
{
	if (signalsCatcherControlBlock_ == nullptr)
		return ENOTSUP;

	signalsCatcherControlBlock_->setSignalMask(signalMask);
	return 0;
}

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

int SignalsReceiverControlBlock::postGenerate(const uint8_t signalNumber,
		const scheduler::ThreadControlBlock& threadControlBlock) const
{
	/// \todo add some form of assertion for validity of \a signalNumber

	if (waitingSignalSet_ == nullptr)
		return 0;

	const auto testResult = waitingSignalSet_->test(signalNumber);
	if (testResult.second == false)	// signalNumber is not "waited for"?
		return 0;

	scheduler::getScheduler().unblock(threadControlBlock.getIterator());
	return 0;
}

}	// namespace synchronization

}	// namespace distortos
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * highlighter.cpp
 *
 * QTextEdit highlighter
 */

#include <QtGui>
#include "highlighter.h"

WorkerThread::~WorkerThread()
{
    if (result != NULL)
        pmh_free_elements(result);
    free(content);
}
void WorkerThread::run()
{
    if (content == NULL)
        return;
    pmh_markdown_to_elements(content, pmh_EXT_NONE, &result);
}

QMarkdownHighlighter::QMarkdownHighlighter(QTextDocument *parent,
                                             int aWaitInterval) : QObject(parent)
{
    highlightingStyles = NULL;
    workerThread = NULL;
    cached_elements = NULL;
    waitInterval = aWaitInterval;
    timer = new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(aWaitInterval);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerTimeout()));
    document = parent;
    connect(document, SIGNAL(contentsChange(int,int,int)),
            this, SLOT(handleContentsChange(int,int,int)));

    this->parse();
}

void QMarkdownHighlighter::setStyles(QVector<HighlightingStyle> &styles)
{
    this->highlightingStyles = &styles;
}

#define STY(type, format) styles->append((HighlightingStyle){type, format})
void QMarkdownHighlighter::setDefaultStyles(int defaultFontSize)
{
    QVector<HighlightingStyle> *styles = new QVector<HighlightingStyle>();

    QTextCharFormat headers; headers.setForeground(QBrush(QColor(0,49,110)));
    headers.setBackground(QBrush(QColor(230,230,240)));
    headers.setFontWeight(QFont::Bold);
    headers.setFontPointSize(defaultFontSize * 1.2);
    STY(pmh_H1, headers);

    headers.setFontPointSize(defaultFontSize * 1.1);
    STY(pmh_H2, headers);

    headers.setFontPointSize(defaultFontSize);
    STY(pmh_H3, headers);
    STY(pmh_H4, headers);
    STY(pmh_H5, headers);
    STY(pmh_H6, headers);

    QTextCharFormat hrule; hrule.setForeground(QBrush(Qt::darkGray));
    hrule.setBackground(QBrush(Qt::lightGray));
    STY(pmh_HRULE, hrule);

    /* <ul> */
    QTextCharFormat list; list.setForeground(QBrush(QColor(163,0,123)));
    STY(pmh_LIST_BULLET, list);
    STY(pmh_LIST_ENUMERATOR, list);

    /* <a href> */
    QTextCharFormat link; link.setForeground(QBrush(QColor(255,128,0)));
    link.setBackground(QBrush(QColor(255,233,211)));
    STY(pmh_LINK, link);
    STY(pmh_AUTO_LINK_URL, link);
    STY(pmh_AUTO_LINK_EMAIL, link);

    /* <img> */
    QTextCharFormat image; image.setForeground(QBrush(QColor(0,191,0)));
    image.setBackground(QBrush(QColor(228,255,228)));
    STY(pmh_IMAGE, image);

    QTextCharFormat ref; ref.setForeground(QBrush(QColor(213,178,178)));
    STY(pmh_REFERENCE, ref);

    /* <pre> */
    QTextCharFormat code; code.setForeground(QBrush(Qt::darkGreen));
    code.setBackground(QBrush(QColor(217,231,217)));
    code.setFontFamily("Monospace");
    STY(pmh_CODE, code);
    STY(pmh_VERBATIM, code);

    /* <em> */
    QTextCharFormat emph; emph.setForeground(QBrush(QColor(0,87,174)));
    emph.setFontItalic(true);
    STY(pmh_EMPH, emph);

    /* <strong> */
    QTextCharFormat strong; strong.setForeground(QBrush(QColor(0,66,138)));
    strong.setFontWeight(QFont::Bold);
    STY(pmh_STRONG, strong);

    QTextCharFormat comment; comment.setForeground(QBrush(Qt::gray));
    STY(pmh_COMMENT, comment);

    QTextCharFormat blockquote; blockquote.setForeground(QBrush(Qt::darkRed));
    STY(pmh_BLOCKQUOTE, blockquote);

    this->setStyles(*styles);
}

void QMarkdownHighlighter::clearFormatting()
{
    QTextBlock block = document->firstBlock();
    while (block.isValid()) {
        block.layout()->clearAdditionalFormats();
        block = block.next();
    }
}

void QMarkdownHighlighter::highlight()
{
    if (cached_elements == NULL) {
        qDebug() << "cached_elements is NULL";
        return;
    }

    if (highlightingStyles == NULL)
        this->setDefaultStyles();

    this->clearFormatting();

    for (int i = 0; i < highlightingStyles->size(); i++)
    {
        HighlightingStyle style = highlightingStyles->at(i);
        pmh_element *elem_cursor = cached_elements[style.type];
        while (elem_cursor != NULL)
        {
            if (elem_cursor->end <= elem_cursor->pos) {
                elem_cursor = elem_cursor->next;
                continue;
            }

            // "The QTextLayout object can only be modified from the
            // documentChanged implementation of a QAbstractTextDocumentLayout
            // subclass. Any changes applied from the outside cause undefined
            // behavior." -- we are breaking this rule here. There might be
            // a better (more correct) way to do this.

            int startBlockNum = document->findBlock(elem_cursor->pos).blockNumber();
            int endBlockNum = document->findBlock(elem_cursor->end).blockNumber();
            for (int j = startBlockNum; j <= endBlockNum; j++)
            {
                QTextBlock block = document->findBlockByNumber(j);

                QTextLayout *layout = block.layout();
                QList<QTextLayout::FormatRange> list = layout->additionalFormats();
                int blockpos = block.position();
                QTextLayout::FormatRange r;
                r.format = style.format;

                if (j == startBlockNum) {
                    r.start = elem_cursor->pos - blockpos;
                    r.length = (startBlockNum == endBlockNum)
                                ? elem_cursor->end - elem_cursor->pos
                                : block.length() - r.start;
                } else if (j == endBlockNum) {
                    r.start = 0;
                    r.length = elem_cursor->end - blockpos;
                } else {
                    r.start = 0;
                    r.length = block.length();
                }

                list.append(r);
                layout->setAdditionalFormats(list);
            }

            elem_cursor = elem_cursor->next;
        }
    }

    document->markContentsDirty(0, document->characterCount());
}

void QMarkdownHighlighter::parse()
{
    if (workerThread != NULL && workerThread->isRunning()) {
        parsePending = true;
        return;
    }

    QString content = document->toPlainText();
    QByteArray ba = content.toLatin1();
    char *content_cstring = strdup((char *)ba.data());

    if (workerThread != NULL)
        delete workerThread;
    workerThread = new WorkerThread();
    workerThread->content = content_cstring;
    connect(workerThread, SIGNAL(finished()), this, SLOT(threadFinished()));
    parsePending = false;
    workerThread->start();
}

void QMarkdownHighlighter::threadFinished()
{
    if (parsePending) {
        this->parse();
        return;
    }

    if (cached_elements != NULL)
        pmh_free_elements(cached_elements);
    cached_elements = workerThread->result;
    workerThread->result = NULL;

    this->highlight();
}

void QMarkdownHighlighter::handleContentsChange(int position, int charsRemoved,
                                                 int charsAdded)
{
    if (charsRemoved == 0 && charsAdded == 0)
        return;
    //qDebug() << "contents changed. chars removed/added:" << charsRemoved << charsAdded;
    timer->stop();
    timer->start();
}

void QMarkdownHighlighter::timerTimeout()
{
    this->parse();
}
<commit_msg>switched code font to `Courier`<commit_after>/*
 * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * highlighter.cpp
 *
 * QTextEdit highlighter
 */

#include <QtGui>
#include "highlighter.h"

WorkerThread::~WorkerThread()
{
    if (result != NULL)
        pmh_free_elements(result);
    free(content);
}
void WorkerThread::run()
{
    if (content == NULL)
        return;
    pmh_markdown_to_elements(content, pmh_EXT_NONE, &result);
}

QMarkdownHighlighter::QMarkdownHighlighter(QTextDocument *parent,
                                             int aWaitInterval) : QObject(parent)
{
    highlightingStyles = NULL;
    workerThread = NULL;
    cached_elements = NULL;
    waitInterval = aWaitInterval;
    timer = new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(aWaitInterval);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerTimeout()));
    document = parent;
    connect(document, SIGNAL(contentsChange(int,int,int)),
            this, SLOT(handleContentsChange(int,int,int)));

    this->parse();
}

void QMarkdownHighlighter::setStyles(QVector<HighlightingStyle> &styles)
{
    this->highlightingStyles = &styles;
}

#define STY(type, format) styles->append((HighlightingStyle){type, format})
void QMarkdownHighlighter::setDefaultStyles(int defaultFontSize)
{
    QVector<HighlightingStyle> *styles = new QVector<HighlightingStyle>();

    QTextCharFormat headers; headers.setForeground(QBrush(QColor(0,49,110)));
    headers.setBackground(QBrush(QColor(230,230,240)));
    headers.setFontWeight(QFont::Bold);
    headers.setFontPointSize(defaultFontSize * 1.2);
    STY(pmh_H1, headers);

    headers.setFontPointSize(defaultFontSize * 1.1);
    STY(pmh_H2, headers);

    headers.setFontPointSize(defaultFontSize);
    STY(pmh_H3, headers);
    STY(pmh_H4, headers);
    STY(pmh_H5, headers);
    STY(pmh_H6, headers);

    QTextCharFormat hrule; hrule.setForeground(QBrush(Qt::darkGray));
    hrule.setBackground(QBrush(Qt::lightGray));
    STY(pmh_HRULE, hrule);

    /* <ul> */
    QTextCharFormat list; list.setForeground(QBrush(QColor(163,0,123)));
    STY(pmh_LIST_BULLET, list);
    STY(pmh_LIST_ENUMERATOR, list);

    /* <a href> */
    QTextCharFormat link; link.setForeground(QBrush(QColor(255,128,0)));
    link.setBackground(QBrush(QColor(255,233,211)));
    STY(pmh_LINK, link);
    STY(pmh_AUTO_LINK_URL, link);
    STY(pmh_AUTO_LINK_EMAIL, link);

    /* <img> */
    QTextCharFormat image; image.setForeground(QBrush(QColor(0,191,0)));
    image.setBackground(QBrush(QColor(228,255,228)));
    STY(pmh_IMAGE, image);

    QTextCharFormat ref; ref.setForeground(QBrush(QColor(213,178,178)));
    STY(pmh_REFERENCE, ref);

    /* <pre> */
    QTextCharFormat code; code.setForeground(QBrush(Qt::darkGreen));
    code.setBackground(QBrush(QColor(217,231,217)));
    code.setFontFamily("Courier");
    STY(pmh_CODE, code);
    STY(pmh_VERBATIM, code);

    /* <em> */
    QTextCharFormat emph; emph.setForeground(QBrush(QColor(0,87,174)));
    emph.setFontItalic(true);
    STY(pmh_EMPH, emph);

    /* <strong> */
    QTextCharFormat strong; strong.setForeground(QBrush(QColor(0,66,138)));
    strong.setFontWeight(QFont::Bold);
    STY(pmh_STRONG, strong);

    QTextCharFormat comment; comment.setForeground(QBrush(Qt::gray));
    STY(pmh_COMMENT, comment);

    QTextCharFormat blockquote; blockquote.setForeground(QBrush(Qt::darkRed));
    STY(pmh_BLOCKQUOTE, blockquote);

    this->setStyles(*styles);
}

void QMarkdownHighlighter::clearFormatting()
{
    QTextBlock block = document->firstBlock();
    while (block.isValid()) {
        block.layout()->clearAdditionalFormats();
        block = block.next();
    }
}

void QMarkdownHighlighter::highlight()
{
    if (cached_elements == NULL) {
        qDebug() << "cached_elements is NULL";
        return;
    }

    if (highlightingStyles == NULL)
        this->setDefaultStyles();

    this->clearFormatting();

    for (int i = 0; i < highlightingStyles->size(); i++)
    {
        HighlightingStyle style = highlightingStyles->at(i);
        pmh_element *elem_cursor = cached_elements[style.type];
        while (elem_cursor != NULL)
        {
            if (elem_cursor->end <= elem_cursor->pos) {
                elem_cursor = elem_cursor->next;
                continue;
            }

            // "The QTextLayout object can only be modified from the
            // documentChanged implementation of a QAbstractTextDocumentLayout
            // subclass. Any changes applied from the outside cause undefined
            // behavior." -- we are breaking this rule here. There might be
            // a better (more correct) way to do this.

            int startBlockNum = document->findBlock(elem_cursor->pos).blockNumber();
            int endBlockNum = document->findBlock(elem_cursor->end).blockNumber();
            for (int j = startBlockNum; j <= endBlockNum; j++)
            {
                QTextBlock block = document->findBlockByNumber(j);

                QTextLayout *layout = block.layout();
                QList<QTextLayout::FormatRange> list = layout->additionalFormats();
                int blockpos = block.position();
                QTextLayout::FormatRange r;
                r.format = style.format;

                if (j == startBlockNum) {
                    r.start = elem_cursor->pos - blockpos;
                    r.length = (startBlockNum == endBlockNum)
                                ? elem_cursor->end - elem_cursor->pos
                                : block.length() - r.start;
                } else if (j == endBlockNum) {
                    r.start = 0;
                    r.length = elem_cursor->end - blockpos;
                } else {
                    r.start = 0;
                    r.length = block.length();
                }

                list.append(r);
                layout->setAdditionalFormats(list);
            }

            elem_cursor = elem_cursor->next;
        }
    }

    document->markContentsDirty(0, document->characterCount());
}

void QMarkdownHighlighter::parse()
{
    if (workerThread != NULL && workerThread->isRunning()) {
        parsePending = true;
        return;
    }

    QString content = document->toPlainText();
    QByteArray ba = content.toLatin1();
    char *content_cstring = strdup((char *)ba.data());

    if (workerThread != NULL)
        delete workerThread;
    workerThread = new WorkerThread();
    workerThread->content = content_cstring;
    connect(workerThread, SIGNAL(finished()), this, SLOT(threadFinished()));
    parsePending = false;
    workerThread->start();
}

void QMarkdownHighlighter::threadFinished()
{
    if (parsePending) {
        this->parse();
        return;
    }

    if (cached_elements != NULL)
        pmh_free_elements(cached_elements);
    cached_elements = workerThread->result;
    workerThread->result = NULL;

    this->highlight();
}

void QMarkdownHighlighter::handleContentsChange(int position, int charsRemoved,
                                                 int charsAdded)
{
    if (charsRemoved == 0 && charsAdded == 0)
        return;
    //qDebug() << "contents changed. chars removed/added:" << charsRemoved << charsAdded;
    timer->stop();
    timer->start();
}

void QMarkdownHighlighter::timerTimeout()
{
    this->parse();
}
<|endoftext|>


<commit_before>#include "globalhandler.h"
#include "ipmid-api.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>

const char  *control_object_name  =  "/org/openbmc/control/bmc0";
const char  *control_intf_name    =  "org.openbmc.control.Bmc";

const char  *objectmapper_service_name =  "org.openbmc.objectmapper";
const char  *objectmapper_object_name  =  "/org/openbmc/objectmapper/objectmapper";
const char  *objectmapper_intf_name    =  "org.openbmc.objectmapper.ObjectMapper";

void register_netfn_global_functions() __attribute__((constructor));

int obj_mapper_get_connection(char** buf, const char* obj_path)
{
    sd_bus_error error = SD_BUS_ERROR_NULL;
    sd_bus_message *m = NULL;
    sd_bus *bus = NULL;
    char *temp_buf = NULL, *intf = NULL;
    size_t buf_size = 0;
    int r;

    //Get the system bus where most system services are provided.
    bus = ipmid_get_sd_bus_connection();

    /*
     * Bus, service, object path, interface and method are provided to call
     * the method.
     * Signatures and input arguments are provided by the arguments at the
     * end.
     */
    r = sd_bus_call_method(bus,
            objectmapper_service_name,                      /* service to contact */
            objectmapper_object_name,                       /* object path */
            objectmapper_intf_name,                         /* interface name */
            "GetObject",                                    /* method name */
            &error,                                         /* object to return error in */
            &m,                                             /* return message on success */
            "s",                                            /* input signature */
            obj_path                                        /* first argument */
            );

    if (r < 0) {
        fprintf(stderr, "Failed to issue method call: %s\n", error.message);
        goto finish;
    }

    // Get the key, aka, the connection name
    sd_bus_message_read(m, "a{sas}", 1, &temp_buf, 1, &intf);

	/*
     * TODO: check the return code. Currently for no reason the message
     * parsing of object mapper is always complaining about
     * "Device or resource busy", but the result seems OK for now. Need
     *  further checks.
     */

    buf_size = strlen(temp_buf) + 1;
    printf("IPMID connection name: %s\n", temp_buf);
    *buf = (char*)malloc(buf_size);

    if (*buf == NULL) {
        fprintf(stderr, "Malloc failed for warm reset");
        r = -1;
        goto finish;
    }

    memcpy(*buf, temp_buf, buf_size);

finish:
    sd_bus_error_free(&error);
    sd_bus_message_unref(m);

    return r;
}

int dbus_warm_reset()
{
    sd_bus_error error = SD_BUS_ERROR_NULL;
    sd_bus_message *m = NULL;
    sd_bus *bus = NULL;
    char* temp_buf = NULL;
    uint8_t* get_value = NULL;
    char* connection = NULL;
    int r, i;

    r = obj_mapper_get_connection(&connection, control_object_name);
    if (r < 0) {
        fprintf(stderr, "Failed to get connection, return value: %d.\n", r);
        goto finish;
    }

    printf("connection: %s\n", connection);

    // Open the system bus where most system services are provided.
    bus = ipmid_get_sd_bus_connection();

    /*
     * Bus, service, object path, interface and method are provided to call
     * the method.
     * Signatures and input arguments are provided by the arguments at the
     * end.
	 */
    r = sd_bus_call_method(bus,
            connection,                                /* service to contact */
            control_object_name,                       /* object path */
            control_intf_name,                         /* interface name */
            "warmReset",                               /* method name */
            &error,                                    /* object to return error in */
            &m,                                        /* return message on success */
            NULL,
            NULL
            );

    if (r < 0) {
        fprintf(stderr, "Failed to issue method call: %s\n", error.message);
        goto finish;
    }

finish:
    sd_bus_error_free(&error);
    sd_bus_message_unref(m);
    free(connection);

    return r;
}

ipmi_ret_t ipmi_global_warm_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                              ipmi_request_t request, ipmi_response_t response,
                              ipmi_data_len_t data_len, ipmi_context_t context)
{
    printf("Handling GLOBAL warmReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);

    // TODO: call the correct dbus method for warmReset.
    dbus_warm_reset();

    // Status code.
    ipmi_ret_t rc = IPMI_CC_OK;
    *data_len = 0;
    return rc;
}

ipmi_ret_t ipmi_global_wildcard_handler(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                              ipmi_request_t request, ipmi_response_t response,
                              ipmi_data_len_t data_len, ipmi_context_t context)
{
    printf("Handling WILDCARD Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);

    // Status code.
    ipmi_ret_t rc = IPMI_CC_OK;

    *data_len = strlen("THIS IS WILDCARD");

    // Now pack actual response
    memcpy(response, "THIS IS WILDCARD", *data_len);

    return rc;
}

void register_netfn_global_functions()
{
    printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WARM_RESET);
    ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL, ipmi_global_warm_reset);

    return;
}
<commit_msg>Removed the handler function of the wild card command  enter the commit message for your changes. Lines starting<commit_after>#include "globalhandler.h"
#include "ipmid-api.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>

const char  *control_object_name  =  "/org/openbmc/control/bmc0";
const char  *control_intf_name    =  "org.openbmc.control.Bmc";

const char  *objectmapper_service_name =  "org.openbmc.objectmapper";
const char  *objectmapper_object_name  =  "/org/openbmc/objectmapper/objectmapper";
const char  *objectmapper_intf_name    =  "org.openbmc.objectmapper.ObjectMapper";

void register_netfn_global_functions() __attribute__((constructor));

int obj_mapper_get_connection(char** buf, const char* obj_path)
{
    sd_bus_error error = SD_BUS_ERROR_NULL;
    sd_bus_message *m = NULL;
    sd_bus *bus = NULL;
    char *temp_buf = NULL, *intf = NULL;
    size_t buf_size = 0;
    int r;

    //Get the system bus where most system services are provided.
    bus = ipmid_get_sd_bus_connection();

    /*
     * Bus, service, object path, interface and method are provided to call
     * the method.
     * Signatures and input arguments are provided by the arguments at the
     * end.
     */
    r = sd_bus_call_method(bus,
            objectmapper_service_name,                      /* service to contact */
            objectmapper_object_name,                       /* object path */
            objectmapper_intf_name,                         /* interface name */
            "GetObject",                                    /* method name */
            &error,                                         /* object to return error in */
            &m,                                             /* return message on success */
            "s",                                            /* input signature */
            obj_path                                        /* first argument */
            );

    if (r < 0) {
        fprintf(stderr, "Failed to issue method call: %s\n", error.message);
        goto finish;
    }

    // Get the key, aka, the connection name
    sd_bus_message_read(m, "a{sas}", 1, &temp_buf, 1, &intf);

	/*
     * TODO: check the return code. Currently for no reason the message
     * parsing of object mapper is always complaining about
     * "Device or resource busy", but the result seems OK for now. Need
     *  further checks.
     */

    buf_size = strlen(temp_buf) + 1;
    printf("IPMID connection name: %s\n", temp_buf);
    *buf = (char*)malloc(buf_size);

    if (*buf == NULL) {
        fprintf(stderr, "Malloc failed for warm reset");
        r = -1;
        goto finish;
    }

    memcpy(*buf, temp_buf, buf_size);

finish:
    sd_bus_error_free(&error);
    sd_bus_message_unref(m);

    return r;
}

int dbus_warm_reset()
{
    sd_bus_error error = SD_BUS_ERROR_NULL;
    sd_bus_message *m = NULL;
    sd_bus *bus = NULL;
    char* temp_buf = NULL;
    uint8_t* get_value = NULL;
    char* connection = NULL;
    int r, i;

    r = obj_mapper_get_connection(&connection, control_object_name);
    if (r < 0) {
        fprintf(stderr, "Failed to get connection, return value: %d.\n", r);
        goto finish;
    }

    printf("connection: %s\n", connection);

    // Open the system bus where most system services are provided.
    bus = ipmid_get_sd_bus_connection();

    /*
     * Bus, service, object path, interface and method are provided to call
     * the method.
     * Signatures and input arguments are provided by the arguments at the
     * end.
	 */
    r = sd_bus_call_method(bus,
            connection,                                /* service to contact */
            control_object_name,                       /* object path */
            control_intf_name,                         /* interface name */
            "warmReset",                               /* method name */
            &error,                                    /* object to return error in */
            &m,                                        /* return message on success */
            NULL,
            NULL
            );

    if (r < 0) {
        fprintf(stderr, "Failed to issue method call: %s\n", error.message);
        goto finish;
    }

finish:
    sd_bus_error_free(&error);
    sd_bus_message_unref(m);
    free(connection);

    return r;
}

ipmi_ret_t ipmi_global_warm_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                              ipmi_request_t request, ipmi_response_t response,
                              ipmi_data_len_t data_len, ipmi_context_t context)
{
    printf("Handling GLOBAL warmReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);

    // TODO: call the correct dbus method for warmReset.
    dbus_warm_reset();

    // Status code.
    ipmi_ret_t rc = IPMI_CC_OK;
    *data_len = 0;
    return rc;
}

void register_netfn_global_functions()
{
    printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WARM_RESET);
    ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL, ipmi_global_warm_reset);

    return;
}
<|endoftext|>


<commit_before>#ifndef __elxFullSearchOptimizer_hxx
#define __elxFullSearchOptimizer_hxx

#include "elxFullSearchOptimizer.h"
#include <iomanip>
#include <sstream>
#include <string>
#include "vnl/vnl_math.h"

namespace elastix
{
using namespace itk;

	/**
	 * ********************* Constructor ****************************
	 */

	template <class TElastix>
		FullSearch<TElastix>
		::FullSearch()
	{
		this->m_OptimizationSurface = 0;

	} // end Constructor

	/**
	 * ***************** BeforeRegistration ***********************
	 */

	template <class TElastix>
		void FullSearch<TElastix>::
		BeforeRegistration(void)
	{
		/** Add the target cells "ItNr" and "Metric" to xout["iteration"].*/
		xl::xout["iteration"].AddTargetCell("2:Metric");

		/** Format the metric as floats */
		xl::xout["iteration"]["2:Metric"]		<< std::showpoint << std::fixed;

	} // end BeforeRegistration

	/**
	 * ***************** BeforeEachResolution ***********************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::BeforeEachResolution(void)
	{
		/** Get the current resolution level.*/
		unsigned int level = static_cast<unsigned int>(
			this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() );

		/**
		 * Read FullSearchRange from the parameter file
		 */

		/** declare variables */

		std::string name("");
		unsigned int param_nr = 0;
		double minimum = 0;
		double maximum = 0;
		double stepsize = 0;
		const std::string prefix = "FS";
		unsigned int entry_nr = 0;
		unsigned int nrOfSearchSpaceDimensions = 0;
		int errorcode = 0;
		int realerror = 0;
		std::ostringstream makeString("");

		/** fullFieldName = "FullSearchSpace0" at level 0; */
		makeString << "FullSearchSpace" << level;
		std::string fullFieldName = makeString.str();

		while ( errorcode==0 )  //as long as still search ranges are defined
		{
			/** Try to read (silently) from the parameter file */
			/** \todo check earlier, in BeforeAll, if the searchspace has been defined. */

			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					name, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					param_nr, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					minimum, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					maximum, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					stepsize, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}

			/** Setup this search range */
			if (!realerror && !errorcode)
			{
				/** Setup the Superclass */
				this->AddSearchDimension(param_nr, minimum, maximum, stepsize);

				/** Create name of this dimension */
				makeString.str("");
				makeString
					<< prefix
					<< ( (entry_nr / 5) - 1 )
					<< ":"
					<< name
					<< ":"
					<< param_nr;

				/** Store the name and create a column in xout["iteration"] */
				this->m_SearchSpaceDimensionNames[param_nr] = makeString.str();
				xl::xout["iteration"].AddTargetCell( makeString.str().c_str() );

				/** Format this xout iteration column as float */
				xl::xout["iteration"][ makeString.str().c_str() ]
					<< std::showpoint << std::fixed;

			} // end if (!realerror)

		} // end while

		if (!realerror)
		{
			/** The number of dimensions */
			nrOfSearchSpaceDimensions = this->GetNumberOfSearchSpaceDimensions();

			/** Create the image that will store the results of the full search. */
			this->m_OptimizationSurface =
				NDImageType::NewNDImage(nrOfSearchSpaceDimensions);
			this->m_OptimizationSurface->CreateNewImage();
			/** \todo don't do this if more than max allowable dimensions. */

			/** Set the correct size and allocate memory */
			this->m_OptimizationSurface->SetRegions(
				this->GetSearchSpaceSize()  );
			this->m_OptimizationSurface->Allocate();
			/** \todo try/catch block around Allocate? */

			/** Set the name of this image on disk. */
			std::string resultImageFormat = "mhd";
			this->m_Configuration->ReadParameter(	resultImageFormat, "ResultImageFormat", 0, true );
			makeString.str("");
			makeString
				<< this->GetConfiguration()->GetCommandLineArgument("-out")
				<< "OptimizationSurface."
				<< this->GetConfiguration()->GetElastixLevel()
				<< ".R" << level
				<< "." << resultImageFormat;
			this->m_OptimizationSurface->SetOutputFileName( makeString.str().c_str() );

			elxout
				<< "Total number of iterations needed in this resolution: "
				<< this->GetNumberOfIterations()
				<< "." << std::endl;

		} // if (!realerror)

		/** \todo else: quit program or something like that. */

	} // end BeforeEachResolution

	/**
	 * ***************** AfterEachIteration *************************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::AfterEachIteration(void)
	{
		/** Print some information */
		xl::xout["iteration"]["2:Metric"]		<< this->GetValue();

		this->m_OptimizationSurface->SetPixel(
			this->GetCurrentIndexInSearchSpace(),
			this->GetValue()   );

		SearchSpacePointType currentPoint = this->GetCurrentPointInSearchSpace();
		unsigned int nrOfSSDims = currentPoint.GetSize();
		NameIteratorType name_it = this->m_SearchSpaceDimensionNames.begin();

		for ( unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			xl::xout["iteration"][name_it->second.c_str()] << currentPoint[dim];
			name_it++;
		}

	} // end AfterEachIteration

	/**
	 * ***************** AfterEachResolution *************************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::AfterEachResolution(void)
	{
		//typedef enum {FullRangeSearched,	MetricError	} StopConditionType;

		std::string stopcondition;

		switch( this->GetStopCondition() )
		{

		case FullRangeSearched :
			stopcondition = "The full range has been searched";
			break;

		case MetricError :
			stopcondition = "Error in metric";
			break;

		default:
			stopcondition = "Unknown";
			break;

		}
		/** Print the stopping condition */

		elxout << "Stopping condition: " << stopcondition << "." << std::endl;

		/** Write the optimization surface to disk */
		try
		{
			this->m_OptimizationSurface->Write();
			elxout
				<< "\nThe scanned optimization surface is saved as: "
				<< this->m_OptimizationSurface->GetOutputFileName()
				<< std::endl;
		}
		catch ( ExceptionObject& err )
		{
			xl::xout["error"]
			  << "ERROR: Saving "
				<< this->m_OptimizationSurface->GetOutputFileName()
				<< " failed."
				<< std::endl;
			xl::xout["error"] << err << std::endl;

		  // do not throw an error, since we would like to go on.
		}

		/** Print the best metric value */
		elxout
			<< std::endl
			<< "Best metric value in this resolution = "
			<< this->GetBestValue()
			<< std::endl;

		/** Print the best index and point */
		SearchSpaceIndexType bestIndex = this->GetBestIndexInSearchSpace();
		SearchSpacePointType bestPoint = this->GetBestPointInSearchSpace();
		unsigned int nrOfSSDims = bestIndex.GetSize();

		elxout <<	"Index of the point in the optimization surface image that has the best metric value: [ ";
		for (unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			elxout << bestIndex[dim] << " ";
		}
		elxout << "]" << std::endl;

		elxout << "The corresponding parameter values: [ " ;
		for (unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			elxout << bestPoint[dim] << " ";
		}
		elxout << "]\n" << std::endl;

		/** Remove the columns from xout["iteration"] */
		NameIteratorType name_it = this->m_SearchSpaceDimensionNames.begin();
		for ( unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			xl::xout["iteration"].RemoveTargetCell( name_it->second.c_str() );
			name_it++;
		}

		/** Clear the dimension names of the previous resolution's search space */
		this->m_SearchSpaceDimensionNames.clear();
		/** Clear the full search ranges */
		this->SetSearchSpace(0);

	} // end AfterEachResolution

	/**
	 * ******************* AfterRegistration ************************
	 */
	template <class TElastix>
		void FullSearch<TElastix>
		::AfterRegistration(void)
	{
	  /** Print the best metric value */
		double bestValue = this->GetBestValue();
		elxout << std::endl << "Final metric value  = " << bestValue  << std::endl;

	} // end AfterRegistration

	/**
	 * ************ CheckSearchSpaceRangeDefinition *****************
	 */
	template <class TElastix>
		int FullSearch<TElastix>
		::CheckSearchSpaceRangeDefinition(const std::string & fullFieldName, int errorcode, unsigned int entry_nr)
	{

		/** Complain if not at least one search space dimension has been found,
		 * or if a search dimension is not fully specified */
		if (
					(errorcode != 0) &&
					( (entry_nr == 0) || ((entry_nr % 5) != 0) )
			 )
		{
			xl::xout["error"]
				<< "ERROR:\nNo (valid) range specified for the full search optimizer!"
				<< std::endl
				<< "Please define the field ("
				<< fullFieldName
				<< " \"name\" parameter_nr min max stepsize) correctly in the parameter file"
				<< std::endl;
			return 1;
		}
		else
		{
			return 0;
		}

	} // end CheckSearchSpaceRangeDefinition

} // end namespace elastix

#endif // end #ifndef __elxFullSearchOptimizer_hxx

<commit_msg>SKwin<commit_after>/** test3 */
#ifndef __elxFullSearchOptimizer_hxx
#define __elxFullSearchOptimizer_hxx

#include "elxFullSearchOptimizer.h"
#include <iomanip>
#include <sstream>
#include <string>
#include "vnl/vnl_math.h"

namespace elastix
{
using namespace itk;

	/**
	 * ********************* Constructor ****************************
	 */

	template <class TElastix>
		FullSearch<TElastix>
		::FullSearch()
	{
		this->m_OptimizationSurface = 0;

	} // end Constructor

	/**
	 * ***************** BeforeRegistration ***********************
	 */

	template <class TElastix>
		void FullSearch<TElastix>::
		BeforeRegistration(void)
	{
		/** Add the target cells "ItNr" and "Metric" to xout["iteration"].*/
		xl::xout["iteration"].AddTargetCell("2:Metric");

		/** Format the metric as floats */
		xl::xout["iteration"]["2:Metric"]		<< std::showpoint << std::fixed;

	} // end BeforeRegistration

	/**
	 * ***************** BeforeEachResolution ***********************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::BeforeEachResolution(void)
	{
		/** Get the current resolution level.*/
		unsigned int level = static_cast<unsigned int>(
			this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() );

		/**
		 * Read FullSearchRange from the parameter file
		 */

		/** declare variables */

		std::string name("");
		unsigned int param_nr = 0;
		double minimum = 0;
		double maximum = 0;
		double stepsize = 0;
		const std::string prefix = "FS";
		unsigned int entry_nr = 0;
		unsigned int nrOfSearchSpaceDimensions = 0;
		int errorcode = 0;
		int realerror = 0;
		std::ostringstream makeString("");

		/** fullFieldName = "FullSearchSpace0" at level 0; */
		makeString << "FullSearchSpace" << level;
		std::string fullFieldName = makeString.str();

		while ( errorcode==0 )  //as long as still search ranges are defined
		{
			/** Try to read (silently) from the parameter file */
			/** \todo check earlier, in BeforeAll, if the searchspace has been defined. */

			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					name, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					param_nr, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					minimum, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					maximum, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}
			if (!realerror && !errorcode)
			{
				errorcode = this->GetConfiguration()->ReadParameter(
					stepsize, fullFieldName.c_str(), entry_nr, true);
				realerror = this->CheckSearchSpaceRangeDefinition(fullFieldName.c_str(), errorcode, entry_nr);
				entry_nr++;
			}

			/** Setup this search range */
			if (!realerror && !errorcode)
			{
				/** Setup the Superclass */
				this->AddSearchDimension(param_nr, minimum, maximum, stepsize);

				/** Create name of this dimension */
				makeString.str("");
				makeString
					<< prefix
					<< ( (entry_nr / 5) - 1 )
					<< ":"
					<< name
					<< ":"
					<< param_nr;

				/** Store the name and create a column in xout["iteration"] */
				this->m_SearchSpaceDimensionNames[param_nr] = makeString.str();
				xl::xout["iteration"].AddTargetCell( makeString.str().c_str() );

				/** Format this xout iteration column as float */
				xl::xout["iteration"][ makeString.str().c_str() ]
					<< std::showpoint << std::fixed;

			} // end if (!realerror)

		} // end while

		if (!realerror)
		{
			/** The number of dimensions */
			nrOfSearchSpaceDimensions = this->GetNumberOfSearchSpaceDimensions();

			/** Create the image that will store the results of the full search. */
			this->m_OptimizationSurface =
				NDImageType::NewNDImage(nrOfSearchSpaceDimensions);
			this->m_OptimizationSurface->CreateNewImage();
			/** \todo don't do this if more than max allowable dimensions. */

			/** Set the correct size and allocate memory */
			this->m_OptimizationSurface->SetRegions(
				this->GetSearchSpaceSize()  );
			this->m_OptimizationSurface->Allocate();
			/** \todo try/catch block around Allocate? */

			/** Set the name of this image on disk. */
			std::string resultImageFormat = "mhd";
			this->m_Configuration->ReadParameter(	resultImageFormat, "ResultImageFormat", 0, true );
			makeString.str("");
			makeString
				<< this->GetConfiguration()->GetCommandLineArgument("-out")
				<< "OptimizationSurface."
				<< this->GetConfiguration()->GetElastixLevel()
				<< ".R" << level
				<< "." << resultImageFormat;
			this->m_OptimizationSurface->SetOutputFileName( makeString.str().c_str() );

			elxout
				<< "Total number of iterations needed in this resolution: "
				<< this->GetNumberOfIterations()
				<< "." << std::endl;

		} // if (!realerror)

		/** \todo else: quit program or something like that. */

	} // end BeforeEachResolution

	/**
	 * ***************** AfterEachIteration *************************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::AfterEachIteration(void)
	{
		/** Print some information */
		xl::xout["iteration"]["2:Metric"]		<< this->GetValue();

		this->m_OptimizationSurface->SetPixel(
			this->GetCurrentIndexInSearchSpace(),
			this->GetValue()   );

		SearchSpacePointType currentPoint = this->GetCurrentPointInSearchSpace();
		unsigned int nrOfSSDims = currentPoint.GetSize();
		NameIteratorType name_it = this->m_SearchSpaceDimensionNames.begin();

		for ( unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			xl::xout["iteration"][name_it->second.c_str()] << currentPoint[dim];
			name_it++;
		}

	} // end AfterEachIteration

	/**
	 * ***************** AfterEachResolution *************************
	 */

	template <class TElastix>
		void FullSearch<TElastix>
		::AfterEachResolution(void)
	{
		//typedef enum {FullRangeSearched,	MetricError	} StopConditionType;

		std::string stopcondition;

		switch( this->GetStopCondition() )
		{

		case FullRangeSearched :
			stopcondition = "The full range has been searched";
			break;

		case MetricError :
			stopcondition = "Error in metric";
			break;

		default:
			stopcondition = "Unknown";
			break;

		}
		/** Print the stopping condition */

		elxout << "Stopping condition: " << stopcondition << "." << std::endl;

		/** Write the optimization surface to disk */
		try
		{
			this->m_OptimizationSurface->Write();
			elxout
				<< "\nThe scanned optimization surface is saved as: "
				<< this->m_OptimizationSurface->GetOutputFileName()
				<< std::endl;
		}
		catch ( ExceptionObject& err )
		{
			xl::xout["error"]
			  << "ERROR: Saving "
				<< this->m_OptimizationSurface->GetOutputFileName()
				<< " failed."
				<< std::endl;
			xl::xout["error"] << err << std::endl;

		  // do not throw an error, since we would like to go on.
		}

		/** Print the best metric value */
		elxout
			<< std::endl
			<< "Best metric value in this resolution = "
			<< this->GetBestValue()
			<< std::endl;

		/** Print the best index and point */
		SearchSpaceIndexType bestIndex = this->GetBestIndexInSearchSpace();
		SearchSpacePointType bestPoint = this->GetBestPointInSearchSpace();
		unsigned int nrOfSSDims = bestIndex.GetSize();

		elxout <<	"Index of the point in the optimization surface image that has the best metric value: [ ";
		for (unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			elxout << bestIndex[dim] << " ";
		}
		elxout << "]" << std::endl;

		elxout << "The corresponding parameter values: [ " ;
		for (unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			elxout << bestPoint[dim] << " ";
		}
		elxout << "]\n" << std::endl;

		/** Remove the columns from xout["iteration"] */
		NameIteratorType name_it = this->m_SearchSpaceDimensionNames.begin();
		for ( unsigned int dim = 0; dim < nrOfSSDims; dim++)
		{
			xl::xout["iteration"].RemoveTargetCell( name_it->second.c_str() );
			name_it++;
		}

		/** Clear the dimension names of the previous resolution's search space */
		this->m_SearchSpaceDimensionNames.clear();
		/** Clear the full search ranges */
		this->SetSearchSpace(0);

	} // end AfterEachResolution

	/**
	 * ******************* AfterRegistration ************************
	 */
	template <class TElastix>
		void FullSearch<TElastix>
		::AfterRegistration(void)
	{
	  /** Print the best metric value */
		double bestValue = this->GetBestValue();
		elxout << std::endl << "Final metric value  = " << bestValue  << std::endl;

	} // end AfterRegistration

	/**
	 * ************ CheckSearchSpaceRangeDefinition *****************
	 */
	template <class TElastix>
		int FullSearch<TElastix>
		::CheckSearchSpaceRangeDefinition(const std::string & fullFieldName, int errorcode, unsigned int entry_nr)
	{

		/** Complain if not at least one search space dimension has been found,
		 * or if a search dimension is not fully specified */
		if (
					(errorcode != 0) &&
					( (entry_nr == 0) || ((entry_nr % 5) != 0) )
			 )
		{
			xl::xout["error"]
				<< "ERROR:\nNo (valid) range specified for the full search optimizer!"
				<< std::endl
				<< "Please define the field ("
				<< fullFieldName
				<< " \"name\" parameter_nr min max stepsize) correctly in the parameter file"
				<< std::endl;
			return 1;
		}
		else
		{
			return 0;
		}

	} // end CheckSearchSpaceRangeDefinition

} // end namespace elastix

#endif // end #ifndef __elxFullSearchOptimizer_hxx

<|endoftext|>


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

#include <random>

#include "gtest/gtest.h"
#include "perfetto/trace/test_event.pbzero.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "test/fake_consumer.h"

namespace perfetto {

class PerfettoCtsTest : public ::testing::Test {
 protected:
  void TestMockProducer(const std::string& producer_name) {
    base::TestTaskRunner task_runner;

    // Setup the trace config.
    TraceConfig trace_config;
    trace_config.add_buffers()->set_size_kb(4096 * 10);
    trace_config.set_duration_ms(200);

    auto* ds_config = trace_config.add_data_sources()->mutable_config();
    ds_config->set_name(producer_name);
    ds_config->set_target_buffer(0);

    // The parameters for the producer.
    static constexpr uint32_t kRandomSeed = 42;
    static constexpr uint32_t kEventCount = 10;

    // Setup the test to use a random number generator.
    ds_config->mutable_for_testing()->set_seed(kRandomSeed);
    ds_config->mutable_for_testing()->set_message_count(kEventCount);

    // Create the random generator with the same seed.
    std::minstd_rand0 rnd_engine(kRandomSeed);

    // Setip the function.
    uint64_t total = 0;
    auto finish = task_runner.CreateCheckpoint("no.more.packets");
    auto function = [&total, &finish, &rnd_engine](
                        std::vector<TracePacket> packets, bool has_more) {
      for (auto& packet : packets) {
        ASSERT_TRUE(packet.Decode());
        ASSERT_TRUE(packet->has_for_testing());
        ASSERT_EQ(protos::TracePacket::kTrustedUid,
                  packet->optional_trusted_uid_case());
        ASSERT_EQ(packet->for_testing().seq_value(), rnd_engine());
      }
      total += packets.size();

      if (!has_more) {
        ASSERT_EQ(total, kEventCount);
        finish();
      }
    };

    // Finally, make the consumer connect to the service.
    FakeConsumer consumer(trace_config, std::move(function), &task_runner);
    consumer.Connect(PERFETTO_CONSUMER_SOCK_NAME);

    // TODO(skyostil): There's a race here before the service processes our data
    // and the consumer tries to retrieve it. For now wait a bit until the
    // service is done, but we should add explicit flushing to avoid this.
    task_runner.PostDelayedTask([&consumer]() { consumer.ReadTraceData(); },
                                5000);

    task_runner.RunUntilCheckpoint("no.more.packets", 10000);
  }
};

TEST_F(PerfettoCtsTest, TestProducerActivity) {
  TestMockProducer("android.perfetto.cts.ProducerActivity");
}

TEST_F(PerfettoCtsTest, TestProducerService) {
  TestMockProducer("android.perfetto.cts.ProducerService");
}

TEST_F(PerfettoCtsTest, TestProducerIsolatedService) {
  TestMockProducer("android.perfetto.cts.ProducerIsolatedService");
}

}  // namespace perfetto
<commit_msg>perfetto: fix cts test failure after clock sync<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <random>

#include "gtest/gtest.h"
#include "perfetto/trace/test_event.pbzero.h"
#include "perfetto/trace/trace_packet.pb.h"
#include "perfetto/trace/trace_packet.pbzero.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "test/fake_consumer.h"

namespace perfetto {

class PerfettoCtsTest : public ::testing::Test {
 protected:
  void TestMockProducer(const std::string& producer_name) {
    base::TestTaskRunner task_runner;

    // Setup the trace config.
    TraceConfig trace_config;
    trace_config.add_buffers()->set_size_kb(4096 * 10);
    trace_config.set_duration_ms(200);

    auto* ds_config = trace_config.add_data_sources()->mutable_config();
    ds_config->set_name(producer_name);
    ds_config->set_target_buffer(0);

    // The parameters for the producer.
    static constexpr uint32_t kRandomSeed = 42;
    static constexpr uint32_t kEventCount = 10;

    // Setup the test to use a random number generator.
    ds_config->mutable_for_testing()->set_seed(kRandomSeed);
    ds_config->mutable_for_testing()->set_message_count(kEventCount);

    // Create the random generator with the same seed.
    std::minstd_rand0 rnd_engine(kRandomSeed);

    // Setip the function.
    uint64_t total = 0;
    auto finish = task_runner.CreateCheckpoint("no.more.packets");
    auto function = [&total, &finish, &rnd_engine](
                        std::vector<TracePacket> packets, bool has_more) {
      for (auto& packet : packets) {
        ASSERT_TRUE(packet.Decode());
        ASSERT_TRUE(packet->has_for_testing() || packet->has_clock_snapshot());
        if (packet->has_clock_snapshot()) {
          continue;
        }
        ASSERT_EQ(protos::TracePacket::kTrustedUid,
                  packet->optional_trusted_uid_case());
        ASSERT_EQ(packet->for_testing().seq_value(), rnd_engine());
      }
      total += packets.size();

      if (!has_more) {
        ASSERT_EQ(total, kEventCount);
        finish();
      }
    };

    // Finally, make the consumer connect to the service.
    FakeConsumer consumer(trace_config, std::move(function), &task_runner);
    consumer.Connect(PERFETTO_CONSUMER_SOCK_NAME);

    // TODO(skyostil): There's a race here before the service processes our data
    // and the consumer tries to retrieve it. For now wait a bit until the
    // service is done, but we should add explicit flushing to avoid this.
    task_runner.PostDelayedTask([&consumer]() { consumer.ReadTraceData(); },
                                5000);

    task_runner.RunUntilCheckpoint("no.more.packets", 10000);
  }
};

TEST_F(PerfettoCtsTest, TestProducerActivity) {
  TestMockProducer("android.perfetto.cts.ProducerActivity");
}

TEST_F(PerfettoCtsTest, TestProducerService) {
  TestMockProducer("android.perfetto.cts.ProducerService");
}

TEST_F(PerfettoCtsTest, TestProducerIsolatedService) {
  TestMockProducer("android.perfetto.cts.ProducerIsolatedService");
}

}  // namespace perfetto
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/
#include "EigenSystem.h"
#include "KernelWarehouse.h"

#include "MaterialData.h"
#include "Factory.h"
#include "EigenKernel.h"

EigenSystem::EigenSystem(FEProblem & fe_problem, const std::string & name) :
    NonlinearSystem(fe_problem, name),
    _all_eigen_vars(false),
    _active_on_old(false),
    _sys_sol_old(NULL),
    _sys_sol_older(NULL),
    _aux_sol_old(NULL),
    _aux_sol_older(NULL)
{
}

EigenSystem::~EigenSystem()
{
}

void
EigenSystem::addKernel(const std::string & kernel_name, const std::string & name, InputParameters parameters)
{
  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
  {
    // Set the parameters for thread ID and material data
    parameters.set<THREAD_ID>("_tid") = tid;
    parameters.set<MaterialData *>("_material_data") = _fe_problem._material_data[tid];

    // In the case of EigenKernels, we might need to add two to the system
    if (parameters.have_parameter<bool>("eigen"))
    {
      {
        // EigenKernel
        parameters.set<bool>("implicit") = true;
        EigenKernel *ekernel = static_cast<EigenKernel *>(_factory.create(kernel_name, name, parameters));
        mooseAssert(ekernel != NULL, "Not an EigenKernel object");
        markEigenVariable(parameters.get<NonlinearVariableName>("variable"));
        // Extract the SubdomainIDs from the object (via BlockRestrictable class)
        std::set<SubdomainID> blk_ids = ekernel->blockIDs();
        _kernels[tid].addKernel(ekernel, blk_ids);
        _fe_problem._objects_by_name[tid][name].push_back(ekernel);
      }
      if (parameters.get<bool>("eigen"))
      {
        // EigenKernel_old
        parameters.set<bool>("implicit") = false;
        std::string old_name(name + "_old");

        EigenKernel *ekernel = static_cast<EigenKernel *>(_factory.create(kernel_name, old_name, parameters));
        _eigen_var_names.insert(parameters.get<NonlinearVariableName>("variable"));
        // Extract the SubdomainIDs from the object (via BlockRestrictable class)
        std::set<SubdomainID> blk_ids = ekernel->blockIDs();
        _kernels[tid].addKernel(ekernel, blk_ids);
        _fe_problem._objects_by_name[tid][old_name].push_back(ekernel);
      }
    }
    else // Standard nonlinear system kernel
    {
      // Create the kernel object via the factory
      KernelBase *kernel = static_cast<KernelBase *>(_factory.create(kernel_name, name, parameters));
      mooseAssert(kernel != NULL, "Not a Kernel object");
      // Extract the SubdomainIDs from the object (via BlockRestrictable class)
      std::set<SubdomainID> blk_ids = kernel->blockIDs();
      _kernels[tid].addKernel(kernel, blk_ids);
      _fe_problem._objects_by_name[tid][name].push_back(kernel);
    }
  }
}

void
EigenSystem::markEigenVariable(const VariableName & var_name)
{
  _eigen_var_names.insert(var_name);
}

void
EigenSystem::scaleSystemSolution(SYSTEMTAG tag, Real scaling_factor)
{
  if (tag==ALL)
  {
    solution().scale(scaling_factor);
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution().scale(scaling_factor);
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solution().set( *it, solution()(*it)*scaling_factor );
    }
  }
  solution().close();
  update();
}

void
EigenSystem::combineSystemSolution(SYSTEMTAG tag, const std::vector<Real> & coefficients)
{
  mooseAssert(coefficients.size()>0 && coefficients.size()<=3, "Size error on coefficients");
  if (tag==ALL)
  {
    solution().scale(coefficients[0]);
    if (coefficients.size()>1) solution().add(coefficients[1], solutionOld());
    if (coefficients.size()>2) solution().add(coefficients[2], solutionOlder());
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution().scale(coefficients[0]);
      if (coefficients.size()>1) solution().add(coefficients[1], solutionOld());
      if (coefficients.size()>2) solution().add(coefficients[2], solutionOlder());
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      if (coefficients.size()>2)
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          t += solutionOld()(*it) * coefficients[1];
          t += solutionOlder()(*it) * coefficients[2];
          solution().set( *it, t );
        }
      }
      else if (coefficients.size()>1)
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          t += solutionOld()(*it) * coefficients[1];
          solution().set( *it, t );
        }
      }
      else
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          solution().set( *it, t );
        }
      }
    }
  }
  solution().close();
  update();
}

void
EigenSystem::initSystemSolution(SYSTEMTAG tag, Real v)
{
  if (tag==ALL)
  {
    solution() = v;
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution() = v;
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solution().set( *it, v );
    }
  }
  solution().close();
  update();
}

void
EigenSystem::initSystemSolutionOld(SYSTEMTAG tag, Real v)
{
  if (tag==ALL)
  {
    solutionOld() = v;
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solutionOld() = v;
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solutionOld().set( *it, v );
    }
  }
  solutionOld().close();
  update();
}

void
EigenSystem::eigenKernelOnOld()
{
  _active_on_old = true;
}

void
EigenSystem::eigenKernelOnCurrent()
{
  _active_on_old = false;
}

bool
EigenSystem::activeOnOld()
{
  return _active_on_old;
}

void
EigenSystem::buildSystemDoFIndices(SYSTEMTAG tag)
{
  if (tag==ALL)
  {
  }
  else if (tag==EIGEN)
  {
    // build DoF indices for the eigen system
    _eigen_var_indices.clear();
    _all_eigen_vars = getEigenVariableNames().size()==getVariableNames().size();
    if (!_all_eigen_vars)
    {
      for (std::set<VariableName>::const_iterator it=getEigenVariableNames().begin();
           it!=getEigenVariableNames().end(); it++)
      {
        unsigned int i = sys().variable_number(*it);
        sys().local_dof_indices(i, _eigen_var_indices);
      }
    }
  }
}

void
EigenSystem::saveOldSolutions()
{
  if (!_sys_sol_old)
    _sys_sol_old= &addVector("save_flux_old", false, PARALLEL);
  if (!_aux_sol_old)
    _aux_sol_old = &_fe_problem.getAuxiliarySystem().addVector("save_aux_old",  false, PARALLEL);
  if (!_sys_sol_older)
    _sys_sol_older = &addVector("save_flux_older", false, PARALLEL);
  if (!_aux_sol_older)
    _aux_sol_older = &_fe_problem.getAuxiliarySystem().addVector("save_aux_older",  false, PARALLEL);
  *_sys_sol_old   = solutionOld();
  *_sys_sol_older = solutionOlder();
  *_aux_sol_old   = _fe_problem.getAuxiliarySystem().solutionOld();
  *_aux_sol_older = _fe_problem.getAuxiliarySystem().solutionOlder();
}

void
EigenSystem::restoreOldSolutions()
{
  solutionOld() = *_sys_sol_old;
  solutionOlder() = *_sys_sol_older;
  _fe_problem.getAuxiliarySystem().solutionOld() = *_aux_sol_old;
  _fe_problem.getAuxiliarySystem().solutionOlder() = *_aux_sol_older;
}
<commit_msg>fix a logic error: an eigen kernel should not mark its variable as eigen variable when eigen==false  #2902<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/
#include "EigenSystem.h"
#include "KernelWarehouse.h"

#include "MaterialData.h"
#include "Factory.h"
#include "EigenKernel.h"

EigenSystem::EigenSystem(FEProblem & fe_problem, const std::string & name) :
    NonlinearSystem(fe_problem, name),
    _all_eigen_vars(false),
    _active_on_old(false),
    _sys_sol_old(NULL),
    _sys_sol_older(NULL),
    _aux_sol_old(NULL),
    _aux_sol_older(NULL)
{
}

EigenSystem::~EigenSystem()
{
}

void
EigenSystem::addKernel(const std::string & kernel_name, const std::string & name, InputParameters parameters)
{
  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
  {
    // Set the parameters for thread ID and material data
    parameters.set<THREAD_ID>("_tid") = tid;
    parameters.set<MaterialData *>("_material_data") = _fe_problem._material_data[tid];

    // In the case of EigenKernels, we might need to add two to the system
    if (parameters.have_parameter<bool>("eigen"))
    {
      {
        // EigenKernel
        parameters.set<bool>("implicit") = true;
        EigenKernel *ekernel = static_cast<EigenKernel *>(_factory.create(kernel_name, name, parameters));
        mooseAssert(ekernel != NULL, "Not an EigenKernel object");
        if (parameters.get<bool>("eigen")) markEigenVariable(parameters.get<NonlinearVariableName>("variable"));
        // Extract the SubdomainIDs from the object (via BlockRestrictable class)
        std::set<SubdomainID> blk_ids = ekernel->blockIDs();
        _kernels[tid].addKernel(ekernel, blk_ids);
        _fe_problem._objects_by_name[tid][name].push_back(ekernel);
      }
      if (parameters.get<bool>("eigen"))
      {
        // EigenKernel_old
        parameters.set<bool>("implicit") = false;
        std::string old_name(name + "_old");

        EigenKernel *ekernel = static_cast<EigenKernel *>(_factory.create(kernel_name, old_name, parameters));
        _eigen_var_names.insert(parameters.get<NonlinearVariableName>("variable"));
        // Extract the SubdomainIDs from the object (via BlockRestrictable class)
        std::set<SubdomainID> blk_ids = ekernel->blockIDs();
        _kernels[tid].addKernel(ekernel, blk_ids);
        _fe_problem._objects_by_name[tid][old_name].push_back(ekernel);
      }
    }
    else // Standard nonlinear system kernel
    {
      // Create the kernel object via the factory
      KernelBase *kernel = static_cast<KernelBase *>(_factory.create(kernel_name, name, parameters));
      mooseAssert(kernel != NULL, "Not a Kernel object");
      // Extract the SubdomainIDs from the object (via BlockRestrictable class)
      std::set<SubdomainID> blk_ids = kernel->blockIDs();
      _kernels[tid].addKernel(kernel, blk_ids);
      _fe_problem._objects_by_name[tid][name].push_back(kernel);
    }
  }
}

void
EigenSystem::markEigenVariable(const VariableName & var_name)
{
  _eigen_var_names.insert(var_name);
}

void
EigenSystem::scaleSystemSolution(SYSTEMTAG tag, Real scaling_factor)
{
  if (tag==ALL)
  {
    solution().scale(scaling_factor);
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution().scale(scaling_factor);
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solution().set( *it, solution()(*it)*scaling_factor );
    }
  }
  solution().close();
  update();
}

void
EigenSystem::combineSystemSolution(SYSTEMTAG tag, const std::vector<Real> & coefficients)
{
  mooseAssert(coefficients.size()>0 && coefficients.size()<=3, "Size error on coefficients");
  if (tag==ALL)
  {
    solution().scale(coefficients[0]);
    if (coefficients.size()>1) solution().add(coefficients[1], solutionOld());
    if (coefficients.size()>2) solution().add(coefficients[2], solutionOlder());
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution().scale(coefficients[0]);
      if (coefficients.size()>1) solution().add(coefficients[1], solutionOld());
      if (coefficients.size()>2) solution().add(coefficients[2], solutionOlder());
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      if (coefficients.size()>2)
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          t += solutionOld()(*it) * coefficients[1];
          t += solutionOlder()(*it) * coefficients[2];
          solution().set( *it, t );
        }
      }
      else if (coefficients.size()>1)
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          t += solutionOld()(*it) * coefficients[1];
          solution().set( *it, t );
        }
      }
      else
      {
        for(; it !=it_end; ++it)
        {
          Real t = solution()(*it) * coefficients[0];
          solution().set( *it, t );
        }
      }
    }
  }
  solution().close();
  update();
}

void
EigenSystem::initSystemSolution(SYSTEMTAG tag, Real v)
{
  if (tag==ALL)
  {
    solution() = v;
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solution() = v;
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solution().set( *it, v );
    }
  }
  solution().close();
  update();
}

void
EigenSystem::initSystemSolutionOld(SYSTEMTAG tag, Real v)
{
  if (tag==ALL)
  {
    solutionOld() = v;
  }
  else if (tag==EIGEN)
  {
    if (_all_eigen_vars)
    {
      solutionOld() = v;
    }
    else
    {
      std::set<dof_id_type>::iterator it      = _eigen_var_indices.begin();
      std::set<dof_id_type>::iterator it_end  = _eigen_var_indices.end();

      for(; it !=it_end; ++it)
        solutionOld().set( *it, v );
    }
  }
  solutionOld().close();
  update();
}

void
EigenSystem::eigenKernelOnOld()
{
  _active_on_old = true;
}

void
EigenSystem::eigenKernelOnCurrent()
{
  _active_on_old = false;
}

bool
EigenSystem::activeOnOld()
{
  return _active_on_old;
}

void
EigenSystem::buildSystemDoFIndices(SYSTEMTAG tag)
{
  if (tag==ALL)
  {
  }
  else if (tag==EIGEN)
  {
    // build DoF indices for the eigen system
    _eigen_var_indices.clear();
    _all_eigen_vars = getEigenVariableNames().size()==getVariableNames().size();
    if (!_all_eigen_vars)
    {
      for (std::set<VariableName>::const_iterator it=getEigenVariableNames().begin();
           it!=getEigenVariableNames().end(); it++)
      {
        unsigned int i = sys().variable_number(*it);
        sys().local_dof_indices(i, _eigen_var_indices);
      }
    }
  }
}

void
EigenSystem::saveOldSolutions()
{
  if (!_sys_sol_old)
    _sys_sol_old= &addVector("save_flux_old", false, PARALLEL);
  if (!_aux_sol_old)
    _aux_sol_old = &_fe_problem.getAuxiliarySystem().addVector("save_aux_old",  false, PARALLEL);
  if (!_sys_sol_older)
    _sys_sol_older = &addVector("save_flux_older", false, PARALLEL);
  if (!_aux_sol_older)
    _aux_sol_older = &_fe_problem.getAuxiliarySystem().addVector("save_aux_older",  false, PARALLEL);
  *_sys_sol_old   = solutionOld();
  *_sys_sol_older = solutionOlder();
  *_aux_sol_old   = _fe_problem.getAuxiliarySystem().solutionOld();
  *_aux_sol_older = _fe_problem.getAuxiliarySystem().solutionOlder();
}

void
EigenSystem::restoreOldSolutions()
{
  solutionOld() = *_sys_sol_old;
  solutionOlder() = *_sys_sol_older;
  _fe_problem.getAuxiliarySystem().solutionOld() = *_aux_sol_old;
  _fe_problem.getAuxiliarySystem().solutionOlder() = *_aux_sol_older;
}
<|endoftext|>


<commit_before><commit_msg>babylon_studio.cpp: debug logs<commit_after><|endoftext|>