<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008      Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
// Copyright 2013      Mohammed Nafees <nafees.technocool@gmail.com>
//

#include "NavigationFloatItem.h"

#include <QtCore/qmath.h>
#include <QtCore/QRect>
#include <QtGui/QPixmap>
#include <QtGui/QToolButton>
#include <QtGui/QSlider>
#include <QtGui/QWidget>
#include <QtGui/QPainter>

#include "ui_navigation.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "WidgetGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"

using namespace Marble;
/* TRANSLATOR Marble::NavigationFloatItem */

NavigationFloatItem::NavigationFloatItem()
    : AbstractFloatItem( 0 )
{
}

NavigationFloatItem::NavigationFloatItem( const MarbleModel *marbleModel )
    : AbstractFloatItem( marbleModel, QPointF( -10, -30 ) ),
      m_marbleWidget( 0 ),
      m_widgetItem( 0 ),
      m_navigationWidget( 0 ),
      m_oldViewportRadius( 0 )
{
    // Plugin is enabled by default
    setEnabled( true );
    setVisible( false );

    setCacheMode( NoCache );
    setBackground( QBrush( QColor( Qt::transparent ) ) );
    setFrame( NoFrame );
}

NavigationFloatItem::~NavigationFloatItem()
{
    delete m_navigationWidget;
}

QStringList NavigationFloatItem::backendTypes() const
{
    return QStringList("navigation");
}

QString NavigationFloatItem::name() const
{
    return tr("Navigation");
}

QString NavigationFloatItem::guiString() const
{
    return tr("&Navigation");
}

QString NavigationFloatItem::nameId() const
{
    return QString("navigation");
}

QString NavigationFloatItem::version() const
{
    return "1.0";
}

QString NavigationFloatItem::description() const
{
    return tr("A mouse control to zoom and move the map");
}

QString NavigationFloatItem::copyrightYears() const
{
    return "2008, 2010, 2013";
}

QList<PluginAuthor> NavigationFloatItem::pluginAuthors() const
{
    return QList<PluginAuthor>()
            << PluginAuthor( QString::fromUtf8( "Dennis Nienhüser" ), "earthwings@gentoo.org" )
            << PluginAuthor( "Bastian Holst", "bastianholst@gmx.de" )
            << PluginAuthor( "Mohammed Nafees", "nafees.technocool@gmail.com" );
}

QIcon NavigationFloatItem::icon() const
{
    return QIcon(":/icons/navigation.png");
}

void NavigationFloatItem::initialize()
{
    QWidget *navigationParent = new QWidget( 0 );
    navigationParent->setAttribute( Qt::WA_NoSystemBackground, true );

    m_navigationWidget = new Ui::Navigation;
    m_navigationWidget->setupUi( navigationParent );

    m_widgetItem = new WidgetGraphicsItem( this );
    m_widgetItem->setWidget( navigationParent );

    MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
    layout->addItem( m_widgetItem, 0, 0 );

    setLayout( layout );
}

bool NavigationFloatItem::isInitialized() const
{
    return m_widgetItem;
}

void NavigationFloatItem::changeViewport( ViewportParams *viewport )
{
    if ( viewport->radius() != m_oldViewportRadius ) {
        const qreal zoomValue = (200.0 * qLn( viewport->radius() ) ); // copied from MarbleWidgetPrivate::zoom()
        setZoomSliderValue( zoomValue );

        m_oldViewportRadius = viewport->radius();
        // The slider depends on the map state (zoom factor)
        update();
    }
}

bool NavigationFloatItem::eventFilter( QObject *object, QEvent *e )
{
    if ( !enabled() || !visible() ) {
        return false;
    }

    MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);
    if ( !widget ) {
        return AbstractFloatItem::eventFilter( object, e );
    }

    if ( m_marbleWidget != widget ) {
        // Delayed initialization
        m_marbleWidget = widget;

        m_maxZoom = m_marbleWidget->maximumZoom();
        m_minZoom = m_marbleWidget->minimumZoom();

        m_navigationWidget->arrowDisc->setMarbleWidget( m_marbleWidget );
        connect( m_navigationWidget->arrowDisc, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );

        connect( m_navigationWidget->homeButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->homeButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(goHome()) );

        connect( m_navigationWidget->zoomInButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->zoomInButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(zoomIn()) );

        connect( m_navigationWidget->zoomOutButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->zoomOutButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(zoomOut()) );

        connect( m_marbleWidget, SIGNAL(zoomChanged(int)), SLOT(updateButtons(int)) );
        updateButtons( m_marbleWidget->zoom() );
        connect( m_marbleWidget, SIGNAL(themeChanged(QString)), this, SLOT(selectTheme(QString)) );

     }

    return AbstractFloatItem::eventFilter(object, e);
}

void NavigationFloatItem::setZoomSliderValue( int level )
{
}

void NavigationFloatItem::setMarbleZoomValue( int level )
{
    // There exists a circular signal/slot connection between MarbleWidget and this widget's
    // zoom slider. MarbleWidget prevents recursion, but it still loops one time unless
    // disconnected here.
    // The circular signal/slot connection results into the Marble Globe flickering, when the
    // zoom slider is used.

    if( !m_marbleWidget ) {
        return;
    }

    disconnect( m_marbleWidget, SIGNAL(zoomChanged(int)),
                this, SLOT(setZoomSliderValue(int)) );
    m_marbleWidget->zoomView( level );
    connect( m_marbleWidget, SIGNAL(zoomChanged(int)),
                this, SLOT(setZoomSliderValue(int)) );
}

void NavigationFloatItem::selectTheme( QString )
{
    if ( m_marbleWidget ) {
        m_maxZoom = m_marbleWidget->maximumZoom();
        m_minZoom = m_marbleWidget->minimumZoom();
        updateButtons( m_marbleWidget->zoom() );
    }
}

void NavigationFloatItem::adjustForAnimation()
{
    if ( !m_marbleWidget ) {
        return;
    }

    m_marbleWidget->setViewContext( Animation );
}

void NavigationFloatItem::adjustForStill()
{
    if ( !m_marbleWidget ) {
        return;
    }

    m_marbleWidget->setViewContext( Still );
}

void NavigationFloatItem::updateButtons( int zoomValue )
{
    bool const zoomInEnabled = m_navigationWidget->zoomInButton->isEnabled();
    bool const zoomOutEnabled = m_navigationWidget->zoomOutButton->isEnabled();
    m_navigationWidget->zoomInButton->setEnabled( zoomValue < m_maxZoom );
    m_navigationWidget->zoomOutButton->setEnabled( zoomValue > m_minZoom );
    if ( zoomInEnabled != m_navigationWidget->zoomInButton->isEnabled() ||
         zoomOutEnabled != m_navigationWidget->zoomOutButton->isEnabled() ) {
        update();
    }
}

Q_EXPORT_PLUGIN2( NavigationFloatItem, Marble::NavigationFloatItem )

#include "NavigationFloatItem.moc"
<commit_msg>Navigation float item is visible by default now.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008      Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2010      Bastian Holst <bastianholst@gmx.de>
// Copyright 2013      Mohammed Nafees <nafees.technocool@gmail.com>
//

#include "NavigationFloatItem.h"

#include <QtCore/qmath.h>
#include <QtCore/QRect>
#include <QtGui/QPixmap>
#include <QtGui/QToolButton>
#include <QtGui/QSlider>
#include <QtGui/QWidget>
#include <QtGui/QPainter>

#include "ui_navigation.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "WidgetGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"

using namespace Marble;
/* TRANSLATOR Marble::NavigationFloatItem */

NavigationFloatItem::NavigationFloatItem()
    : AbstractFloatItem( 0 )
{
}

NavigationFloatItem::NavigationFloatItem( const MarbleModel *marbleModel )
    : AbstractFloatItem( marbleModel, QPointF( -10, -30 ) ),
      m_marbleWidget( 0 ),
      m_widgetItem( 0 ),
      m_navigationWidget( 0 ),
      m_oldViewportRadius( 0 )
{
    // Plugin is visible by default
    setEnabled( true );
    setVisible( true );

    setCacheMode( NoCache );
    setBackground( QBrush( QColor( Qt::transparent ) ) );
    setFrame( NoFrame );
}

NavigationFloatItem::~NavigationFloatItem()
{
    delete m_navigationWidget;
}

QStringList NavigationFloatItem::backendTypes() const
{
    return QStringList("navigation");
}

QString NavigationFloatItem::name() const
{
    return tr("Navigation");
}

QString NavigationFloatItem::guiString() const
{
    return tr("&Navigation");
}

QString NavigationFloatItem::nameId() const
{
    return QString("navigation");
}

QString NavigationFloatItem::version() const
{
    return "1.0";
}

QString NavigationFloatItem::description() const
{
    return tr("A mouse control to zoom and move the map");
}

QString NavigationFloatItem::copyrightYears() const
{
    return "2008, 2010, 2013";
}

QList<PluginAuthor> NavigationFloatItem::pluginAuthors() const
{
    return QList<PluginAuthor>()
            << PluginAuthor( QString::fromUtf8( "Dennis Nienhüser" ), "earthwings@gentoo.org" )
            << PluginAuthor( "Bastian Holst", "bastianholst@gmx.de" )
            << PluginAuthor( "Mohammed Nafees", "nafees.technocool@gmail.com" );
}

QIcon NavigationFloatItem::icon() const
{
    return QIcon(":/icons/navigation.png");
}

void NavigationFloatItem::initialize()
{
    QWidget *navigationParent = new QWidget( 0 );
    navigationParent->setAttribute( Qt::WA_NoSystemBackground, true );

    m_navigationWidget = new Ui::Navigation;
    m_navigationWidget->setupUi( navigationParent );

    m_widgetItem = new WidgetGraphicsItem( this );
    m_widgetItem->setWidget( navigationParent );

    MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
    layout->addItem( m_widgetItem, 0, 0 );

    setLayout( layout );
}

