<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications 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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include <QApplication>
#include <QTranslator>
#include <QDebug>

#if defined (Q_OS_SYMBIAN)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void myMessageOutput(QtMsgType type, const char *msg)
{
    static int fd = -1;
    if (fd == -1)
        fd = ::open("E:\\qmlviewer.log", O_WRONLY | O_CREAT);

    ::write(fd, msg, strlen(msg));
    ::write(fd, "\n", 1);
    ::fsync(fd);

    switch (type) {
    case QtFatalMsg:
        abort();
    }
}
#endif

void usage()
{
    qWarning("Usage: qmlviewer [options] <filename>");
    qWarning(" ");
    qWarning(" options:");
    qWarning("  -v, -version ............................. display version");
    qWarning("  -frameless ............................... run with no window frame");
    qWarning("  -maximized................................ run maximized");
    qWarning("  -fullscreen............................... run fullscreen");
    qWarning("  -stayontop................................ keep viewer window on top");
    qWarning("  -skin <qvfbskindir> ...................... run with a skin window frame");
    qWarning("                                             \"list\" for a list of built-ins");
    qWarning("  -resizeview .............................. resize the view, not the skin");
    qWarning("  -recordfile <output> ..................... set video recording file");
    qWarning("                                              - ImageMagick 'convert' for GIF)");
    qWarning("                                              - png file for raw frames");
    qWarning("                                              - 'ffmpeg' for other formats");
    qWarning("  -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
    qWarning("  -recordrate <fps> ........................ set recording frame rate");
    qWarning("  -record arg .............................. add a recording process argument");
    qWarning("  -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
    qWarning("  -devicekeys .............................. use numeric keys (see F1)");
    qWarning("  -netcache <size> ......................... set disk cache to size bytes");
    qWarning("  -translation <translationfile> ........... set the language to run in");
    qWarning("  -L <directory> ........................... prepend to the library search path");
    qWarning("  -opengl .................................. use a QGLWidget for the viewport");
    qWarning("  -script <path> ........................... set the script to use");
    qWarning("  -scriptopts <options>|help ............... set the script options to use");

    qWarning(" ");
    qWarning(" Press F1 for interactive help");
    exit(1);
}

void scriptOptsUsage()
{
    qWarning("Usage: qmlviewer -scriptopts <option>[,<option>...] ...");
    qWarning(" options:");
    qWarning("  record ................................... record a new script");
    qWarning("  play ..................................... playback an existing script");
    qWarning("  testimages ............................... record images or compare images on playback");
    qWarning("  testerror ................................ test 'error' property of root item on playback");
    qWarning("  exitoncomplete ........................... cleanly exit the viewer on script completion");
    qWarning("  exitonfailure ............................ immediately exit the viewer on script failure");
    qWarning("  saveonexit ............................... save recording on viewer exit");
    qWarning(" ");
    qWarning(" One of record, play or both must be specified.");
    exit(1);
}

int main(int argc, char ** argv)
{
#if defined (Q_OS_SYMBIAN)
    qInstallMsgHandler(myMessageOutput);
#endif

#if defined (Q_WS_X11)
    //### default to using raster graphics backend for now
    bool gsSpecified = false;
    for (int i = 0; i < argc; ++i) {
        QString arg = argv[i];
        if (arg == "-graphicssystem") {
            gsSpecified = true;
            break;
        }
    }

    if (!gsSpecified)
        QApplication::setGraphicsSystem("raster");
#endif

    QApplication app(argc, argv);
    app.setApplicationName("viewer");
    app.setOrganizationName("Nokia");
    app.setOrganizationDomain("nokia.com");

    bool frameless = false;
    bool resizeview = false;
    QString fileName;
    double fps = 0;
    int autorecord_from = 0;
    int autorecord_to = 0;
    QString dither = "none";
    QString recordfile;
    QStringList recordargs;
    QStringList libraries;
    QString skin;
    QString script;
    QString scriptopts;
    bool runScript = false;
    bool devkeys = false;
    int cache = 0;
    QString translationFile;
    bool useGL = false;
    bool fullScreen = false;
    bool stayOnTop = false;
    bool maximized = false;
    bool useNativeFileBrowser = true;

#if defined(Q_OS_SYMBIAN)
    maximized = true;
    useNativeFileBrowser = false;
#endif

    for (int i = 1; i < argc; ++i) {
        bool lastArg = (i == argc - 1);
        QString arg = argv[i];
        if (arg == "-frameless") {
            frameless = true;
        } else if (arg == "-maximized") {
            maximized = true;
        } else if (arg == "-fullscreen") {
            fullScreen = true;
        } else if (arg == "-stayontop") {
            stayOnTop = true;
        } else if (arg == "-skin") {
            if (lastArg) usage();
            skin = QString(argv[++i]);
        } else if (arg == "-resizeview") {
            resizeview = true;
        } else if (arg == "-netcache") {
            if (lastArg) usage();
            cache = QString(argv[++i]).toInt();
        } else if (arg == "-recordrate") {
            if (lastArg) usage();
            fps = QString(argv[++i]).toDouble();
        } else if (arg == "-recordfile") {
            if (lastArg) usage();
            recordfile = QString(argv[++i]);
        } else if (arg == "-record") {
            if (lastArg) usage();
            recordargs << QString(argv[++i]);
        } else if (arg == "-recorddither") {
            if (lastArg) usage();
            dither = QString(argv[++i]);
        } else if (arg == "-autorecord") {
            if (lastArg) usage();
            QString range = QString(argv[++i]);
            int dash = range.indexOf('-');
            if (dash > 0)
                autorecord_from = range.left(dash).toInt();
            autorecord_to = range.mid(dash+1).toInt();
        } else if (arg == "-devicekeys") {
            devkeys = true;
        } else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
            fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
            return 0;
        } else if (arg == "-translation") {
            if (lastArg) usage();
            translationFile = argv[++i];
        } else if (arg == "-opengl") {
            useGL = true;
        } else if (arg == "-L") {
            if (lastArg) usage();
            libraries << QString(argv[++i]);
        } else if (arg == "-script") {
            if (lastArg) usage();
            script = QString(argv[++i]);
        } else if (arg == "-scriptopts") {
            if (lastArg) usage();
            scriptopts = QString(argv[++i]);
        } else if (arg == "-savescript") {
            if (lastArg) usage();
            script = QString(argv[++i]);
            runScript = false;
        } else if (arg == "-playscript") {
            if (lastArg) usage();
            script = QString(argv[++i]);
            runScript = true;
        } else if (arg[0] != '-') {
            fileName = arg;
        } else if (1 || arg == "-help") {
            usage();
        }
    }

    QTranslator qmlTranslator;
    if (!translationFile.isEmpty()) {
        qmlTranslator.load(translationFile);
        app.installTranslator(&qmlTranslator);
    }

    Qt::WFlags wflags = (frameless ? Qt::FramelessWindowHint : Qt::Widget);
    if (stayOnTop)
        wflags |= Qt::WindowStaysOnTopHint;

    QmlViewer viewer(0, wflags);
    if (!scriptopts.isEmpty()) {
        QStringList options =
            scriptopts.split(QLatin1Char(','), QString::SkipEmptyParts);

        QmlViewer::ScriptOptions scriptOptions = 0;
        for (int i = 0; i < options.count(); ++i) {
            const QString &option = options.at(i);
            if (option == QLatin1String("help")) {
                scriptOptsUsage();
            } else if (option == QLatin1String("play")) {
                scriptOptions |= QmlViewer::Play;
            } else if (option == QLatin1String("record")) {
                scriptOptions |= QmlViewer::Record;
            } else if (option == QLatin1String("testimages")) {
                scriptOptions |= QmlViewer::TestImages;
            } else if (option == QLatin1String("testerror")) {
                scriptOptions |= QmlViewer::TestErrorProperty;
            } else if (option == QLatin1String("exitoncomplete")) {
                scriptOptions |= QmlViewer::ExitOnComplete;
            } else if (option == QLatin1String("exitonfailure")) {
                scriptOptions |= QmlViewer::ExitOnFailure;
            } else if (option == QLatin1String("saveonexit")) {
                scriptOptions |= QmlViewer::SaveOnExit;
            } else {
                scriptOptsUsage();
            }
        }

        if (script.isEmpty())
            usage();

        if (!(scriptOptions & QmlViewer::Record) && !(scriptOptions & QmlViewer::Play))
            scriptOptsUsage();
        viewer.setScriptOptions(scriptOptions);
        viewer.setScript(script);
    }  else if (!script.isEmpty()) {
        usage();
    }

    viewer.setUseGL(useGL);
    foreach (QString lib, libraries)
        viewer.addLibraryPath(lib);
    viewer.setNetworkCacheSize(cache);
    viewer.setRecordFile(recordfile);
    if (resizeview)
        viewer.setScaleView();
    if (fps>0)
        viewer.setRecordRate(fps);
    if (autorecord_to)
        viewer.setAutoRecord(autorecord_from,autorecord_to);
    if (!skin.isEmpty()) {
        if (skin == "list") {
            foreach (QString s, viewer.builtinSkins())
                qWarning(s.toUtf8());
            exit(0);
        } else {
            viewer.setSkin(skin);
        }
    }
    if (devkeys)
        viewer.setDeviceKeys(true);
    viewer.setRecordDither(dither);
    if (recordargs.count())
        viewer.setRecordArgs(recordargs);

    viewer.setUseNativeFileBrowser(useNativeFileBrowser);
    if (fullScreen && maximized)
        qWarning() << "Both -fullscreen and -maximized specified. Using -fullscreen.";
    if (!fileName.isEmpty()) {
        viewer.open(fileName);
        fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
    } else {
        if (!useNativeFileBrowser)
            viewer.openFile();
        fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
        if (useNativeFileBrowser)
            viewer.openFile();
    }
    viewer.raise();

    return app.exec();
}
<commit_msg>Fix bad behaviour on N900<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications 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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include <QApplication>
#include <QTranslator>
#include <QDebug>

#if defined (Q_OS_SYMBIAN)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void myMessageOutput(QtMsgType type, const char *msg)
{
    static int fd = -1;
    if (fd == -1)
        fd = ::open("E:\\qmlviewer.log", O_WRONLY | O_CREAT);

    ::write(fd, msg, strlen(msg));
    ::write(fd, "\n", 1);
    ::fsync(fd);

    switch (type) {
    case QtFatalMsg:
        abort();
    }
}
#endif

void usage()
{
    qWarning("Usage: qmlviewer [options] <filename>");
    qWarning(" ");
    qWarning(" options:");
    qWarning("  -v, -version ............................. display version");
    qWarning("  -frameless ............................... run with no window frame");
    qWarning("  -maximized................................ run maximized");
    qWarning("  -fullscreen............................... run fullscreen");
    qWarning("  -stayontop................................ keep viewer window on top");
    qWarning("  -skin <qvfbskindir> ...................... run with a skin window frame");
    qWarning("                                             \"list\" for a list of built-ins");
    qWarning("  -resizeview .............................. resize the view, not the skin");
    qWarning("  -recordfile <output> ..................... set video recording file");
    qWarning("                                              - ImageMagick 'convert' for GIF)");
    qWarning("                                              - png file for raw frames");
    qWarning("                                              - 'ffmpeg' for other formats");
    qWarning("  -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
    qWarning("  -recordrate <fps> ........................ set recording frame rate");
    qWarning("  -record arg .............................. add a recording process argument");
    qWarning("  -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
    qWarning("  -devicekeys .............................. use numeric keys (see F1)");
    qWarning("  -netcache <size> ......................... set disk cache to size bytes");
    qWarning("  -translation <translationfile> ........... set the language to run in");
    qWarning("  -L <directory> ........................... prepend to the library search path");
    qWarning("  -opengl .................................. use a QGLWidget for the viewport");
    qWarning("  -script <path> ........................... set the script to use");
    qWarning("  -scriptopts <options>|help ............... set the script options to use");

    qWarning(" ");
    qWarning(" Press F1 for interactive help");
    exit(1);
}

void scriptOptsUsage()
{
    qWarning("Usage: qmlviewer -scriptopts <option>[,<option>...] ...");
    qWarning(" options:");
    qWarning("  record ................................... record a new script");
    qWarning("  play ..................................... playback an existing script");
    qWarning("  testimages ............................... record images or compare images on playback");
    qWarning("  testerror ................................ test 'error' property of root item on playback");
    qWarning("  exitoncomplete ........................... cleanly exit the viewer on script completion");
    qWarning("  exitonfailure ............................ immediately exit the viewer on script failure");
    qWarning("  saveonexit ............................... save recording on viewer exit");
    qWarning(" ");
    qWarning(" One of record, play or both must be specified.");
    exit(1);
}

int main(int argc, char ** argv)
{
#if defined (Q_OS_SYMBIAN)
    qInstallMsgHandler(myMessageOutput);
#endif

#if defined (Q_WS_X11)
    //### default to using raster graphics backend for now
    bool gsSpecified = false;
    for (int i = 0; i < argc; ++i) {
        QString arg = argv[i];
        if (arg == "-graphicssystem") {
            gsSpecified = true;
            break;
        }
    }

    if (!gsSpecified)
        QApplication::setGraphicsSystem("raster");
#endif

    QApplication app(argc, argv);
    app.setApplicationName("viewer");
    app.setOrganizationName("Nokia");
    app.setOrganizationDomain("nokia.com");

    bool frameless = false;
    bool resizeview = false;
    QString fileName;
    double fps = 0;
    int autorecord_from = 0;
    int autorecord_to = 0;
    QString dither = "none";
    QString recordfile;
    QStringList recordargs;
    QStringList libraries;
    QString skin;
    QString script;
    QString scriptopts;
    bool runScript = false;
    bool devkeys = false;
    int cache = 0;
    QString translationFile;
    bool useGL = false;
    bool fullScreen = false;
    bool stayOnTop = false;
    bool maximized = false;
    bool useNativeFileBrowser = true;

#if defined(Q_OS_SYMBIAN)
    maximized = true;
    useNativeFileBrowser = false;
#endif

    for (int i = 1; i < argc; ++i) {
        bool lastArg = (i == argc - 1);
        QString arg = argv[i];
        if (arg == "-frameless") {
            frameless = true;
        } else if (arg == "-maximized") {
            maximized = true;
        } else if (arg == "-fullscreen") {
            fullScreen = true;
        } else if (arg == "-stayontop") {
            stayOnTop = true;
        } else if (arg == "-skin") {
            if (lastArg) usage();
            skin = QString(argv[++i]);
        } else if (arg == "-resizeview") {
            resizeview = true;
        } else if (arg == "-netcache") {
            if (lastArg) usage();
            cache = QString(argv[++i]).toInt();
        } else if (arg == "-recordrate") {
            if (lastArg) usage();
            fps = QString(argv[++i]).toDouble();
        } else if (arg == "-recordfile") {
            if (lastArg) usage();
            recordfile = QString(argv[++i]);
        } else if (arg == "-record") {
            if (lastArg) usage();
            recordargs << QString(argv[++i]);
        } else if (arg == "-recorddither") {
            if (lastArg) usage();
            dither = QString(argv[++i]);
        } else if (arg == "-autorecord") {
            if (lastArg) usage();
            QString range = QString(argv[++i]);
            int dash = range.indexOf('-');
            if (dash > 0)
                autorecord_from = range.left(dash).toInt();
            autorecord_to = range.mid(dash+1).toInt();
        } else if (arg == "-devicekeys") {
            devkeys = true;
        } else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
            fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
            return 0;
        } else if (arg == "-translation") {
            if (lastArg) usage();
            translationFile = argv[++i];
        } else if (arg == "-opengl") {
            useGL = true;
        } else if (arg == "-L") {
            if (lastArg) usage();
            libraries << QString(argv[++i]);
        } else if (arg == "-script") {
            if (lastArg) usage();
            script = QString(argv[++i]);
        } else if (arg == "-scriptopts") {
            if (lastArg) usage();
            scriptopts = QString(argv[++i]);
        } else if (arg == "-savescript") {
            if (lastArg) usage();
            script = QString(argv[++i]);
            runScript = false;
        } else if (arg == "-playscript") {
            if (lastArg) usage();
            script = QString(argv[++i]);
            runScript = true;
        } else if (arg[0] != '-') {
            fileName = arg;
        } else if (1 || arg == "-help") {
            usage();
        }
    }

    QTranslator qmlTranslator;
    if (!translationFile.isEmpty()) {
        qmlTranslator.load(translationFile);
        app.installTranslator(&qmlTranslator);
    }

    Qt::WFlags wflags = (frameless ? Qt::FramelessWindowHint : Qt::Widget);
    if (stayOnTop)
        wflags |= Qt::WindowStaysOnTopHint;

    QmlViewer viewer(0, wflags);
    if (!scriptopts.isEmpty()) {
        QStringList options =
            scriptopts.split(QLatin1Char(','), QString::SkipEmptyParts);

        QmlViewer::ScriptOptions scriptOptions = 0;
        for (int i = 0; i < options.count(); ++i) {
            const QString &option = options.at(i);
            if (option == QLatin1String("help")) {
                scriptOptsUsage();
            } else if (option == QLatin1String("play")) {
                scriptOptions |= QmlViewer::Play;
            } else if (option == QLatin1String("record")) {
                scriptOptions |= QmlViewer::Record;
            } else if (option == QLatin1String("testimages")) {
                scriptOptions |= QmlViewer::TestImages;
            } else if (option == QLatin1String("testerror")) {
                scriptOptions |= QmlViewer::TestErrorProperty;
            } else if (option == QLatin1String("exitoncomplete")) {
                scriptOptions |= QmlViewer::ExitOnComplete;
            } else if (option == QLatin1String("exitonfailure")) {
                scriptOptions |= QmlViewer::ExitOnFailure;
            } else if (option == QLatin1String("saveonexit")) {
                scriptOptions |= QmlViewer::SaveOnExit;
            } else {
                scriptOptsUsage();
            }
        }

        if (script.isEmpty())
            usage();

        if (!(scriptOptions & QmlViewer::Record) && !(scriptOptions & QmlViewer::Play))
            scriptOptsUsage();
        viewer.setScriptOptions(scriptOptions);
        viewer.setScript(script);
    }  else if (!script.isEmpty()) {
        usage();
    }

    foreach (QString lib, libraries)
        viewer.addLibraryPath(lib);
    viewer.setNetworkCacheSize(cache);
    viewer.setRecordFile(recordfile);
    if (resizeview)
        viewer.setScaleView();
    if (fps>0)
        viewer.setRecordRate(fps);
    if (autorecord_to)
        viewer.setAutoRecord(autorecord_from,autorecord_to);
    if (!skin.isEmpty()) {
        if (skin == "list") {
            foreach (QString s, viewer.builtinSkins())
                qWarning(s.toUtf8());
            exit(0);
        } else {
            viewer.setSkin(skin);
        }
    }
    if (devkeys)
        viewer.setDeviceKeys(true);
    viewer.setRecordDither(dither);
    if (recordargs.count())
        viewer.setRecordArgs(recordargs);

    viewer.setUseNativeFileBrowser(useNativeFileBrowser);
    if (fullScreen && maximized)
        qWarning() << "Both -fullscreen and -maximized specified. Using -fullscreen.";
    if (!fileName.isEmpty()) {
        viewer.open(fileName);
        fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
    } else {
        if (!useNativeFileBrowser)
            viewer.openFile();
        fullScreen ? viewer.showFullScreen() : maximized ? viewer.showMaximized() : viewer.show();
        if (useNativeFileBrowser)
            viewer.openFile();
    }
    viewer.setUseGL(useGL);
    viewer.raise();

    return app.exec();
}
<|endoftext|>


<commit_before>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <QMultiHash>
#include <QTime>
#include "DustLib.hpp"
#include "DustEmissivity.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "PanDustSystem.hpp"
#include "Parallel.hpp"
#include "ParallelFactory.hpp"
#include "PeerToPeerCommunicator.hpp"
#include "StaggeredAssigner.hpp"
#include "TimeLogger.hpp"
#include "WavelengthGrid.hpp"
#include "TextOutFile.hpp"

using namespace std;

////////////////////////////////////////////////////////////////////

DustLib::DustLib()
    : _assigner(0)
{
}

////////////////////////////////////////////////////////////////////

void DustLib::setupSelfBefore()
{
    SimulationItem::setupSelfBefore();

    // If no assigner was set, use a StaggeredAssigner as default
    if (!_assigner) setAssigner(new StaggeredAssigner(this));
}

////////////////////////////////////////////////////////////////////

void DustLib::setAssigner(ProcessAssigner* value)
{
    if (_assigner) delete _assigner;
    _assigner = value;
    if (_assigner) _assigner->setParent(this);
}

////////////////////////////////////////////////////////////////////

ProcessAssigner* DustLib::assigner() const
{
    return _assigner;
}

////////////////////////////////////////////////////////////////////

namespace
{
    class EmissionCalculator : public ParallelTarget
    {
    private:
        // data members initialized in constructor
        ArrayTable<2>& _Lvv;        // output luminosities indexed on m or n and ell (writable reference)
        QMultiHash<int,int> _mh;    // hash map <n,m> of cells for each library entry
        Log* _log;
        PanDustSystem* _ds;
        DustEmissivity* _de;
        WavelengthGrid* _lambdagrid;
        int _Nlambda;
        int _Ncomp;
        QTime _timer;           // measures the time elapsed since the most recent log message

    public:
        // constructor
        EmissionCalculator(ArrayTable<2>& Lvv, vector<int>& nv, int Nlib, SimulationItem* item)
            : _Lvv(Lvv)
        {
            // get basic information about the wavelength grid and the dust system
            _log = item->find<Log>();
            _ds = item->find<PanDustSystem>();
            _de = item->find<DustEmissivity>();
            _lambdagrid = item->find<WavelengthGrid>();
            _Nlambda = _lambdagrid->Nlambda();
            _Ncomp = _ds->Ncomp();

            // invert mapping vector into a temporary hash map
            int Ncells = nv.size();
            _mh.reserve(Ncells);
            for (int m=0; m<Ncells; m++) if (nv[m] >= 0) _mh.insert(nv[m],m);

            // log usage statistics
            int Nused = _mh.uniqueKeys().size();
            _log->info("Library entries in use: " + QString::number(Nused) +
                                       " out of " + QString::number(Nlib) + ".");

            // resize result vectors appropriately (for every cell or for every library entry)
            // If there are multiple dust components, the _Lvv vector is indexed on m (the dust cells)
            int Nout = _Ncomp>1 ? Ncells : Nlib;
            _Lvv.resize(Nout,_Nlambda);  // also sets all values to zero

            // start the logging timer
            _timer.start();
        }

        // the parallized loop body; calculates the emission for a single library entry
        void body(size_t n)
        {
            // get the list of dust cells that map to this library entry
            QList<int> mv = _mh.values(n);
            int Nmapped = mv.size();

            // if this library entry is used by at least one cell, calculate the emission for those cells
            if (Nmapped > 0)
            {
                if (_de->logfrequency())
                {
                    // space the messages at least 5 seconds apart; in the interest of speed,
                    // we do this without locking, so once in a while two consecutive messages may slip through
                    if (_timer.elapsed() > 5000)
                    {
                        _timer.restart();
                        _log->info("Calculating emission for library entry " + QString::number(n+1) + "...");
                    }
                }

                // calculate the average ISRF for this library entry from the ISRF of all dust cells that map to it
                Array Jv(_Nlambda);
                foreach (int m, mv) Jv += _ds->meanintensityv(m);
                Jv /= Nmapped;

                // multiple dust components: calculate emission for each dust cell separately
                if (_Ncomp > 1)
                {
                    // get emissivity for each dust component (i.e. for the corresponding dust mix)
                    ArrayTable<2> evv(_Ncomp,0);
                    for (int h=0; h<_Ncomp; h++) evv[h] = _de->emissivity(_ds->mix(h),Jv);

                    // combine emissivities into SED for each dust cell, and store the normalized SEDs
                    foreach (int m, mv)
                    {
                        // get a reference to the output array for this dust cell
                        Array& Lv = _Lvv[m];

                        // calculate the emission for this cell
                        for (int h=0; h<_Ncomp; h++) Lv += evv[h] * _ds->density(m,h);

                        // convert to luminosities and normalize the result
                        Lv *= _lambdagrid->dlambdav();
                        double total = Lv.sum();
                        if (total>0) Lv /= total;
                    }
                }

                // single dust component: remember just the libary template, which serves for all mapped cells
                else
                {
                    // get a reference to the output array for this library entry
                    Array& Lv = _Lvv[n];

                    // get the emissivity of the library entry
                    Lv = _de->emissivity(_ds->mix(0),Jv);

                    // convert to luminosities and normalize the result
                    Lv *= _lambdagrid->dlambdav();
                    double total = Lv.sum();
                    if (total>0) Lv /= total;
                }
            }
        }
    };
}

////////////////////////////////////////////////////////////////////

void DustLib::calculate()
{
    // get mapping from cells to library entries
    int Nlib = entries();
    _nv = mapping();

    // assign each process to a set of library entries
    _assigner->assign(Nlib);

    // calculate the emissivity for each library entry assigned to this process
    EmissionCalculator calc(_Lvv, _nv, Nlib, this);
    Parallel* parallel = find<ParallelFactory>()->parallel();
    parallel->call(&calc, _assigner);

    // Wait for the other processes to reach this point
    PeerToPeerCommunicator* comm = find<PeerToPeerCommunicator>();
    comm->wait("the emission spectra calculation");

    // assemble _Lvv from the information stored at different processes, if the work is done in parallel processes
    if (_assigner->parallel()) assemble();

}

////////////////////////////////////////////////////////////////////

double DustLib::luminosity(int m, int ell) const
{
    size_t Ncells = _nv.size();
    if (_Lvv.size(0) == Ncells)     // _Lvv is indexed on m, the index of the dust cells
    {
        return _Lvv[m][ell];
    }
    else    // _Lvv is indexed on n, the library entry index
    {
        int n = _nv[m];
        return n>=0 ? _Lvv[n][ell] : 0.;
    }
}

////////////////////////////////////////////////////////////////////

void DustLib::assemble()
{
    // Get a pointer to the PeerToPeerCommunicator of this simulation
    PeerToPeerCommunicator* comm = find<PeerToPeerCommunicator>();

    Log* log = find<Log>();
    TimeLogger logger(log->verbose() && comm->isMultiProc() ? log : 0, "communication of the dust emission spectra");

    size_t Ncells = _nv.size();
    if (_Lvv.size(0) == Ncells)     // _Lvv is indexed on m, the index of the dust cells
    {
        for (size_t m = 0; m < Ncells; m++) // for each dust cell
        {
            size_t n = _nv[m];                      // get the library index for this dust cell ..
            int rank = _assigner->rankForIndex(n);    // .. to determine which process calculated the emission SED

            // finally, broadcast the emission SED from that process to all the other processes
            comm->broadcast(_Lvv[m],rank);
        }

    }
    else    // _Lvv is indexed on n, the library entry index
    {
        for (size_t n = 0; n < _Lvv.size(0); n++)   // for each library entry
        {
            int rank = _assigner->rankForIndex(n);    // determine which process calculated the emission SED of this entry

            // broadcast the emission SED from that process to all the other processes
            comm->broadcast(_Lvv[n],rank);
        }
    }
}

////////////////////////////////////////////////////////////////////
<commit_msg>print densities<commit_after>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <QMultiHash>
#include <QTime>
#include "DustLib.hpp"
#include "DustEmissivity.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "PanDustSystem.hpp"
#include "Parallel.hpp"
#include "ParallelFactory.hpp"
#include "PeerToPeerCommunicator.hpp"
#include "StaggeredAssigner.hpp"
#include "TimeLogger.hpp"
#include "WavelengthGrid.hpp"
#include "TextOutFile.hpp"

using namespace std;

////////////////////////////////////////////////////////////////////

DustLib::DustLib()
    : _assigner(0)
{
}

////////////////////////////////////////////////////////////////////

void DustLib::setupSelfBefore()
{
    SimulationItem::setupSelfBefore();

    // If no assigner was set, use a StaggeredAssigner as default
    if (!_assigner) setAssigner(new StaggeredAssigner(this));
}

////////////////////////////////////////////////////////////////////

void DustLib::setAssigner(ProcessAssigner* value)
{
    if (_assigner) delete _assigner;
    _assigner = value;
    if (_assigner) _assigner->setParent(this);
}

////////////////////////////////////////////////////////////////////

ProcessAssigner* DustLib::assigner() const
{
    return _assigner;
}

////////////////////////////////////////////////////////////////////

namespace
{
    class EmissionCalculator : public ParallelTarget
    {
    private:
        // data members initialized in constructor
        ArrayTable<2>& _Lvv;        // output luminosities indexed on m or n and ell (writable reference)
        QMultiHash<int,int> _mh;    // hash map <n,m> of cells for each library entry
        Log* _log;
        PanDustSystem* _ds;
        DustEmissivity* _de;
        WavelengthGrid* _lambdagrid;
        int _Nlambda;
        int _Ncomp;
        QTime _timer;           // measures the time elapsed since the most recent log message

    public:
        // constructor
        EmissionCalculator(ArrayTable<2>& Lvv, vector<int>& nv, int Nlib, SimulationItem* item)
            : _Lvv(Lvv)
        {
            // get basic information about the wavelength grid and the dust system
            _log = item->find<Log>();
            _ds = item->find<PanDustSystem>();
            _de = item->find<DustEmissivity>();
            _lambdagrid = item->find<WavelengthGrid>();
            _Nlambda = _lambdagrid->Nlambda();
            _Ncomp = _ds->Ncomp();

            // invert mapping vector into a temporary hash map
            int Ncells = nv.size();
            _mh.reserve(Ncells);
            for (int m=0; m<Ncells; m++) if (nv[m] >= 0) _mh.insert(nv[m],m);

            // log usage statistics
            int Nused = _mh.uniqueKeys().size();
            _log->info("Library entries in use: " + QString::number(Nused) +
                                       " out of " + QString::number(Nlib) + ".");

            // resize result vectors appropriately (for every cell or for every library entry)
            // If there are multiple dust components, the _Lvv vector is indexed on m (the dust cells)
            int Nout = _Ncomp>1 ? Ncells : Nlib;
            _Lvv.resize(Nout,_Nlambda);  // also sets all values to zero

            // start the logging timer
            _timer.start();
        }

        // the parallized loop body; calculates the emission for a single library entry
        void body(size_t n)
        {
            // get the list of dust cells that map to this library entry
            QList<int> mv = _mh.values(n);
            int Nmapped = mv.size();

            // if this library entry is used by at least one cell, calculate the emission for those cells
            if (Nmapped > 0)
            {
                if (_de->logfrequency())
                {
                    // space the messages at least 5 seconds apart; in the interest of speed,
                    // we do this without locking, so once in a while two consecutive messages may slip through
                    if (_timer.elapsed() > 5000)
                    {
                        _timer.restart();
                        _log->info("Calculating emission for library entry " + QString::number(n+1) + "...");
                    }
                }

                // calculate the average ISRF for this library entry from the ISRF of all dust cells that map to it
                Array Jv(_Nlambda);
                foreach (int m, mv) Jv += _ds->meanintensityv(m);
                Jv /= Nmapped;

                // multiple dust components: calculate emission for each dust cell separately
                if (true)//_Ncomp > 1)
                {
                    // get emissivity for each dust component (i.e. for the corresponding dust mix)
                    ArrayTable<2> evv(_Ncomp,0);
                    for (int h=0; h<_Ncomp; h++) evv[h] = _de->emissivity(_ds->mix(h),Jv);

                    // combine emissivities into SED for each dust cell, and store the normalized SEDs
                    foreach (int m, mv)
                    {
                        // get a reference to the output array for this dust cell
                        Array& Lv = _Lvv[m];

                        // calculate the emission for this cell
                        for (int h=0; h<_Ncomp; h++)
                        {
                            Lv += evv[h] * _ds->density(m,h);
                            if (m % 100 == 0) _log->info("density("+QString::number(m)+",0) == "
                                                         +QString::number(_ds->density(m,h)));
                        }

                        // convert to luminosities and normalize the result
                        Lv *= _lambdagrid->dlambdav();
                        double total = Lv.sum();
                        if (total>0) Lv /= total;
                    }
                }

                // single dust component: remember just the libary template, which serves for all mapped cells
                else
                {
                    // get a reference to the output array for this library entry
                    Array& Lv = _Lvv[n];

                    // get the emissivity of the library entry
                    Lv = _de->emissivity(_ds->mix(0),Jv);

                    // convert to luminosities and normalize the result
                    Lv *= _lambdagrid->dlambdav();
                    double total = Lv.sum();
                    if (total>0) Lv /= total;
                }
            }
        }
    };
}

////////////////////////////////////////////////////////////////////

void DustLib::calculate()
{
    // get mapping from cells to library entries
    int Nlib = entries();
    _nv = mapping();

    // assign each process to a set of library entries
    _assigner->assign(Nlib);

    // calculate the emissivity for each library entry assigned to this process
    EmissionCalculator calc(_Lvv, _nv, Nlib, this);
    Parallel* parallel = find<ParallelFactory>()->parallel();
    parallel->call(&calc, _assigner);

    // Wait for the other processes to reach this point
    PeerToPeerCommunicator* comm = find<PeerToPeerCommunicator>();
    comm->wait("the emission spectra calculation");

    // assemble _Lvv from the information stored at different processes, if the work is done in parallel processes
    if (_assigner->parallel()) assemble();

}

////////////////////////////////////////////////////////////////////

double DustLib::luminosity(int m, int ell) const
{
    size_t Ncells = _nv.size();
    if (_Lvv.size(0) == Ncells)     // _Lvv is indexed on m, the index of the dust cells
    {
        return _Lvv[m][ell];
    }
    else    // _Lvv is indexed on n, the library entry index
    {
        int n = _nv[m];
        return n>=0 ? _Lvv[n][ell] : 0.;
    }
}

////////////////////////////////////////////////////////////////////

void DustLib::assemble()
{
    // Get a pointer to the PeerToPeerCommunicator of this simulation
    PeerToPeerCommunicator* comm = find<PeerToPeerCommunicator>();

    Log* log = find<Log>();
    TimeLogger logger(log->verbose() && comm->isMultiProc() ? log : 0, "communication of the dust emission spectra");

    size_t Ncells = _nv.size();
    if (_Lvv.size(0) == Ncells)     // _Lvv is indexed on m, the index of the dust cells
    {
        for (size_t m = 0; m < Ncells; m++) // for each dust cell
        {
            size_t n = _nv[m];                      // get the library index for this dust cell ..
            int rank = _assigner->rankForIndex(n);    // .. to determine which process calculated the emission SED

            // finally, broadcast the emission SED from that process to all the other processes
            comm->broadcast(_Lvv[m],rank);
        }

    }
    else    // _Lvv is indexed on n, the library entry index
    {
        for (size_t n = 0; n < _Lvv.size(0); n++)   // for each library entry
        {
            int rank = _assigner->rankForIndex(n);    // determine which process calculated the emission SED of this entry

            // broadcast the emission SED from that process to all the other processes
            comm->broadcast(_Lvv[n],rank);
        }
    }
}

////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright 2020 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <Tensile/msgpack/MessagePack.hpp>

#include <Tensile/msgpack/Loading.hpp>

#include <fstream>

namespace Tensile
{
    namespace Serialization
    {
        void objectToMap(msgpack::object&                                  object,
                         std::unordered_map<std::string, msgpack::object>& result)
        {
            if(object.type != msgpack::type::object_type::MAP)
                throw std::runtime_error(concatenate("Expected MAP, found ", object.type));

            for(uint32_t i = 0; i < object.via.map.size; i++)
            {
                auto& element = object.via.map.ptr[i];

                std::string key;
                switch(element.key.type)
                {
                case msgpack::type::object_type::STR:
                {
                    element.key.convert(key);
                    break;
                }
                case msgpack::type::object_type::POSITIVE_INTEGER:
                {
                    auto iKey = element.key.as<uint32_t>();
                    key       = std::to_string(iKey);
                    break;
                }
                default:
                    throw std::runtime_error("Unexpected map key type");
                }

                result[key] = std::move(element.val);
            }
        }
    }

    template <typename MyProblem, typename MySolution>
    std::shared_ptr<SolutionLibrary<MyProblem, MySolution>>
        MessagePackLoadLibraryFile(std::string const& filename)
    {
        try
        {
            std::ifstream        in(filename, std::ios::in | std::ios::binary);
            std::vector<uint8_t> data((std::istreambuf_iterator<char>(in)),
                                      std::istreambuf_iterator<char>());

            return MessagePackLoadLibraryData<MyProblem, MySolution>(data);
        }
        catch(std::runtime_error const& exc)
        {
            if(Debug::Instance().printDataInit())
                std::cout << "Error loading " << filename << "(msgpack):" << std::endl
                          << exc.what() << std::endl;

            return nullptr;
        }
    }

    template <typename MyProblem, typename MySolution>
    std::shared_ptr<SolutionLibrary<MyProblem, MySolution>>
        MessagePackLoadLibraryData(std::vector<uint8_t> const& data)
    {
        try
        {
            std::shared_ptr<MasterSolutionLibrary<MyProblem, MySolution>> rv;

            auto result = msgpack::unpack((const char*)data.data(), data.size());
            Serialization::MessagePackInput min(result.get());

            Serialization::PointerMappingTraits<Tensile::MasterContractionLibrary,
                                                Serialization::MessagePackInput>::mapping(min, rv);

            if(!min.error.empty())
            {
                std::ostringstream msg;
                msg << "Error loading msgpack data:" << std::endl;
                for(auto const& err : min.error)
                    msg << err << std::endl;

                throw std::runtime_error(msg.str());
            }

            return rv;
        }
        catch(std::runtime_error const& exc)
        {
            if(Debug::Instance().printDataInit())
                std::cout << "Error loading msgpack data:" << std::endl << exc.what() << std::endl;

            return nullptr;
        }
    }

    template std::shared_ptr<SolutionLibrary<ContractionProblem, ContractionSolution>>
        MessagePackLoadLibraryFile<ContractionProblem, ContractionSolution>(
            std::string const& filename);

    template std::shared_ptr<SolutionLibrary<ContractionProblem, ContractionSolution>>
        MessagePackLoadLibraryData<ContractionProblem, ContractionSolution>(
            std::vector<uint8_t> const& data);
}
<commit_msg>Optimize MessagePackLoadLibraryFile (#1471)<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright 2020-2022 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <Tensile/msgpack/MessagePack.hpp>

#include <Tensile/msgpack/Loading.hpp>

#include <fstream>

namespace Tensile
{
    namespace Serialization
    {
        void objectToMap(msgpack::object&                                  object,
                         std::unordered_map<std::string, msgpack::object>& result)
        {
            if(object.type != msgpack::type::object_type::MAP)
                throw std::runtime_error(concatenate("Expected MAP, found ", object.type));

            for(uint32_t i = 0; i < object.via.map.size; i++)
            {
                auto& element = object.via.map.ptr[i];

                std::string key;
                switch(element.key.type)
                {
                case msgpack::type::object_type::STR:
                {
                    element.key.convert(key);
                    break;
                }
                case msgpack::type::object_type::POSITIVE_INTEGER:
                {
                    auto iKey = element.key.as<uint32_t>();
                    key       = std::to_string(iKey);
                    break;
                }
                default:
                    throw std::runtime_error("Unexpected map key type");
                }

                result[key] = std::move(element.val);
            }
        }
    }

    template <typename MyProblem, typename MySolution>
    std::shared_ptr<SolutionLibrary<MyProblem, MySolution>>
        MessagePackLoadLibraryFile(std::string const& filename)
    {
        // parse file into a msgpack::object_handle
        msgpack::object_handle result;
        try
        {
            std::ifstream in(filename, std::ios::in | std::ios::binary);
            if(!in.is_open())
            {
                if(Debug::Instance().printDataInit())
                    std::cout << "Error loading " << filename << " (msgpack):\nFailed to open file"
                              << std::endl;

                return nullptr;
            }

            msgpack::unpacker unp;
            bool              finished_parsing;
            constexpr size_t  buffer_size = 1 << 19;
            do
            {
                unp.reserve_buffer(buffer_size);
                in.read(unp.buffer(), buffer_size);
                unp.buffer_consumed(in.gcount());
                finished_parsing = unp.next(result); // may throw msgpack::parse_error
            } while(!finished_parsing && !in.fail());

            if(!finished_parsing)
            {
                if(Debug::Instance().printDataInit())
                {
                    const char* const error_str
                        = in.eof() ? "Unexpected end of file" : "Read failure";
                    std::cout << "Error loading " << filename << " (msgpack):\n"
                              << error_str << std::endl;
                }

                return nullptr;
            }
        }
        catch(std::runtime_error const& exc)
        {
            if(Debug::Instance().printDataInit())
                std::cout << "Error loading msgpack data:\n" << exc.what() << std::endl;

            return nullptr;
        }

        // copy data from msgpack::object_handle into MasterSolutionLibrary
        try
        {
            std::shared_ptr<MasterSolutionLibrary<MyProblem, MySolution>> rv;

            Serialization::MessagePackInput min(result.get());

            Serialization::PointerMappingTraits<Tensile::MasterContractionLibrary,
                                                Serialization::MessagePackInput>::mapping(min, rv);

            if(!min.error.empty())
            {
                std::ostringstream msg;
                msg << "Error loading msgpack data:\n";
                for(auto const& err : min.error)
                    msg << err << std::endl;

                throw std::runtime_error(msg.str());
            }

            return rv;
        }
        catch(std::runtime_error const& exc)
        {
            if(Debug::Instance().printDataInit())
                std::cout << "Error loading msgpack data:\n" << exc.what() << std::endl;

            return nullptr;
        }
    }

    template <typename MyProblem, typename MySolution>
    std::shared_ptr<SolutionLibrary<MyProblem, MySolution>>
        MessagePackLoadLibraryData(std::vector<uint8_t> const& data)
    {
        try
        {
            std::shared_ptr<MasterSolutionLibrary<MyProblem, MySolution>> rv;

            auto result = msgpack::unpack((const char*)data.data(), data.size());
            Serialization::MessagePackInput min(result.get());

            Serialization::PointerMappingTraits<Tensile::MasterContractionLibrary,
                                                Serialization::MessagePackInput>::mapping(min, rv);

            if(!min.error.empty())
            {
                std::ostringstream msg;
                msg << "Error loading msgpack data:" << std::endl;
                for(auto const& err : min.error)
                    msg << err << std::endl;

                throw std::runtime_error(msg.str());
            }

            return rv;
        }
        catch(std::runtime_error const& exc)
        {
            if(Debug::Instance().printDataInit())
                std::cout << "Error loading msgpack data:" << std::endl << exc.what() << std::endl;

            return nullptr;
        }
    }

    template std::shared_ptr<SolutionLibrary<ContractionProblem, ContractionSolution>>
        MessagePackLoadLibraryFile<ContractionProblem, ContractionSolution>(
            std::string const& filename);

    template std::shared_ptr<SolutionLibrary<ContractionProblem, ContractionSolution>>
        MessagePackLoadLibraryData<ContractionProblem, ContractionSolution>(
            std::vector<uint8_t> const& data);
}
<|endoftext|>


<commit_before>#ifdef _WIN32
#define M_PI 3.14
#endif

#include <cmath>
#include <iostream>
#include <fstream>

#include "Body.hpp"

#define G 15 // TODO: Get the right number
#define SIZE 6
#define DENSITY 7878 // kg/m^3

using namespace sf;
using namespace std;

Body::Body(Vector2f pos, int m, Vector2f dir)
	: position(pos), direction(dir), mass(m)
{
	/*
	float volume = DENSITY / mass;
	float radius = cbrt(3*volume/4*M_PI) * 0.5;
	*/
	shape.setRadius(mass / 2);
	shape.setFillColor(Color::Red);
}

void Body::move(float dt)
{
	position += direction * dt;
}

void Body::applyGravityOf(const Body &b, float dt)
{
	// Get the force between bodies
	float F = fabs(G * ((mass*b.mass) / (getDistanceTo(b)*getDistanceTo(b)) ) );

	// Get the unit vector to the other body
	Vector2f to_Body(b.position - position);
	to_Body = to_Body / getDistanceTo(b); // unit vector = v / v.length

	// Apply the force in the direction of the other body
	position += (to_Body * F) * dt;
}

float Body::getDistanceTo(const Body &p)
{
	Vector2f a = this->position;
	Vector2f b = p.position;

	return sqrt((b.x-a.x)*(b.x-a.x) + (b.y*a.y)*(b.y*a.y));
}

void Body::draw(RenderWindow &window)
{
	shape.setPosition(position);
	window.draw(shape);
}

bool Body::operator!=(const Body& b)
{
	return (this->direction != b.direction) && (this->mass != b.mass) && (this->position != b.position);
}
<commit_msg>fixed a regression (previous did'nt work)<commit_after>#ifdef _WIN32
#define M_PI 3.14
#endif

#include <cmath>
#include <iostream>
#include <fstream>

#include "Body.hpp"

#define G 15 // TODO: Get the right number
#define SIZE 6
#define DENSITY 7878 // kg/m^3

using namespace sf;
using namespace std;

Body::Body(Vector2f pos, int m, Vector2f dir)
	: position(pos), direction(dir), mass(m)
{
	float volume = DENSITY / mass;
	float radius = cbrt(3*volume/4*M_PI) * 0.5;
	shape.setRadius(radius);
	shape.setFillColor(Color::Red);
}

void Body::move(float dt)
{
	position += direction * dt;
}

void Body::applyGravityOf(const Body &b, float dt)
{
	// Get the force between bodies
	if (getDistanceTo(b) < 0)
		cout << "R" << endl;
	float F = fabs(G * (mass*b.mass / getDistanceTo(b)*getDistanceTo(b) ) );
	// cout << F << endl;

	// Get the unit vector to the other body
	Vector2f to_Body(b.position - position);
	to_Body = to_Body / getDistanceTo(b);

	// Apply the force in the direction of the other body
	cout << ((to_Body * F) * dt).x << ';' << ((to_Body * F) * dt).y << endl;
	position += (to_Body * F) * dt;
}

float Body::getDistanceTo(const Body &p)
{
	Vector2f a = this->position;
	Vector2f b = p.position;

	return sqrt((b.x-a.x)*(b.x-a.x)+(b.y*a.y)*(b.y*a.y));
}

void Body::draw(RenderWindow &window)
{
	shape.setPosition(position);
	window.draw(shape);
}

bool Body::operator!=(const Body& b)
{
	return (this->direction != b.direction) && (this->mass != b.mass) && (this->position != b.position);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlccompile.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 12:26:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif

#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2_00
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<commit_msg>INTEGRATION: CWS gcc430two (1.22.14); FILE MERGED 2008/01/28 09:53:07 rene 1.22.14.1: more gcc 4.3.0 things<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlccompile.cxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: ihi $ $Date: 2008-02-04 13:44:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif

#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

#include <string.h>

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2_00
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
/*!
 * \file neutron_diffusion.cpp
 * \author Stuart R. Slattery
 * \brief Neutron diffusion driver.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <string>
#include <cassert>

#include "DiffusionProblem.hpp"
#include "Partitioner.hpp"
#include "VTKOutput.hpp"

#include <Chimera_LinearSolver.hpp>
#include <Chimera_LinearSolverFactory.hpp>
#include <Chimera_OperatorTools.hpp>

#include <MCLS_SolverFactory.hpp>
#include <MCLS_SolverManager.hpp>
#include <MCLS_LinearProblem.hpp>
#include <MCLS_TpetraAdapter.hpp>

#include <Teuchos_GlobalMPISession.hpp>
#include <Teuchos_FancyOStream.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>
#include <Teuchos_ParameterList.hpp>
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"
#include <Teuchos_TimeMonitor.hpp>
#include <Teuchos_Time.hpp>

#include <Tpetra_Map.hpp>
#include <Tpetra_CrsMatrix.hpp>
#include <Tpetra_Vector.hpp>
#include <Tpetra_MultiVector.hpp>
#include <Tpetra_Operator.hpp>

#include <BelosConfigDefs.hpp>
#include <BelosLinearProblem.hpp>
#include <BelosTpetraAdapter.hpp>
#include <BelosPseudoBlockGmresSolMgr.hpp>
#include <BelosPseudoBlockCGSolMgr.hpp>

//---------------------------------------------------------------------------//
int main( int argc, char * argv[] )
{
    // Initialize parallel communication.
    Teuchos::GlobalMPISession mpi_session( &argc, &argv );
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    Teuchos::FancyOStream out( Teuchos::rcpFromRef( std::cout ) );
    out.setOutputToRootOnly( 0 );
    out.setShowProcRank( true );

    // Read in command line options.
    std::string xml_input_filename;
    Teuchos::CommandLineProcessor clp(false);
    clp.setOption( "xml-in-file",
		   &xml_input_filename,
		   "The XML file to read into a parameter list" );
    clp.parse(argc,argv);

    // Build the parameter list from the xml input.
    Teuchos::RCP<Teuchos::ParameterList> plist =
	Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile(
	xml_input_filename, Teuchos::inoutArg(*plist) );

    // Build and partition the mesh.
    Teuchos::RCP<Chimera::Partitioner> partitioner = Teuchos::rcp(
	new Chimera::Partitioner( comm, plist ) );

    // Build the diffusion problem.
    Teuchos::RCP<Chimera::DiffusionProblem> diffusion_problem = Teuchos::rcp(
	new Chimera::DiffusionProblem( comm, partitioner, plist, true ) );

    // // CHIMERA SOLVE
    // Build the solver.
    Teuchos::RCP<Chimera::LinearSolver<double,int,int> > csolver =
        Chimera::LinearSolverFactory::create(
            plist, diffusion_problem->getProblem() );

    // Compute the iteration matrix spectral radius.
    double spec_rad = Chimera::OperatorTools::spectralRadius(
        csolver->linearOperatorSplit()->iterationMatrix() );
    if ( comm->getRank() == 0 )
    {
        std::cout << "SPECTRAL RADIUS: " << spec_rad << std::endl;
    }
    comm->barrier();

    typedef Tpetra::Vector<double,int,int> Vector;
    typedef Tpetra::CrsMatrix<double,int,int> Matrix;
    typedef Tpetra::MultiVector<double,int,int> MV;
    typedef Tpetra::Operator<double,int,int> OP;

    // MCLS SOLVE
    if ( "MCLS" == plist->get<std::string>("Solver Package") )
    {
        Teuchos::RCP<MCLS::LinearProblem<Vector,Matrix> > linear_problem =
            Teuchos::rcp( new MCLS::LinearProblem<Vector,Matrix>(
                              diffusion_problem->getProblem()->getOperator(),
                              diffusion_problem->getProblem()->getLHS(),
                              diffusion_problem->getProblem()->getRHS() ) );

        std::string solver_type = plist->get<std::string>("Solver Type");

        MCLS::SolverFactory<Vector,Matrix> factory;
        Teuchos::RCP<MCLS::SolverManager<Vector,Matrix> > solver_manager =
            factory.create( solver_type, comm, plist );
        solver_manager->setProblem( linear_problem );
        Teuchos::Time timer("");
        timer.start(true);
        solver_manager->solve();
        timer.stop();
        if ( comm->getRank() == 0 )
        {
            std::cout << "MCLS Solve: Complete in " << timer.totalElapsedTime()
                      << " seconds." << std::endl;
        }
    }

    // Belos Solve
    else if ( "Belos" == plist->get<std::string>("Solver Package") )
    {
        Teuchos::RCP<Teuchos::ParameterList> belosList = Teuchos::parameterList();
        belosList->set( "Maximum Iterations", 1000 );
        belosList->set( "Maximum Restarts", 10 );
        belosList->set( "Convergence Tolerance", 1.0e-8 );
        int verbosity = Belos::Errors + Belos::Warnings +
                        Belos::TimingDetails + Belos::StatusTestDetails;
        belosList->set( "Verbosity", verbosity );

        Teuchos::RCP<Belos::LinearProblem<double,MV,OP> > linear_problem
            = Teuchos::rcp( new Belos::LinearProblem<double,MV,OP>(
                                diffusion_problem->getProblem()->getOperator(),
                                diffusion_problem->getProblem()->getLHS(),
                                diffusion_problem->getProblem()->getRHS() ) );
        linear_problem->setProblem();

        Teuchos::RCP<Belos::SolverManager<double,MV,OP> > solver_manager;

        if ( "GMRES" == plist->get<std::string>("Solver Type") )
        {
            solver_manager = Teuchos::rcp(
                new Belos::PseudoBlockGmresSolMgr<double,MV,OP>(
                    linear_problem, belosList) );
        }
        else if ( "CG" == plist->get<std::string>("Solver Type") )
        {
            solver_manager = Teuchos::rcp(
                new Belos::PseudoBlockCGSolMgr<double,MV,OP>(
                    linear_problem, belosList) );
        }

        Teuchos::Time timer("");
        timer.start(true);
        solver_manager->solve();
        timer.stop();
        if ( comm->getRank() == 0 )
        {
            std::cout << "Belos Solve: Complete in " << timer.totalElapsedTime()
                      << " seconds." << std::endl;
            int numIters = solver_manager->getNumIters();
            std::cout << "Number of iterations performed for this solve: "
                      << numIters << std::endl;
        }
    }

    // Write the solution to VTK.
    Chimera::VTKOutput vtk_output( comm, partitioner, plist );
    vtk_output.addField( Chimera::VTKOutput::VERTEX_FIELD,
                         diffusion_problem->getProblem()->getLHS(),
                         "NEUTRON_FLUX" );
    vtk_output.write();

    return 0;
}

//---------------------------------------------------------------------------//
// end neutron_diffusion.cpp
//---------------------------------------------------------------------------//

<commit_msg>updating diffusion driver for consistent parameters between mcls and belos<commit_after>//---------------------------------------------------------------------------//
/*!
 * \file neutron_diffusion.cpp
 * \author Stuart R. Slattery
 * \brief Neutron diffusion driver.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <string>
#include <cassert>

#include "DiffusionProblem.hpp"
#include "Partitioner.hpp"
#include "VTKOutput.hpp"

#include <Chimera_LinearSolver.hpp>
#include <Chimera_LinearSolverFactory.hpp>
#include <Chimera_OperatorTools.hpp>

#include <MCLS_SolverFactory.hpp>
#include <MCLS_SolverManager.hpp>
#include <MCLS_LinearProblem.hpp>
#include <MCLS_TpetraAdapter.hpp>

#include <Teuchos_GlobalMPISession.hpp>
#include <Teuchos_FancyOStream.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>
#include <Teuchos_ParameterList.hpp>
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"
#include <Teuchos_TimeMonitor.hpp>
#include <Teuchos_Time.hpp>

#include <Tpetra_Map.hpp>
#include <Tpetra_CrsMatrix.hpp>
#include <Tpetra_Vector.hpp>
#include <Tpetra_MultiVector.hpp>
#include <Tpetra_Operator.hpp>

#include <BelosConfigDefs.hpp>
#include <BelosLinearProblem.hpp>
#include <BelosTpetraAdapter.hpp>
#include <BelosPseudoBlockGmresSolMgr.hpp>
#include <BelosPseudoBlockCGSolMgr.hpp>

//---------------------------------------------------------------------------//
int main( int argc, char * argv[] )
{
    // Initialize parallel communication.
    Teuchos::GlobalMPISession mpi_session( &argc, &argv );
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    Teuchos::FancyOStream out( Teuchos::rcpFromRef( std::cout ) );
    out.setOutputToRootOnly( 0 );
    out.setShowProcRank( true );

    // Read in command line options.
    std::string xml_input_filename;
    Teuchos::CommandLineProcessor clp(false);
    clp.setOption( "xml-in-file",
		   &xml_input_filename,
		   "The XML file to read into a parameter list" );
    clp.parse(argc,argv);

    // Build the parameter list from the xml input.
    Teuchos::RCP<Teuchos::ParameterList> plist =
	Teuchos::rcp( new Teuchos::ParameterList() );
    Teuchos::updateParametersFromXmlFile(
	xml_input_filename, Teuchos::inoutArg(*plist) );

    // Build and partition the mesh.
    Teuchos::RCP<Chimera::Partitioner> partitioner = Teuchos::rcp(
	new Chimera::Partitioner( comm, plist ) );

    // Build the diffusion problem.
    Teuchos::RCP<Chimera::DiffusionProblem> diffusion_problem = Teuchos::rcp(
	new Chimera::DiffusionProblem( comm, partitioner, plist, true ) );

    // // CHIMERA SOLVE
    // Build the solver.
    Teuchos::RCP<Chimera::LinearSolver<double,int,int> > csolver =
        Chimera::LinearSolverFactory::create(
            plist, diffusion_problem->getProblem() );

    // Compute the iteration matrix spectral radius.
    double spec_rad = Chimera::OperatorTools::spectralRadius(
        csolver->linearOperatorSplit()->iterationMatrix() );
    if ( comm->getRank() == 0 )
    {
        std::cout << "SPECTRAL RADIUS: " << spec_rad << std::endl;
    }
    comm->barrier();

    typedef Tpetra::Vector<double,int,int> Vector;
    typedef Tpetra::CrsMatrix<double,int,int> Matrix;
    typedef Tpetra::MultiVector<double,int,int> MV;
    typedef Tpetra::Operator<double,int,int> OP;

    // MCLS SOLVE
    if ( "MCLS" == plist->get<std::string>("Solver Package") )
    {
        Teuchos::RCP<MCLS::LinearProblem<Vector,Matrix> > linear_problem =
            Teuchos::rcp( new MCLS::LinearProblem<Vector,Matrix>(
                              diffusion_problem->getProblem()->getOperator(),
                              diffusion_problem->getProblem()->getLHS(),
                              diffusion_problem->getProblem()->getRHS() ) );

        std::string solver_type = plist->get<std::string>("Solver Type");

        MCLS::SolverFactory<Vector,Matrix> factory;
        Teuchos::RCP<MCLS::SolverManager<Vector,Matrix> > solver_manager =
            factory.create( solver_type, comm, plist );
        solver_manager->setProblem( linear_problem );
        Teuchos::Time timer("");
        timer.start(true);
        solver_manager->solve();
        timer.stop();
        if ( comm->getRank() == 0 )
        {
            std::cout << "MCLS Solve: Complete in " << timer.totalElapsedTime()
                      << " seconds." << std::endl;
        }
    }

    // Belos Solve
    else if ( "Belos" == plist->get<std::string>("Solver Package") )
    {
        Teuchos::RCP<Teuchos::ParameterList> belosList = Teuchos::parameterList();
        belosList->set( "Maximum Iterations", plist->get<int>("Maximum Iterations") );
        belosList->set( "Convergence Tolerance", plist->get<double>("Convergence Tolerance") );
        belosList->set( "Maximum Restarts", 10 );
        int verbosity = Belos::Errors + Belos::Warnings +
                        Belos::TimingDetails + Belos::StatusTestDetails;
        belosList->set( "Verbosity", verbosity );

        Teuchos::RCP<Belos::LinearProblem<double,MV,OP> > linear_problem
            = Teuchos::rcp( new Belos::LinearProblem<double,MV,OP>(
                                diffusion_problem->getProblem()->getOperator(),
                                diffusion_problem->getProblem()->getLHS(),
                                diffusion_problem->getProblem()->getRHS() ) );
        linear_problem->setProblem();

        Teuchos::RCP<Belos::SolverManager<double,MV,OP> > solver_manager;

        if ( "GMRES" == plist->get<std::string>("Solver Type") )
        {
            solver_manager = Teuchos::rcp(
                new Belos::PseudoBlockGmresSolMgr<double,MV,OP>(
                    linear_problem, belosList) );
        }
        else if ( "CG" == plist->get<std::string>("Solver Type") )
        {
            solver_manager = Teuchos::rcp(
                new Belos::PseudoBlockCGSolMgr<double,MV,OP>(
                    linear_problem, belosList) );
        }

        Teuchos::Time timer("");
        timer.start(true);
        solver_manager->solve();
        timer.stop();
        if ( comm->getRank() == 0 )
        {
            std::cout << "Belos Solve: Complete in " << timer.totalElapsedTime()
                      << " seconds." << std::endl;
            int numIters = solver_manager->getNumIters();
            std::cout << "Number of iterations performed for this solve: "
                      << numIters << std::endl;
        }
    }

    // Write the solution to VTK.
    Chimera::VTKOutput vtk_output( comm, partitioner, plist );
    vtk_output.addField( Chimera::VTKOutput::VERTEX_FIELD,
                         diffusion_problem->getProblem()->getLHS(),
                         "NEUTRON_FLUX" );
    vtk_output.write();

    return 0;
}

//---------------------------------------------------------------------------//
// end neutron_diffusion.cpp
//---------------------------------------------------------------------------//

<|endoftext|>