bool NavigationFloatItem::isInitialized() const
{
    return m_widgetItem;
}

void NavigationFloatItem::changeViewport( ViewportParams *viewport )
{
    if ( viewport->radius() != m_oldViewportRadius ) {
        const qreal zoomValue = (200.0 * qLn( viewport->radius() ) ); // copied from MarbleWidgetPrivate::zoom()
        setZoomSliderValue( zoomValue );

        m_oldViewportRadius = viewport->radius();
        // The slider depends on the map state (zoom factor)
        update();
    }
}

bool NavigationFloatItem::eventFilter( QObject *object, QEvent *e )
{
    if ( !enabled() || !visible() ) {
        return false;
    }

    MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);
    if ( !widget ) {
        return AbstractFloatItem::eventFilter( object, e );
    }

    if ( m_marbleWidget != widget ) {
        // Delayed initialization
        m_marbleWidget = widget;

        m_maxZoom = m_marbleWidget->maximumZoom();
        m_minZoom = m_marbleWidget->minimumZoom();

        m_navigationWidget->arrowDisc->setMarbleWidget( m_marbleWidget );
        connect( m_navigationWidget->arrowDisc, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );

        connect( m_navigationWidget->homeButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->homeButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(goHome()) );

        connect( m_navigationWidget->zoomInButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->zoomInButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(zoomIn()) );

        connect( m_navigationWidget->zoomOutButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );
        connect( m_navigationWidget->zoomOutButton, SIGNAL(clicked()),
                 m_marbleWidget, SLOT(zoomOut()) );

        connect( m_marbleWidget, SIGNAL(zoomChanged(int)), SLOT(updateButtons(int)) );
        updateButtons( m_marbleWidget->zoom() );
        connect( m_marbleWidget, SIGNAL(themeChanged(QString)), this, SLOT(selectTheme(QString)) );

     }

    return AbstractFloatItem::eventFilter(object, e);
}

void NavigationFloatItem::setZoomSliderValue( int level )
{
}

void NavigationFloatItem::setMarbleZoomValue( int level )
{
    // There exists a circular signal/slot connection between MarbleWidget and this widget's
    // zoom slider. MarbleWidget prevents recursion, but it still loops one time unless
    // disconnected here.
    // The circular signal/slot connection results into the Marble Globe flickering, when the
    // zoom slider is used.

    if( !m_marbleWidget ) {
        return;
    }

    disconnect( m_marbleWidget, SIGNAL(zoomChanged(int)),
                this, SLOT(setZoomSliderValue(int)) );
    m_marbleWidget->zoomView( level );
    connect( m_marbleWidget, SIGNAL(zoomChanged(int)),
                this, SLOT(setZoomSliderValue(int)) );
}

void NavigationFloatItem::selectTheme( QString )
{
    if ( m_marbleWidget ) {
        m_maxZoom = m_marbleWidget->maximumZoom();
        m_minZoom = m_marbleWidget->minimumZoom();
        updateButtons( m_marbleWidget->zoom() );
    }
}

void NavigationFloatItem::adjustForAnimation()
{
    if ( !m_marbleWidget ) {
        return;
    }

    m_marbleWidget->setViewContext( Animation );
}

void NavigationFloatItem::adjustForStill()
{
    if ( !m_marbleWidget ) {
        return;
    }

    m_marbleWidget->setViewContext( Still );
}

void NavigationFloatItem::updateButtons( int zoomValue )
{
    bool const zoomInEnabled = m_navigationWidget->zoomInButton->isEnabled();
    bool const zoomOutEnabled = m_navigationWidget->zoomOutButton->isEnabled();
    m_navigationWidget->zoomInButton->setEnabled( zoomValue < m_maxZoom );
    m_navigationWidget->zoomOutButton->setEnabled( zoomValue > m_minZoom );
    if ( zoomInEnabled != m_navigationWidget->zoomInButton->isEnabled() ||
         zoomOutEnabled != m_navigationWidget->zoomOutButton->isEnabled() ) {
        update();
    }
}

Q_EXPORT_PLUGIN2( NavigationFloatItem, Marble::NavigationFloatItem )

#include "NavigationFloatItem.moc"
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
#include "sparse.h"
#include <Eigen/SparseQR>

template<typename MatrixType,typename DenseMat>
int generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)
{
  eigen_assert(maxRows >= maxCols);
  typedef typename MatrixType::Scalar Scalar;
  int rows = internal::random<int>(1,maxRows);
  int cols = internal::random<int>(1,rows);
  double density = (std::max)(8./(rows*cols), 0.01);

  A.resize(rows,rows);
  dA.resize(rows,rows);
  initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);
  A.makeCompressed();
  int nop = internal::random<int>(0, internal::random<double>(0,1) > 0.5 ? cols/2 : 0);
  for(int k=0; k<nop; ++k)
  {
    int j0 = internal::random<int>(0,cols-1);
    int j1 = internal::random<int>(0,cols-1);
    Scalar s = internal::random<Scalar>();
    A.col(j0)  = s * A.col(j1);
    dA.col(j0) = s * dA.col(j1);
  }
  return rows;
}

template<typename Scalar> void test_sparseqr_scalar()
{
  typedef SparseMatrix<Scalar,ColMajor> MatrixType;
  typedef Matrix<Scalar,Dynamic,Dynamic> DenseMat;
  typedef Matrix<Scalar,Dynamic,1> DenseVector;
  MatrixType A;
  DenseMat dA;
  DenseVector refX,x,b;
  SparseQR<MatrixType, AMDOrdering<int> > solver;
  generate_sparse_rectangular_problem(A,dA);

  int n = A.cols();
  b = DenseVector::Random(n);
  solver.compute(A);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  x = solver.solve(b);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  //Compare with a dense QR solver
  ColPivHouseholderQR<DenseMat> dqr(dA);
  refX = dqr.solve(b);

  VERIFY_IS_EQUAL(dqr.rank(), solver.rank());

  if(solver.rank()<A.cols())
    VERIFY((dA * refX - b).norm() * 2 > (A * x - b).norm() );
  else
    VERIFY_IS_APPROX(x, refX);
}
void test_sparseqr()
{
  for(int i=0; i<g_repeat; ++i)
  {
    CALL_SUBTEST_1(test_sparseqr_scalar<double>());
    CALL_SUBTEST_2(test_sparseqr_scalar<std::complex<double> >());
  }
}<commit_msg>Fix no newline warning.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
#include "sparse.h"
#include <Eigen/SparseQR>

template<typename MatrixType,typename DenseMat>
int generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)
{
  eigen_assert(maxRows >= maxCols);
  typedef typename MatrixType::Scalar Scalar;
  int rows = internal::random<int>(1,maxRows);
  int cols = internal::random<int>(1,rows);
  double density = (std::max)(8./(rows*cols), 0.01);

  A.resize(rows,rows);
  dA.resize(rows,rows);
  initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);
  A.makeCompressed();
  int nop = internal::random<int>(0, internal::random<double>(0,1) > 0.5 ? cols/2 : 0);
  for(int k=0; k<nop; ++k)
  {
    int j0 = internal::random<int>(0,cols-1);
    int j1 = internal::random<int>(0,cols-1);
    Scalar s = internal::random<Scalar>();
    A.col(j0)  = s * A.col(j1);
    dA.col(j0) = s * dA.col(j1);
  }
  return rows;
}

template<typename Scalar> void test_sparseqr_scalar()
{
  typedef SparseMatrix<Scalar,ColMajor> MatrixType;
  typedef Matrix<Scalar,Dynamic,Dynamic> DenseMat;
  typedef Matrix<Scalar,Dynamic,1> DenseVector;
  MatrixType A;
  DenseMat dA;
  DenseVector refX,x,b;
  SparseQR<MatrixType, AMDOrdering<int> > solver;
  generate_sparse_rectangular_problem(A,dA);

  int n = A.cols();
  b = DenseVector::Random(n);
  solver.compute(A);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  x = solver.solve(b);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  //Compare with a dense QR solver
  ColPivHouseholderQR<DenseMat> dqr(dA);
  refX = dqr.solve(b);

  VERIFY_IS_EQUAL(dqr.rank(), solver.rank());

  if(solver.rank()<A.cols())
    VERIFY((dA * refX - b).norm() * 2 > (A * x - b).norm() );
  else
    VERIFY_IS_APPROX(x, refX);
}
void test_sparseqr()
{
  for(int i=0; i<g_repeat; ++i)
  {
    CALL_SUBTEST_1(test_sparseqr_scalar<double>());
    CALL_SUBTEST_2(test_sparseqr_scalar<std::complex<double> >());
  }
}
<|endoftext|>


<commit_before>
#include <algorithm>
#include <cstddef>
#include <cstdint>

#include "catch.hpp"

#include "variant.hpp"
#include "variant_io.hpp"

struct some_struct {
    int a;
    bool b;
    std::string c;
};

using variant_internal_index_type = size_t;

TEST_CASE( "size of variants" ) {
    constexpr const auto min_overhead = sizeof(variant_internal_index_type);

    using std::max_align_t; // workaround for bug in GCC <= 4.8 where max_align_t is not in std
    constexpr const auto max_overhead = alignof(max_align_t) + min_overhead;

    using v1 = mapbox::util::variant<int>;
    using v2 = mapbox::util::variant<int, bool, int64_t>;
    using v3 = mapbox::util::variant<int, std::string>;
    using v4 = mapbox::util::variant<std::string, std::string>;
    using v5 = mapbox::util::variant<some_struct>;

    constexpr const auto si   = sizeof(int);
    constexpr const auto sb   = sizeof(bool);
    constexpr const auto si64 = sizeof(int64_t);
    constexpr const auto sd   = sizeof(double);
    constexpr const auto sstr = sizeof(std::string);
    constexpr const auto spi  = sizeof(std::pair<int, int>);
    constexpr const auto ss   = sizeof(some_struct);

    REQUIRE(sizeof(v1) <= max_overhead + si                      );
    REQUIRE(sizeof(v2) <= max_overhead + std::max({si, sb, si64}));
    REQUIRE(sizeof(v3) <= max_overhead + std::max({si, sstr})    );
    REQUIRE(sizeof(v4) <= max_overhead + sstr                    );
    REQUIRE(sizeof(v5) <= max_overhead + ss                      );

    REQUIRE(sizeof(v1) >= min_overhead + si                      );
    REQUIRE(sizeof(v2) >= min_overhead + std::max({si, sb, si64}));
    REQUIRE(sizeof(v3) >= min_overhead + std::max({si, sstr})    );
    REQUIRE(sizeof(v4) >= min_overhead + sstr                    );
    REQUIRE(sizeof(v5) >= min_overhead + ss                      );
}

<commit_msg>Fix for the workaround in 86a78c2adfde1de718231ea8f95af4745e838779.<commit_after>
#include <algorithm>
#include <cstddef>
#include <cstdint>

#include "catch.hpp"

#include "variant.hpp"
#include "variant_io.hpp"

struct some_struct {
    int a;
    bool b;
    std::string c;
};

using variant_internal_index_type = size_t;

TEST_CASE( "size of variants" ) {
    constexpr const auto min_overhead = sizeof(variant_internal_index_type);

    using namespace std; // workaround for bug in GCC <= 4.8 where max_align_t is not in std
    constexpr const auto max_overhead = alignof(max_align_t) + min_overhead;

    using v1 = mapbox::util::variant<int>;
    using v2 = mapbox::util::variant<int, bool, int64_t>;
    using v3 = mapbox::util::variant<int, std::string>;
    using v4 = mapbox::util::variant<std::string, std::string>;
    using v5 = mapbox::util::variant<some_struct>;

    constexpr const auto si   = sizeof(int);
    constexpr const auto sb   = sizeof(bool);
    constexpr const auto si64 = sizeof(int64_t);
    constexpr const auto sd   = sizeof(double);
    constexpr const auto sstr = sizeof(std::string);
    constexpr const auto spi  = sizeof(std::pair<int, int>);
    constexpr const auto ss   = sizeof(some_struct);

    REQUIRE(sizeof(v1) <= max_overhead + si                      );
    REQUIRE(sizeof(v2) <= max_overhead + std::max({si, sb, si64}));
    REQUIRE(sizeof(v3) <= max_overhead + std::max({si, sstr})    );
    REQUIRE(sizeof(v4) <= max_overhead + sstr                    );
    REQUIRE(sizeof(v5) <= max_overhead + ss                      );

    REQUIRE(sizeof(v1) >= min_overhead + si                      );
    REQUIRE(sizeof(v2) >= min_overhead + std::max({si, sb, si64}));
    REQUIRE(sizeof(v3) >= min_overhead + std::max({si, sstr})    );
    REQUIRE(sizeof(v4) >= min_overhead + sstr                    );
    REQUIRE(sizeof(v5) >= min_overhead + ss                      );
}

<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <fstream>
#include <clocale>
#include <locale>

#include "interp.hxx"
#include "common.hxx"

using namespace std;
using namespace tglng;

int main(int argc, const char*const* argv) {
  wstring out;
  Interpreter interp;

  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");
  locale::global(locale(""));

  //Try to read from standard configuration file.
  //TODO: Change this to something more sensible
  {
    wifstream in("rc.default");
    if (!interp.exec(out, in, Interpreter::ParseModeCommand)) {
      wcerr << L"Error reading user library." << endl;
      return EXIT_EXEC_ERROR_IN_USER_LIBRARY;
    }
  }

  if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) {
    wcout << out;
    Interpreter::freeGlobalBindings();
    return 0;
  } else {
    wcerr << L"Failed." << endl;
    return EXIT_EXEC_ERROR_IN_INPUT;
  }
}
<commit_msg>Sort-of work around GNU C++ locale being broken on non-GNU libc.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <fstream>
#include <clocale>
#include <locale>
#include <exception>
#include <stdexcept>

#include "interp.hxx"
#include "common.hxx"

using namespace std;
using namespace tglng;

int main(int argc, const char*const* argv) {
  wstring out;
  Interpreter interp;

  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");
  try {
    locale::global(locale(""));
  } catch (runtime_error& re) {
    /*
      When GNU libstdc++ is used on top of a non-GNU libc, no locales other
      than "C" are supported. On some versions of libstdc++, trying to set the
      default locale throws a runtime_error().

      See:
      http://gcc.gnu.org/ml/libstdc++/2003-02/msg00345.html

      Unfortunately, no --use-my-systems-libc-dammit option seems to exist yet,
      especially not one usable at compilation time.

      If we catch the runtime_error, just ignore it and carry on --- there's
      nothing else we can do.
    */
  }

  //Try to read from standard configuration file.
  //TODO: Change this to something more sensible
  {
    wifstream in("rc.default");
    if (!interp.exec(out, in, Interpreter::ParseModeCommand)) {
      wcerr << L"Error reading user library." << endl;
      return EXIT_EXEC_ERROR_IN_USER_LIBRARY;
    }
  }

  if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) {
    wcout << out;
    Interpreter::freeGlobalBindings();
    return 0;
  } else {
    wcerr << L"Failed." << endl;
    return EXIT_EXEC_ERROR_IN_INPUT;
  }
}
<|endoftext|>


<commit_before>#include <gst/gst.h>
#include "MediaPipelineImpl.hpp"
#include "MediaObjectImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#define GST_CAT_DEFAULT kurento_media_object_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaObjectImpl"

namespace kurento
{

MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)
{
  id = createId();
  this->config = config;
}

MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent)
{
  this->parent = parent;
  id = createId();
  this->config = config;
}

std::shared_ptr<MediaPipeline>
MediaObjectImpl::getMediaPipeline ()
{
  if (parent) {
    return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();
  } else {
    return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );
  }
}

std::string
MediaObjectImpl::createId()
{
  std::stringstream ss;
  boost::uuids::uuid uuid = boost::uuids::random_generator() ();

  ss << uuid;

  if (parent) {
    std::shared_ptr<MediaPipelineImpl> pipeline;

    pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );
    return pipeline->getId() + "/" +
           ss.str();
  } else {
    return ss.str();
  }
}

MediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;

MediaObjectImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<commit_msg>MediaObjectImpl: Improve UUID generation<commit_after>#include <gst/gst.h>
#include "MediaPipelineImpl.hpp"
#include "MediaObjectImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <chrono>

#define GST_CAT_DEFAULT kurento_media_object_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaObjectImpl"

namespace kurento
{

class RandomGeneratorBase
{
protected:
  RandomGeneratorBase () {
    std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
    std::chrono::duration<time_t> time = std::chrono::duration_cast<std::chrono::duration<time_t>> (now.time_since_epoch () );

    ran.seed (time.count() );
  }

  boost::mt19937 ran;
};

class RandomGenerator : RandomGeneratorBase
{
  boost::mt19937 ran;
  boost::uuids::basic_random_generator<boost::mt19937> gen;

public:
  RandomGenerator () : RandomGeneratorBase(), gen (&ran) {
  }

  std::string getUUID () {
    std::stringstream ss;
    boost::uuids::uuid uuid = gen ();

    ss << uuid;
    return ss.str();
  }
};

static RandomGenerator gen;

MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)
{
  id = createId();
  this->config = config;
}

MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent)
{
  this->parent = parent;
  id = createId();
  this->config = config;
}

std::shared_ptr<MediaPipeline>
MediaObjectImpl::getMediaPipeline ()
{
  if (parent) {
    return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();
  } else {
    return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );
  }
}

std::string
MediaObjectImpl::createId()
{
  std::string uuid = gen.getUUID ();

  if (parent) {
    std::shared_ptr<MediaPipelineImpl> pipeline;

    pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );
    return pipeline->getId() + "/" +
           uuid;
  } else {
    return uuid;
  }
}

MediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;

MediaObjectImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<|endoftext|>


<commit_before>#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
<commit_msg>qt: qml: fix warning message<commit_after>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtWebView>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QtWebView::initialize();

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

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


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

Module: FGMatrix.cpp
Author: Originally by Tony Peden [formatted here (and broken??) by JSB]
Date started: 1998
Purpose: FGMatrix class
Called by: Various

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
??/??/??   TP   Created
03/16/2000 JSB  Added exception throwing

********************************************************************************
INCLUDES
*******************************************************************************/

#include "FGMatrix.h"

/*******************************************************************************
************************************ CODE **************************************
*******************************************************************************/

double** FGalloc(int rows, int cols)
{
  double **A;

  A = new double *[rows+1];
  if (!A)  return NULL;

  for (int i=0; i <= rows; i++){
    A[i] = new double [cols+1];
    if (!A[i]) return NULL;
  }
  return A;
}

/******************************************************************************/

void dealloc(double **A, int rows)
{
  for(int i=0;i<= rows;i++) delete[] A[i];
  delete[] A;
}

/******************************************************************************/

FGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c)
{
  data = FGalloc(rows,cols);
  InitMatrix();
  rowCtr = colCtr = 1;
}

/******************************************************************************/

FGMatrix::FGMatrix(const FGMatrix& M)
{
  data  = NULL;
  rowCtr = colCtr = 1;
  *this = M;
}

/******************************************************************************/

FGMatrix::~FGMatrix(void)
{
  dealloc(data,rows);
  rowCtr = colCtr = 1;
  rows = cols = 0;
}

/******************************************************************************/

ostream& operator<<(ostream& os, const FGMatrix& M)
{
  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      if (i == M.Rows() && j == M.Cols())
        os << M.data[i][j];
      else
        os << M.data[i][j] << ", ";
    }
  }
  return os;
}

/******************************************************************************/

FGMatrix& FGMatrix::operator<<(const float ff)
{
  data[rowCtr][colCtr] = ff;
  if (++colCtr > Cols()) {
    colCtr = 1;
    if (++rowCtr > Rows())
      rowCtr = 1;
  }
  return *this;
}

/******************************************************************************/

istream& operator>>(istream& is, FGMatrix& M)
{
  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      is >> M.data[i][j];
    }
  }
  return is;
}

/******************************************************************************/

FGMatrix& FGMatrix::operator=(const FGMatrix& M)
{
  if (&M != this) {
    if (data != NULL) dealloc(data,rows);

    width  = M.width;
    prec   = M.prec;
    delim  = M.delim;
    origin = M.origin;
    rows   = M.rows;
    cols   = M.cols;

    data = FGalloc(rows,cols);
    for (unsigned int i=0; i<=rows; i++) {
      for (unsigned int j=0; j<=cols; j++) {
        data[i][j] = M.data[i][j];
      }
    }
  }
  return *this;
}

/******************************************************************************/

unsigned int FGMatrix::Rows(void) const
{
  return rows;
}

/******************************************************************************/

unsigned int FGMatrix::Cols(void) const
{
  return cols;
}

/******************************************************************************/

void FGMatrix::SetOParams(char delim,int width,int prec,int origin)
{
  FGMatrix::delim  = delim;
  FGMatrix::width  = width;
  FGMatrix::prec   = prec;
  FGMatrix::origin = origin;
}

/******************************************************************************/

void FGMatrix::InitMatrix(double value)
{
  if (data) {
    for (unsigned int i=0;i<=rows;i++) {
      for (unsigned int j=0;j<=cols;j++) {
        operator()(i,j) = value;
      }
    }
  }
}

/******************************************************************************/

void FGMatrix::InitMatrix(void)
{
  this->InitMatrix(0);
}

// *****************************************************************************
// binary operators ************************************************************
// *****************************************************************************

FGMatrix FGMatrix::operator-(const FGMatrix& M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator -";
    throw mE;
  }

  FGMatrix Diff(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      Diff(i,j) = data[i][j] - M(i,j);
    }
  }
  return Diff;
}

/******************************************************************************/

void FGMatrix::operator-=(const FGMatrix &M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator -=";
    throw mE;
  }

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j] -= M(i,j);
    }
  }
}

/******************************************************************************/

FGMatrix FGMatrix::operator+(const FGMatrix& M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator +";
    throw mE;
  }

  FGMatrix Sum(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      Sum(i,j) = data[i][j] + M(i,j);
    }
  }
  return Sum;
}

/******************************************************************************/

void FGMatrix::operator+=(const FGMatrix &M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator +=";
    throw mE;
  }

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j]+=M(i,j);
    }
  }
}

/******************************************************************************/

FGMatrix operator*(double scalar, FGMatrix &M)
{
  FGMatrix Product(M.Rows(), M.Cols());

  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      Product(i,j) = scalar*M(i,j);
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::operator*=(const double scalar)
{
  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j] *= scalar;
    }
  }
}

/******************************************************************************/

FGMatrix FGMatrix::operator*(const FGMatrix& M)
{
  if (Cols() != M.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator *";
    throw mE;
  }

  FGMatrix Product(Rows(), M.Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++)  {
      Product(i,j) = 0;
      for (unsigned int k=1; k<=Cols(); k++) {
         Product(i,j) += data[i][k] * M(k,j);
      }
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::operator*=(const FGMatrix& M)
{
  if (Cols() != M.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator *=";
    throw mE;
  }

  double **prod;

  prod = FGalloc(Rows(), M.Cols());
  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      prod[i][j] = 0;
      for (unsigned int k=1; k<=Cols(); k++) {
        prod[i][j] += data[i][k] * M(k,j);
      }
    }
  }
  dealloc(data, Rows());
  data = prod;
  cols = M.cols;
}

/******************************************************************************/

FGMatrix FGMatrix::operator/(const double scalar)
{
  FGMatrix Quot(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++)  {
       Quot(i,j) = data[i][j]/scalar;
    }
  }
  return Quot;
}

/******************************************************************************/

void FGMatrix::operator/=(const double scalar)
{
  for (unsigned int i=1; i<=Rows(); i++)  {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j]/=scalar;
    }
  }
}

/******************************************************************************/

void FGMatrix::T(void)
{
  if (rows==cols)
    TransposeSquare();
  else
    TransposeNonSquare();
}

/******************************************************************************/

FGColumnVector FGMatrix::operator*(const FGColumnVector& Col)
{
  FGColumnVector Product(Col.Rows());

  if (Cols() != Col.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  for (unsigned int i=1;i<=Rows();i++) {
    Product(i) = 0.00;
    for (unsigned int j=1;j<=Cols();j++) {
      Product(i) += Col(j)*data[i][j];
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::TransposeSquare(void)
{
  for (unsigned int i=1; i<=rows; i++) {
    for (unsigned int j=i+1; j<=cols; j++) {
      double tmp = data[i][j];
      data[i][j] = data[j][i];
      data[j][i] = tmp;
    }
  }
}

/******************************************************************************/

void FGMatrix::TransposeNonSquare(void)
{
  double **tran;

  tran = FGalloc(rows,cols);

  for (unsigned int i=1; i<=rows; i++) {
    for (unsigned int j=1; j<=cols; j++) {
      tran[j][i] = data[i][j];
    }
  }

  dealloc(data,rows);

  data       = tran;
  unsigned int m = rows;
  rows       = cols;
  cols       = m;
}

/******************************************************************************/

FGColumnVector::FGColumnVector(void):FGMatrix(3,1) { }
FGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { }
FGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { }
FGColumnVector::~FGColumnVector() { }

/******************************************************************************/

double& FGColumnVector::operator()(int m) const
{
  return FGMatrix::operator()(m,1);
}

/******************************************************************************/

FGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col)
{
  FGColumnVector Product(Col.Rows());

  if (Mat.Cols() != Col.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  for (unsigned int i=1;i<=Mat.Rows();i++) {
    Product(i) = 0.00;
    for (unsigned int j=1;j<=Mat.Cols();j++) {
      Product(i) += Col(j)*Mat(i,j);
    }
  }

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator+(const FGColumnVector& C)
{
  if (Rows() != C.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  FGColumnVector Sum(C.Rows());

  for (unsigned int i=1; i<=C.Rows(); i++) {
    Sum(i) = C(i) + data[i][1];
  }

  return Sum;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator*(const double scalar)
{
  FGColumnVector Product(Rows());

  for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1];

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator-(const FGColumnVector& V)
{
  if ((Rows() != V.Rows()) || (Cols() != V.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator -";
    throw mE;
  }

  FGColumnVector Diff(Rows());

  for (unsigned int i=1; i<=Rows(); i++) {
    Diff(i) = data[i][1] - V(i);
  }

  return Diff;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator/(const double scalar)
{
  FGColumnVector Quotient(Rows());

  for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] / scalar;

  return Quotient;
}

/******************************************************************************/

FGColumnVector operator*(const double scalar, const FGColumnVector& C)
{
  FGColumnVector Product(C.Rows());

  for (unsigned int i=1; i<=C.Rows(); i++) {
     Product(i) = scalar * C(i);
  }

  return Product;
}

/******************************************************************************/

float FGColumnVector::Magnitude(void)
{
  double num=0.0;

  if ((data[1][1] == 0.00) &&
      (data[2][1] == 0.00) &&
      (data[3][1] == 0.00))
  {
    return 0.00;
  } else {
    for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1];
    return sqrt(num);
  }
}

/******************************************************************************/

FGColumnVector FGColumnVector::Normalize(void)
{
  double Mag = Magnitude();

  for (unsigned int i=1; i<=Rows(); i++)
    for (unsigned int j=1; j<=Cols(); j++)
      data[i][j] = data[i][j]/Mag;

  return *this;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator*(const FGColumnVector& V)
{
  if (Rows() != 3 || V.Rows() != 3) {
    MatrixException mE;
    mE.Message = "Invalid row count in vector cross product function";
    throw mE;
  }

  FGColumnVector Product(3);

  Product(1) = data[2][1] * V(3) - data[3][1] * V(2);
  Product(2) = data[3][1] * V(1) - data[1][1] * V(3);
  Product(3) = data[1][1] * V(2) - data[2][1] * V(1);

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V)
{
  if (Rows() != 3 || V.Rows() != 3) {
    MatrixException mE;
    mE.Message = "Invalid row count in vector cross product function";
    throw mE;
  }

  FGColumnVector Product(3);

  Product(1) = data[1][1] * V(1);
  Product(2) = data[2][1] * V(2);
  Product(3) = data[3][1] * V(3);

  return Product;
}

/******************************************************************************/
<commit_msg>Added check for 0 magnitude in Normalize()<commit_after>/*******************************************************************************

Module: FGMatrix.cpp
Author: Originally by Tony Peden [formatted here (and broken??) by JSB]
Date started: 1998
Purpose: FGMatrix class
Called by: Various

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
??/??/??   TP   Created
03/16/2000 JSB  Added exception throwing

********************************************************************************
INCLUDES
*******************************************************************************/

#include "FGMatrix.h"

/*******************************************************************************
************************************ CODE **************************************
*******************************************************************************/

double** FGalloc(int rows, int cols)
{
  double **A;

  A = new double *[rows+1];
  if (!A)  return NULL;

  for (int i=0; i <= rows; i++){
    A[i] = new double [cols+1];
    if (!A[i]) return NULL;
  }
  return A;
}

/******************************************************************************/

void dealloc(double **A, int rows)
{
  for(int i=0;i<= rows;i++) delete[] A[i];
  delete[] A;
}

/******************************************************************************/

FGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c)
{
  data = FGalloc(rows,cols);
  InitMatrix();
  rowCtr = colCtr = 1;
}

/******************************************************************************/

FGMatrix::FGMatrix(const FGMatrix& M)
{
  data  = NULL;
  rowCtr = colCtr = 1;
  *this = M;
}

/******************************************************************************/

FGMatrix::~FGMatrix(void)
{
  dealloc(data,rows);
  rowCtr = colCtr = 1;
  rows = cols = 0;
}

/******************************************************************************/

ostream& operator<<(ostream& os, const FGMatrix& M)
{
  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      if (i == M.Rows() && j == M.Cols())
        os << M.data[i][j];
      else
        os << M.data[i][j] << ", ";
    }
  }
  return os;
}

/******************************************************************************/

FGMatrix& FGMatrix::operator<<(const float ff)
{
  data[rowCtr][colCtr] = ff;
  if (++colCtr > Cols()) {
    colCtr = 1;
    if (++rowCtr > Rows())
      rowCtr = 1;
  }
  return *this;
}

/******************************************************************************/

istream& operator>>(istream& is, FGMatrix& M)
{
  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      is >> M.data[i][j];
    }
  }
  return is;
}

/******************************************************************************/

FGMatrix& FGMatrix::operator=(const FGMatrix& M)
{
  if (&M != this) {
    if (data != NULL) dealloc(data,rows);

    width  = M.width;
    prec   = M.prec;
    delim  = M.delim;
    origin = M.origin;
    rows   = M.rows;
    cols   = M.cols;

    data = FGalloc(rows,cols);
    for (unsigned int i=0; i<=rows; i++) {
      for (unsigned int j=0; j<=cols; j++) {
        data[i][j] = M.data[i][j];
      }
    }
  }
  return *this;
}

/******************************************************************************/

unsigned int FGMatrix::Rows(void) const
{
  return rows;
}

/******************************************************************************/

unsigned int FGMatrix::Cols(void) const
{
  return cols;
}

/******************************************************************************/

void FGMatrix::SetOParams(char delim,int width,int prec,int origin)
{
  FGMatrix::delim  = delim;
  FGMatrix::width  = width;
  FGMatrix::prec   = prec;
  FGMatrix::origin = origin;
}

/******************************************************************************/

void FGMatrix::InitMatrix(double value)
{
  if (data) {
    for (unsigned int i=0;i<=rows;i++) {
      for (unsigned int j=0;j<=cols;j++) {
        operator()(i,j) = value;
      }
    }
  }
}

/******************************************************************************/

void FGMatrix::InitMatrix(void)
{
  this->InitMatrix(0);
}

// *****************************************************************************
// binary operators ************************************************************
// *****************************************************************************

FGMatrix FGMatrix::operator-(const FGMatrix& M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator -";
    throw mE;
  }

  FGMatrix Diff(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      Diff(i,j) = data[i][j] - M(i,j);
    }
  }
  return Diff;
}

/******************************************************************************/

void FGMatrix::operator-=(const FGMatrix &M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator -=";
    throw mE;
  }

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j] -= M(i,j);
    }
  }
}

/******************************************************************************/

FGMatrix FGMatrix::operator+(const FGMatrix& M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator +";
    throw mE;
  }

  FGMatrix Sum(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      Sum(i,j) = data[i][j] + M(i,j);
    }
  }
  return Sum;
}

/******************************************************************************/

void FGMatrix::operator+=(const FGMatrix &M)
{
  if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator +=";
    throw mE;
  }

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j]+=M(i,j);
    }
  }
}

/******************************************************************************/

FGMatrix operator*(double scalar, FGMatrix &M)
{
  FGMatrix Product(M.Rows(), M.Cols());

  for (unsigned int i=1; i<=M.Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      Product(i,j) = scalar*M(i,j);
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::operator*=(const double scalar)
{
  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j] *= scalar;
    }
  }
}

/******************************************************************************/

FGMatrix FGMatrix::operator*(const FGMatrix& M)
{
  if (Cols() != M.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator *";
    throw mE;
  }

  FGMatrix Product(Rows(), M.Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++)  {
      Product(i,j) = 0;
      for (unsigned int k=1; k<=Cols(); k++) {
         Product(i,j) += data[i][k] * M(k,j);
      }
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::operator*=(const FGMatrix& M)
{
  if (Cols() != M.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Matrix operator *=";
    throw mE;
  }

  double **prod;

  prod = FGalloc(Rows(), M.Cols());
  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=M.Cols(); j++) {
      prod[i][j] = 0;
      for (unsigned int k=1; k<=Cols(); k++) {
        prod[i][j] += data[i][k] * M(k,j);
      }
    }
  }
  dealloc(data, Rows());
  data = prod;
  cols = M.cols;
}

/******************************************************************************/

FGMatrix FGMatrix::operator/(const double scalar)
{
  FGMatrix Quot(Rows(), Cols());

  for (unsigned int i=1; i<=Rows(); i++) {
    for (unsigned int j=1; j<=Cols(); j++)  {
       Quot(i,j) = data[i][j]/scalar;
    }
  }
  return Quot;
}

/******************************************************************************/

void FGMatrix::operator/=(const double scalar)
{
  for (unsigned int i=1; i<=Rows(); i++)  {
    for (unsigned int j=1; j<=Cols(); j++) {
      data[i][j]/=scalar;
    }
  }
}

/******************************************************************************/

void FGMatrix::T(void)
{
  if (rows==cols)
    TransposeSquare();
  else
    TransposeNonSquare();
}

/******************************************************************************/

FGColumnVector FGMatrix::operator*(const FGColumnVector& Col)
{
  FGColumnVector Product(Col.Rows());

  if (Cols() != Col.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  for (unsigned int i=1;i<=Rows();i++) {
    Product(i) = 0.00;
    for (unsigned int j=1;j<=Cols();j++) {
      Product(i) += Col(j)*data[i][j];
    }
  }
  return Product;
}

/******************************************************************************/

void FGMatrix::TransposeSquare(void)
{
  for (unsigned int i=1; i<=rows; i++) {
    for (unsigned int j=i+1; j<=cols; j++) {
      double tmp = data[i][j];
      data[i][j] = data[j][i];
      data[j][i] = tmp;
    }
  }
}

/******************************************************************************/

void FGMatrix::TransposeNonSquare(void)
{
  double **tran;

  tran = FGalloc(rows,cols);

  for (unsigned int i=1; i<=rows; i++) {
    for (unsigned int j=1; j<=cols; j++) {
      tran[j][i] = data[i][j];
    }
  }

  dealloc(data,rows);

  data       = tran;
  unsigned int m = rows;
  rows       = cols;
  cols       = m;
}

/******************************************************************************/

FGColumnVector::FGColumnVector(void):FGMatrix(3,1) { }
FGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { }
FGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { }
FGColumnVector::~FGColumnVector() { }

/******************************************************************************/

double& FGColumnVector::operator()(int m) const
{
  return FGMatrix::operator()(m,1);
}

/******************************************************************************/

FGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col)
{
  FGColumnVector Product(Col.Rows());

  if (Mat.Cols() != Col.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  for (unsigned int i=1;i<=Mat.Rows();i++) {
    Product(i) = 0.00;
    for (unsigned int j=1;j<=Mat.Cols();j++) {
      Product(i) += Col(j)*Mat(i,j);
    }
  }

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator+(const FGColumnVector& C)
{
  if (Rows() != C.Rows()) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator *";
    throw mE;
  }

  FGColumnVector Sum(C.Rows());

  for (unsigned int i=1; i<=C.Rows(); i++) {
    Sum(i) = C(i) + data[i][1];
  }

  return Sum;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator*(const double scalar)
{
  FGColumnVector Product(Rows());

  for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1];

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator-(const FGColumnVector& V)
{
  if ((Rows() != V.Rows()) || (Cols() != V.Cols())) {
    MatrixException mE;
    mE.Message = "Invalid row/column match in Column Vector operator -";
    throw mE;
  }

  FGColumnVector Diff(Rows());

  for (unsigned int i=1; i<=Rows(); i++) {
    Diff(i) = data[i][1] - V(i);
  }

  return Diff;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator/(const double scalar)
{
  FGColumnVector Quotient(Rows());

  for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] / scalar;

  return Quotient;
}

/******************************************************************************/

FGColumnVector operator*(const double scalar, const FGColumnVector& C)
{
  FGColumnVector Product(C.Rows());

  for (unsigned int i=1; i<=C.Rows(); i++) {
     Product(i) = scalar * C(i);
  }

  return Product;
}

/******************************************************************************/

float FGColumnVector::Magnitude(void)
{
  double num=0.0;

  if ((data[1][1] == 0.00) &&
      (data[2][1] == 0.00) &&
      (data[3][1] == 0.00))
  {
    return 0.00;
  } else {
    for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1];
    return sqrt(num);
  }
}

/******************************************************************************/

FGColumnVector FGColumnVector::Normalize(void)
{
  double Mag = Magnitude();

  if(Mag != 0 {
    for (unsigned int i=1; i<=Rows(); i++)
      for (unsigned int j=1; j<=Cols(); j++)
        data[i][j] = data[i][j]/Mag;
  }

  return *this;
}

/******************************************************************************/

FGColumnVector FGColumnVector::operator*(const FGColumnVector& V)
{
  if (Rows() != 3 || V.Rows() != 3) {
    MatrixException mE;
    mE.Message = "Invalid row count in vector cross product function";
    throw mE;
  }

  FGColumnVector Product(3);

  Product(1) = data[2][1] * V(3) - data[3][1] * V(2);
  Product(2) = data[3][1] * V(1) - data[1][1] * V(3);
  Product(3) = data[1][1] * V(2) - data[2][1] * V(1);

  return Product;
}

/******************************************************************************/

FGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V)
{
  if (Rows() != 3 || V.Rows() != 3) {
    MatrixException mE;
    mE.Message = "Invalid row count in vector cross product function";
    throw mE;
  }

  FGColumnVector Product(3);

  Product(1) = data[1][1] * V(1);
  Product(2) = data[2][1] * V(2);
  Product(3) = data[3][1] * V(3);

  return Product;
}

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


<commit_before>/*
 * Copyright (c) 2011, The University of Oxford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the University of Oxford nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "sky/oskar_SkyModel.h"
#include "sky/oskar_load_sources.h"
#include "sky/oskar_date_time_to_mjd.h"

#include "station/oskar_StationModel.h"

#include "interferometry/oskar_TelescopeModel.h"
#include "interferometry/oskar_interferometer1_scalar.h"
#include "interferometry/oskar_VisData.h"

#include "apps/lib/oskar_load_telescope.h"
#include "apps/lib/oskar_load_stations.h"
#include "apps/lib/oskar_Settings.h"

#ifndef OSKAR_NO_MS
#include "apps/lib/oskar_write_ms.h"
#endif

#include "utility/oskar_cuda_device_info.h"

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <math.h>

#include <QtCore/QTime>

using namespace std;

int sim1_d(const oskar_Settings& settings);
int sim1_f(const oskar_Settings& settings);

int main(int argc, char** argv)
{
    // $> oskar_sim1_scalar settings_file.txt
    if (argc != 2)
    {
        fprintf(stderr, "ERROR: Missing command line arguments.\n");
        fprintf(stderr, "Usage:  $ oskar_sim1_scalar [settings file]\n");
        return EXIT_FAILURE;
    }

    oskar_Settings settings;
    if (!settings.load(QString(argv[1]))) return EXIT_FAILURE;
    settings.print();

    QTime timer;
    timer.start();

    // Double precision.
    if (settings.double_precision())
    {
        sim1_d(settings);
    }

    // Single precision.
    else
    {
        sim1_f(settings);
    }

    printf("= Completed simulation after %f seconds.\n", timer.elapsed() / 1.0e3);

    return EXIT_SUCCESS;
}

int sim1_d(const oskar_Settings& settings)
{
    // ============== Load input data =========================================
    oskar_SkyModelGlobal_d sky;
    oskar_load_sources_d(settings.sky_file().toLatin1().data(), &sky);
    oskar_TelescopeModel_d telescope;
    oskar_load_telescope_d(settings.telescope_file().toLatin1().data(),
            settings.longitude_rad(), settings.latitude_rad(), &telescope);
    oskar_StationModel_d* stations;
    const char* station_dir = settings.station_dir().toLatin1().data();
    unsigned num_stations = oskar_load_stations_d(station_dir, &stations,
            &telescope.identical_stations);
    if (num_stations != telescope.num_antennas)
    {
        fprintf(stderr, "ERROR: Error loading telescope geometry.\n");
        return EXIT_FAILURE;
    }

    // ============== Simulation loop =========================================
    int error_code = 0;
    for (unsigned i = 0; i < settings.obs().num_channels(); ++i)
    {
        unsigned year   = settings.obs().start_time_utc_year();
        unsigned month  = settings.obs().start_time_utc_month();
        unsigned day    = settings.obs().start_time_utc_day();
        unsigned hour   = settings.obs().start_time_utc_hour();
        unsigned minute = settings.obs().start_time_utc_minute();
        double second   = settings.obs().start_time_utc_second();
        double day_fraction = (hour + minute/60 + second/3600) / 24.0;
        double start_time_mjd_utc = oskar_date_time_to_mjd_d(
                year, month, day, day_fraction);
        printf("- %i/%i/%i %i:%i:%f -> mjd %f\n", day, month, year, hour, minute,
                second, start_time_mjd_utc);

        double frequency = settings.obs().frequency(i);
        printf("- Frequency: %e\n", frequency);

        // Allocate memory for frequency scaled sky model.
        oskar_SkyModelGlobal_d sky_temp;
        sky_temp.num_sources = sky.num_sources;
        sky_temp.Dec = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.RA  = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.I   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.Q   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.U   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.V   = (double*) malloc(sky.num_sources * sizeof(double));
        memcpy(sky_temp.Dec, sky.Dec,  sky.num_sources * sizeof(double));
        memcpy(sky_temp.RA,  sky.RA,   sky.num_sources * sizeof(double));
        memcpy(sky_temp.I,   sky.I,    sky.num_sources * sizeof(double));
        for (int s = 0; s < sky.num_sources; ++s)
        {
//            sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);
            sky_temp.I[s] *= pow(frequency / settings.obs().start_frequency(), -0.7);
        }

        // Allocate visibility data.
        oskar_VisData_d vis;
        int num_baselines = num_stations * (num_stations-1) / 2;
        oskar_allocate_vis_data_d(num_baselines * settings.obs().num_vis_dumps(), &vis);

        error_code = oskar_interferometer1_scalar_d(telescope, stations, sky,
                settings.obs().ra0_rad(), settings.obs().dec0_rad(),
                settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),
                settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),
                settings.obs().num_fringe_ave(), frequency,
                settings.obs().channel_bandwidth(),
                settings.disable_station_beam(), &vis);

        printf("= Number of visibility points generated: %i\n", vis.num_samples);

        // Write visibility binary file.
        if (!settings.obs().oskar_vis_filename().isEmpty())
        {
            QString vis_file = settings.obs().oskar_vis_filename() + "_channel_" + QString::number(i) + ".dat";
            printf("= Writing OSKAR visibility data file: %s\n",
                    vis_file.toLatin1().data());
            oskar_write_vis_data_d(vis_file.toLatin1().data(), &vis);
        }

        // Write MS.
#ifndef OSKAR_NO_MS
        if (!settings.obs().ms_filename().isEmpty())
        {
            QString ms_file = settings.obs().ms_filename() + "_channel_" + QString::number(i) + ".ms";
            printf("= Writing Measurement Set: %s\n", ms_file.toLatin1().data());
            oskar_write_ms_d(ms_file.toLatin1().data(), &settings, &vis, true);
        }
#endif

        free(sky_temp.RA);
        free(sky_temp.Dec);
        free(sky_temp.I);
        free(sky_temp.Q);
        free(sky_temp.U);
        free(sky_temp.V);
        oskar_free_vis_data_d(&vis);
    }

    // ============== Cleanup =================================================
    free(sky.RA);
    free(sky.Dec);
    free(sky.I);
    free(sky.Q);
    free(sky.U);
    free(sky.V);
    free(telescope.antenna_x);
    free(telescope.antenna_y);
    free(telescope.antenna_z);
    for (unsigned i = 0; i < num_stations; ++i)
    {
        free(stations[i].antenna_x);
        free(stations[i].antenna_y);
    }
    free(stations);

    return EXIT_SUCCESS;
}

int sim1_f(const oskar_Settings& settings)
{
    // ============== Load input data =========================================
    oskar_SkyModelGlobal_f sky;
    oskar_load_sources_f(settings.sky_file().toLatin1().data(), &sky);
    oskar_TelescopeModel_f telescope;
    oskar_load_telescope_f(settings.telescope_file().toLatin1().data(),
            settings.longitude_rad(), settings.latitude_rad(), &telescope);
    oskar_StationModel_f* stations;
    const char* station_dir = settings.station_dir().toLatin1().data();
    unsigned num_stations = oskar_load_stations_f(station_dir, &stations,
            &telescope.identical_stations);
    if (num_stations != telescope.num_antennas)
    {
        fprintf(stderr, "ERROR: Error loading telescope geometry.\n");
        return EXIT_FAILURE;
    }

    // ============== Simulation loop =========================================
    int error_code = 0;
    for (unsigned i = 0; i < settings.obs().num_channels(); ++i)
    {
        float frequency = settings.obs().frequency(i);
        printf("- Frequency: %e\n", frequency);

        // Allocate memory for frequency scaled sky model.
        oskar_SkyModelGlobal_f sky_temp;
        sky_temp.num_sources = sky.num_sources;
        sky_temp.Dec = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.RA  = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.I   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.Q   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.U   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.V   = (float*) malloc(sky.num_sources * sizeof(float));
        memcpy(sky_temp.Dec, sky.Dec,  sky.num_sources * sizeof(float));
        memcpy(sky_temp.RA,  sky.RA,   sky.num_sources * sizeof(float));
        memcpy(sky_temp.I,   sky.I,    sky.num_sources * sizeof(float));
        for (int s = 0; s < sky.num_sources; ++s)
        {
//            sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);
            sky_temp.I[s] *= pow(frequency / settings.obs().start_frequency(), -0.7);
        }

        // Allocate visibility data.
        oskar_VisData_f vis;
        int num_baselines = num_stations * (num_stations-1) / 2;
        oskar_allocate_vis_data_f(num_baselines * settings.obs().num_vis_dumps(), &vis);

        error_code = oskar_interferometer1_scalar_f(telescope, stations, sky,
                settings.obs().ra0_rad(), settings.obs().dec0_rad(),
                settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),
                settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),
                settings.obs().num_fringe_ave(), frequency, settings.obs().channel_bandwidth(),
                settings.disable_station_beam(), &vis);

        printf("= Number of visibility points generated: %i\n", vis.num_samples);

        // Write visibility binary file.
        if (!settings.obs().oskar_vis_filename().isEmpty())
        {
            QString vis_file = settings.obs().oskar_vis_filename() + "_channel_" + QString::number(i) + ".dat";
            printf("= Writing OSKAR visibility data file: %s\n",
                    vis_file.toLatin1().data());
            oskar_write_vis_data_f(vis_file.toLatin1().data(), &vis);
        }

        // Write MS.
#ifndef OSKAR_NO_MS
        if (!settings.obs().ms_filename().isEmpty())
        {
            QString ms_file = settings.obs().ms_filename() + "_channel_" + QString::number(i) + ".ms";
            printf("= Writing Measurement Set: %s\n", ms_file.toLatin1().data());
            oskar_write_ms_f(ms_file.toLatin1().data(), &settings, &vis, true);
        }
#endif

        free(sky_temp.RA);
        free(sky_temp.Dec);
        free(sky_temp.I);
        free(sky_temp.Q);
        free(sky_temp.U);
        free(sky_temp.V);
        oskar_free_vis_data_f(&vis);
    }

    // ============== Cleanup =================================================
    free(sky.RA);
    free(sky.Dec);
    free(sky.I);
    free(sky.Q);
    free(sky.U);
    free(sky.V);
    free(telescope.antenna_x);
    free(telescope.antenna_y);
    free(telescope.antenna_z);
    for (unsigned i = 0; i < num_stations; ++i)
    {
        free(stations[i].antenna_x);
        free(stations[i].antenna_y);
    }
    free(stations);

    return EXIT_SUCCESS;
}

<commit_msg>fixed time for float version of sim 1 script<commit_after>/*
 * Copyright (c) 2011, The University of Oxford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the University of Oxford nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "sky/oskar_SkyModel.h"
#include "sky/oskar_load_sources.h"
#include "sky/oskar_date_time_to_mjd.h"

#include "station/oskar_StationModel.h"

#include "interferometry/oskar_TelescopeModel.h"
#include "interferometry/oskar_interferometer1_scalar.h"
#include "interferometry/oskar_VisData.h"

#include "apps/lib/oskar_load_telescope.h"
#include "apps/lib/oskar_load_stations.h"
#include "apps/lib/oskar_Settings.h"

#ifndef OSKAR_NO_MS
#include "apps/lib/oskar_write_ms.h"
#endif

#include "utility/oskar_cuda_device_info.h"

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <math.h>

#include <QtCore/QTime>

using namespace std;

int sim1_d(const oskar_Settings& settings);
int sim1_f(const oskar_Settings& settings);

int main(int argc, char** argv)
{
    // $> oskar_sim1_scalar settings_file.txt
    if (argc != 2)
    {
        fprintf(stderr, "ERROR: Missing command line arguments.\n");
        fprintf(stderr, "Usage:  $ oskar_sim1_scalar [settings file]\n");
        return EXIT_FAILURE;
    }

    oskar_Settings settings;
    if (!settings.load(QString(argv[1]))) return EXIT_FAILURE;
    settings.print();

    QTime timer;
    timer.start();

    // Double precision.
    if (settings.double_precision())
    {
        sim1_d(settings);
    }

    // Single precision.
    else
    {
        sim1_f(settings);
    }

    printf("= Completed simulation after %f seconds.\n", timer.elapsed() / 1.0e3);

    return EXIT_SUCCESS;
}

int sim1_d(const oskar_Settings& settings)
{
    // ============== Load input data =========================================
    oskar_SkyModelGlobal_d sky;
    oskar_load_sources_d(settings.sky_file().toLatin1().data(), &sky);
    oskar_TelescopeModel_d telescope;
    oskar_load_telescope_d(settings.telescope_file().toLatin1().data(),
            settings.longitude_rad(), settings.latitude_rad(), &telescope);
    oskar_StationModel_d* stations;
    const char* station_dir = settings.station_dir().toLatin1().data();
    unsigned num_stations = oskar_load_stations_d(station_dir, &stations,
            &telescope.identical_stations);
    if (num_stations != telescope.num_antennas)
    {
        fprintf(stderr, "ERROR: Error loading telescope geometry.\n");
        return EXIT_FAILURE;
    }

    // ============== Simulation loop =========================================
    int error_code = 0;
    for (unsigned i = 0; i < settings.obs().num_channels(); ++i)
    {
        unsigned year   = settings.obs().start_time_utc_year();
        unsigned month  = settings.obs().start_time_utc_month();
        unsigned day    = settings.obs().start_time_utc_day();
        unsigned hour   = settings.obs().start_time_utc_hour();
        unsigned minute = settings.obs().start_time_utc_minute();
        double second   = settings.obs().start_time_utc_second();
        double day_fraction = (hour + minute/60 + second/3600) / 24.0;
        double start_time_mjd_utc = oskar_date_time_to_mjd_d(
                year, month, day, day_fraction);
        printf("- %i/%i/%i %i:%i:%f -> mjd %f\n", day, month, year, hour, minute,
                second, start_time_mjd_utc);

        double frequency = settings.obs().frequency(i);
        printf("- Frequency: %e\n", frequency);

        // Allocate memory for frequency scaled sky model.
        oskar_SkyModelGlobal_d sky_temp;
        sky_temp.num_sources = sky.num_sources;
        sky_temp.Dec = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.RA  = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.I   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.Q   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.U   = (double*) malloc(sky.num_sources * sizeof(double));
        sky_temp.V   = (double*) malloc(sky.num_sources * sizeof(double));
        memcpy(sky_temp.Dec, sky.Dec,  sky.num_sources * sizeof(double));
        memcpy(sky_temp.RA,  sky.RA,   sky.num_sources * sizeof(double));
        memcpy(sky_temp.I,   sky.I,    sky.num_sources * sizeof(double));
        for (int s = 0; s < sky.num_sources; ++s)
        {
//            sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);
            sky_temp.I[s] *= pow(frequency / settings.obs().start_frequency(), -0.7);
        }

        // Allocate visibility data.
        oskar_VisData_d vis;
        int num_baselines = num_stations * (num_stations-1) / 2;
        oskar_allocate_vis_data_d(num_baselines * settings.obs().num_vis_dumps(), &vis);

        error_code = oskar_interferometer1_scalar_d(telescope, stations, sky,
                settings.obs().ra0_rad(), settings.obs().dec0_rad(),
                settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),
                settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),
                settings.obs().num_fringe_ave(), frequency,
                settings.obs().channel_bandwidth(),
                settings.disable_station_beam(), &vis);

        printf("= Number of visibility points generated: %i\n", vis.num_samples);

        // Write visibility binary file.
        if (!settings.obs().oskar_vis_filename().isEmpty())
        {
            QString vis_file = settings.obs().oskar_vis_filename() + "_channel_" + QString::number(i) + ".dat";
            printf("= Writing OSKAR visibility data file: %s\n",
                    vis_file.toLatin1().data());
            oskar_write_vis_data_d(vis_file.toLatin1().data(), &vis);
        }

        // Write MS.
#ifndef OSKAR_NO_MS
        if (!settings.obs().ms_filename().isEmpty())
        {
            QString ms_file = settings.obs().ms_filename() + "_channel_" + QString::number(i) + ".ms";
            printf("= Writing Measurement Set: %s\n", ms_file.toLatin1().data());
            oskar_write_ms_d(ms_file.toLatin1().data(), &settings, &vis, true);
        }
#endif

        free(sky_temp.RA);
        free(sky_temp.Dec);
        free(sky_temp.I);
        free(sky_temp.Q);
        free(sky_temp.U);
        free(sky_temp.V);
        oskar_free_vis_data_d(&vis);
    }

    // ============== Cleanup =================================================
    free(sky.RA);
    free(sky.Dec);
    free(sky.I);
    free(sky.Q);
    free(sky.U);
    free(sky.V);
    free(telescope.antenna_x);
    free(telescope.antenna_y);
    free(telescope.antenna_z);
    for (unsigned i = 0; i < num_stations; ++i)
    {
        free(stations[i].antenna_x);
        free(stations[i].antenna_y);
    }
    free(stations);

    return EXIT_SUCCESS;
}

int sim1_f(const oskar_Settings& settings)
{
    // ============== Load input data =========================================
    oskar_SkyModelGlobal_f sky;
    oskar_load_sources_f(settings.sky_file().toLatin1().data(), &sky);
    oskar_TelescopeModel_f telescope;
    oskar_load_telescope_f(settings.telescope_file().toLatin1().data(),
            settings.longitude_rad(), settings.latitude_rad(), &telescope);
    oskar_StationModel_f* stations;
    const char* station_dir = settings.station_dir().toLatin1().data();
    unsigned num_stations = oskar_load_stations_f(station_dir, &stations,
            &telescope.identical_stations);
    if (num_stations != telescope.num_antennas)
    {
        fprintf(stderr, "ERROR: Error loading telescope geometry.\n");
        return EXIT_FAILURE;
    }

    // ============== Simulation loop =========================================
    int error_code = 0;
    for (unsigned i = 0; i < settings.obs().num_channels(); ++i)
    {
        unsigned year   = settings.obs().start_time_utc_year();
        unsigned month  = settings.obs().start_time_utc_month();
        unsigned day    = settings.obs().start_time_utc_day();
        unsigned hour   = settings.obs().start_time_utc_hour();
        unsigned minute = settings.obs().start_time_utc_minute();
        float second   = settings.obs().start_time_utc_second();
        float day_fraction = (hour + minute/60 + second/3600) / 24.0;
        float start_time_mjd_utc = oskar_date_time_to_mjd_d(
                year, month, day, day_fraction);
        printf("- %i/%i/%i %i:%i:%f -> mjd %f\n", day, month, year, hour, minute,
                second, start_time_mjd_utc);

        float frequency = settings.obs().frequency(i);
        printf("- Frequency: %e\n", frequency);

        // Allocate memory for frequency scaled sky model.
        oskar_SkyModelGlobal_f sky_temp;
        sky_temp.num_sources = sky.num_sources;
        sky_temp.Dec = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.RA  = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.I   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.Q   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.U   = (float*) malloc(sky.num_sources * sizeof(float));
        sky_temp.V   = (float*) malloc(sky.num_sources * sizeof(float));
        memcpy(sky_temp.Dec, sky.Dec,  sky.num_sources * sizeof(float));
        memcpy(sky_temp.RA,  sky.RA,   sky.num_sources * sizeof(float));
        memcpy(sky_temp.I,   sky.I,    sky.num_sources * sizeof(float));
        for (int s = 0; s < sky.num_sources; ++s)
        {
//            sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);
            sky_temp.I[s] *= pow(frequency / settings.obs().start_frequency(), -0.7);
        }

        // Allocate visibility data.
        oskar_VisData_f vis;
        int num_baselines = num_stations * (num_stations-1) / 2;
        oskar_allocate_vis_data_f(num_baselines * settings.obs().num_vis_dumps(), &vis);

        error_code = oskar_interferometer1_scalar_f(telescope, stations, sky,
                settings.obs().ra0_rad(), settings.obs().dec0_rad(),
                start_time_mjd_utc, settings.obs().obs_length_days(),
                settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),
                settings.obs().num_fringe_ave(), frequency, settings.obs().channel_bandwidth(),
                settings.disable_station_beam(), &vis);

        printf("= Number of visibility points generated: %i\n", vis.num_samples);

        // Write visibility binary file.
        if (!settings.obs().oskar_vis_filename().isEmpty())
        {
            QString vis_file = settings.obs().oskar_vis_filename() + "_channel_" + QString::number(i) + ".dat";
            printf("= Writing OSKAR visibility data file: %s\n",
                    vis_file.toLatin1().data());
            oskar_write_vis_data_f(vis_file.toLatin1().data(), &vis);
        }

        // Write MS.
#ifndef OSKAR_NO_MS
        if (!settings.obs().ms_filename().isEmpty())
        {
            QString ms_file = settings.obs().ms_filename() + "_channel_" + QString::number(i) + ".ms";
            printf("= Writing Measurement Set: %s\n", ms_file.toLatin1().data());
            oskar_write_ms_f(ms_file.toLatin1().data(), &settings, &vis, true);
        }
#endif

        free(sky_temp.RA);
        free(sky_temp.Dec);
        free(sky_temp.I);
        free(sky_temp.Q);
        free(sky_temp.U);
        free(sky_temp.V);
        oskar_free_vis_data_f(&vis);
    }

    // ============== Cleanup =================================================
    free(sky.RA);
    free(sky.Dec);
    free(sky.I);
    free(sky.Q);
    free(sky.U);
    free(sky.V);
    free(telescope.antenna_x);
    free(telescope.antenna_y);
    free(telescope.antenna_z);
    for (unsigned i = 0; i < num_stations; ++i)
    {
        free(stations[i].antenna_x);
        free(stations[i].antenna_y);
    }
    free(stations);

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief basic exceptions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Exceptions.h"

using namespace std;
using namespace triagens::basics;

// -----------------------------------------------------------------------------
// --SECTION--                                                      public types
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief base class for all errors
////////////////////////////////////////////////////////////////////////////////

TriagensError::TriagensError (string const& type, string const& details, char const* file, int line)
  : _type("unknown"),
    _details(details),
    _file(file),
    _line(line) {
  _message = "exception in '" + _file + "' at line " + StringUtils::itoa(_line) + ": "
           + "type = '" + _type + "'";

  if (! details.empty()) {
    _message += " details = '" + _details + "'";
  }

#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
  _getBacktrace(_message);
#endif
#endif

}

TriagensError::~TriagensError () throw () {
}

char const * TriagensError::what () const throw() {
  return _message.c_str();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for internal errors
////////////////////////////////////////////////////////////////////////////////

InternalError::InternalError (string const& details, char const* file, int line)
  : TriagensError("internal error", details, file, line) {
}

InternalError::InternalError (std::exception const& ex, char const* file, int line)
  : TriagensError("internal exception", ex.what(), file, line) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for out-of-memory errors
////////////////////////////////////////////////////////////////////////////////

OutOfMemoryError::OutOfMemoryError (char const* file, int line)
  : TriagensError("out-of-memory", "", file, line) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for file errors
////////////////////////////////////////////////////////////////////////////////

FileError::FileError (string const& func,
                      string const& details,
                      string const& filename,
                      string const& mode,
                      int error,
                      char const* file,
                      int line)
  : TriagensError("file-error", details, file, line),
    _filename(filename),
    _mode(mode),
    _error(error) {
  if (! mode.empty()) {
    _message += " mode = '" + _mode + "'";
  }

  if (_error != 0) {
    _message += " errno = " + StringUtils::itoa(_error) + ""
             +  " error = '" + strerror(_error) + "'";
  }

  if (! _filename.empty()) {
    _message += " file = '" + _filename + "'";
  }
}

FileError::~FileError () throw () {
}

void FileError::setFilename (string const& filename) {
  _filename = filename;

  if (! _filename.empty()) {
    _message += " file = '" + _filename + "'";
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for parse errors
////////////////////////////////////////////////////////////////////////////////

ParseError::ParseError (string const& details,
                        int lineNumber,
                        char const* file,
                        int line)
  : TriagensError("parse-error", details, file, line),
    _lineNumber(lineNumber) {
  if (_lineNumber != -1) {
    _message += " line-number = '" + StringUtils::itoa(_lineNumber) + "'";
  }
}

void ParseError::setLineNumber (int lineNumber) {
  _lineNumber = lineNumber;

  if (_lineNumber != -1) {
    _message += " line-number = '" + StringUtils::itoa(_lineNumber) + "'";
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for parameter errors
////////////////////////////////////////////////////////////////////////////////

ParameterError::ParameterError (string const& parameter,
                                string const& details,
                                string const& func,
                                char const* file,
                                int line)
  : TriagensError("parameter-error", details, file, line),
    _parameter(parameter),
    _func(func) {
  _message += " parameter = '" + _parameter + "'";

  if (! _func.empty()) {
    _message += " func = '" + _func + "'";
  }
}

ParameterError::~ParameterError () throw () {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Fix a but where a type argument was unused.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief basic exceptions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Exceptions.h"

using namespace std;
using namespace triagens::basics;

// -----------------------------------------------------------------------------
// --SECTION--                                                      public types
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief base class for all errors
////////////////////////////////////////////////////////////////////////////////

TriagensError::TriagensError (string const& type, string const& details, char const* file, int line)
  : _type(type),
    _details(details),
    _file(file),
    _line(line) {
  _message = "exception in '" + _file + "' at line " + StringUtils::itoa(_line) + ": "
           + "type = '" + _type + "'";

  if (! details.empty()) {
    _message += " details = '" + _details + "'";
  }

#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
  _getBacktrace(_message);
#endif
#endif

}

TriagensError::~TriagensError () throw () {
}

char const * TriagensError::what () const throw() {
  return _message.c_str();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for internal errors
////////////////////////////////////////////////////////////////////////////////

InternalError::InternalError (string const& details, char const* file, int line)
  : TriagensError("internal error", details, file, line) {
}

InternalError::InternalError (std::exception const& ex, char const* file, int line)
  : TriagensError("internal exception", ex.what(), file, line) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for out-of-memory errors
////////////////////////////////////////////////////////////////////////////////

OutOfMemoryError::OutOfMemoryError (char const* file, int line)
  : TriagensError("out-of-memory", "", file, line) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for file errors
////////////////////////////////////////////////////////////////////////////////

FileError::FileError (string const& func,
                      string const& details,
                      string const& filename,
                      string const& mode,
                      int error,
                      char const* file,
                      int line)
  : TriagensError("file-error", details, file, line),
    _filename(filename),
    _mode(mode),
    _error(error) {
  if (! mode.empty()) {
    _message += " mode = '" + _mode + "'";
  }

  if (_error != 0) {
    _message += " errno = " + StringUtils::itoa(_error) + ""
             +  " error = '" + strerror(_error) + "'";
  }

  if (! _filename.empty()) {
    _message += " file = '" + _filename + "'";
  }
}

FileError::~FileError () throw () {
}

void FileError::setFilename (string const& filename) {
  _filename = filename;

  if (! _filename.empty()) {
    _message += " file = '" + _filename + "'";
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for parse errors
////////////////////////////////////////////////////////////////////////////////

ParseError::ParseError (string const& details,
                        int lineNumber,
                        char const* file,
                        int line)
  : TriagensError("parse-error", details, file, line),
    _lineNumber(lineNumber) {
  if (_lineNumber != -1) {
    _message += " line-number = '" + StringUtils::itoa(_lineNumber) + "'";
  }
}

void ParseError::setLineNumber (int lineNumber) {
  _lineNumber = lineNumber;

  if (_lineNumber != -1) {
    _message += " line-number = '" + StringUtils::itoa(_lineNumber) + "'";
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exception for parameter errors
////////////////////////////////////////////////////////////////////////////////

ParameterError::ParameterError (string const& parameter,
                                string const& details,
                                string const& func,
                                char const* file,
                                int line)
  : TriagensError("parameter-error", details, file, line),
    _parameter(parameter),
    _func(func) {
  _message += " parameter = '" + _parameter + "'";

  if (! _func.empty()) {
    _message += " func = '" + _func + "'";
  }
}

ParameterError::~ParameterError () throw () {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>