<commit_before>//=============================================================================================================
/**
* @file     coherency.cpp
* @author   Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     April, 2018
*
* @section  LICENSE
*
* Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @note Notes:
* - Some of this code was adapted from mne-python (https://martinos.org/mne) with permission from Alexandre Gramfort.
* - QtConcurrent can be used to speed up computation.
*
* @brief     Coherency class declaration.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "coherency.h"
#include "network/networknode.h"
#include "network/networkedge.h"
#include "network/network.h"

#include <utils/spectral.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QtConcurrent>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <unsupported/Eigen/FFT>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace CONNECTIVITYLIB;
using namespace Eigen;
using namespace UTILSLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

Coherency::Coherency()
{
}

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

QVector<MatrixXcd> Coherency::computeCoherency(const QList<MatrixXd> &matDataList,
                                               int iNfft,
                                               const QString &sWindowType)
{
    // Check that iNfft >= signal length
    int iSignalLength = matDataList.at(0).cols();
    if (iNfft < iSignalLength) {
        iNfft = iSignalLength;
    }

    // Generate tapers
    QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iSignalLength, sWindowType);

    // Initialize vecPsdAvg and vecCsdAvg
    int iNRows = matDataList.at(0).rows();
    int iNFreqs = int(floor(iNfft / 2.0)) + 1;

    // Generate tapered spectra, PSD, and CSD and sum over epoch
    // This part could be parallelized with QtConcurrent::mappedReduced
    QList<AbstractMetricInputData> lData;
    for (int i = 0; i < matDataList.size(); ++i) {
        AbstractMetricInputData dataTemp;
        dataTemp.matInputData = matDataList.at(i);
        dataTemp.iNRows = iNRows;
        dataTemp.iNFreqs = iNFreqs;
        dataTemp.iNfft = iNfft;
        dataTemp.tapers = tapers;

        lData.append(dataTemp);
    }

//    // Sequential
//    AbstractMetricResultData finalResult;

//    for (int i = 0; i < lData.length(); ++i) {
//        reduce(finalResult, compute(lData.at(i)));
//    }

    // Parallel
    QFuture<AbstractMetricResultData> result = QtConcurrent::mappedReduced(lData,
                                                                           compute,
                                                                           reduce);
    result.waitForFinished();

    AbstractMetricResultData finalResult = result.result();

    QVector<MatrixXcd> vecCoherency;
    finalResult.matPsdAvg = finalResult.matPsdAvg.cwiseSqrt();

    for (int i = 0; i < iNRows; ++i) {
        MatrixXd matPSDtmp = MatrixXd::Zero(iNRows, iNFreqs);
        for(int j = 0; j < iNRows; ++j){
            matPSDtmp.row(j) = finalResult.matPsdAvg.row(i).cwiseProduct(finalResult.matPsdAvg.row(j));
        }
        vecCoherency.append(finalResult.vecCsdAvg.at(i).cwiseQuotient(matPSDtmp));
    }

    return vecCoherency;
}

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

AbstractMetricResultData Coherency::compute(const AbstractMetricInputData& inputData)
{
    MatrixXd data = inputData.matInputData;

    MatrixXd matPsdAvg = MatrixXd::Zero(inputData.iNRows, inputData.iNFreqs);

    QVector<MatrixXcd> vecCsdAvg;

    QElapsedTimer time;
    int mSeconds;
    time.start();
    //Remove mean
    for (int i = 0; i < data.rows(); ++i) {
        data.row(i).array() -= data.row(i).mean();
    }
    mSeconds = time.elapsed();
    //qDebug()<<"mean" << mSeconds;

    // This part could be parallelized with QtConcurrent::mapped
    time.restart();
    QVector<Eigen::MatrixXcd> vecTapSpectra = Spectral::computeTaperedSpectraMatrix(data,
                                                                                inputData.tapers.first,
                                                                                inputData.iNfft,
                                                                                true);
    mSeconds = time.elapsed();
    //qDebug()<<"tapSpectra" << mSeconds;

    // This part could be parallelized with QtConcurrent::mappedReduced
    time.restart();
    for (int j = 0; j < inputData.iNRows; ++j) {
        RowVectorXd vecTmpPsd = Spectral::psdFromTaperedSpectra(vecTapSpectra.at(j),
                                                                inputData.tapers.second,
                                                                inputData.iNfft,
                                                                1.0);
        matPsdAvg.row(j) = vecTmpPsd;
    }
    mSeconds = time.elapsed();
    //qDebug()<<"psd" << mSeconds;

    // This part could be parallelized with QtConcurrent::mappedReduced
    time.restart();
    for (int j = 0; j < inputData.iNRows; ++j) {
        MatrixXcd matCsd = MatrixXcd(inputData.iNRows, inputData.iNFreqs);
        for (int k = 0; k < inputData.iNRows; ++k) {
            matCsd.row(k) = Spectral::csdFromTaperedSpectra(vecTapSpectra.at(j),
                                                            vecTapSpectra.at(k),
                                                            inputData.tapers.second,
                                                            inputData.tapers.second,
                                                            inputData.iNfft,
                                                            1.0);
        }

        vecCsdAvg.append(matCsd);
    }
    mSeconds = time.elapsed();
    //qDebug()<<"csd" << mSeconds;

    AbstractMetricResultData resultData;
    resultData.iNFreqs = inputData.iNFreqs;
    resultData.iNRows = inputData.iNRows;
    resultData.matPsdAvg = matPsdAvg;
    resultData.vecCsdAvg = vecCsdAvg;

    return resultData;
}

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

void Coherency::reduce(AbstractMetricResultData& finalData,
                       const AbstractMetricResultData& resultData)
{
    if(finalData.matPsdAvg.rows() == 0 || finalData.matPsdAvg.cols() == 0) {
        finalData.matPsdAvg = resultData.matPsdAvg;
    } else {
        finalData.matPsdAvg += resultData.matPsdAvg;
    }

    if(finalData.vecCsdAvg.isEmpty()) {
        finalData.vecCsdAvg = resultData.vecCsdAvg;
    } else {
        for (int j = 0; j < finalData.vecCsdAvg.size(); ++j) {
            finalData.vecCsdAvg[j] += resultData.vecCsdAvg.at(j);
        }
    }
}
<commit_msg>[SC-167] Cleaned up Coherency class<commit_after>//=============================================================================================================
/**
* @file     coherency.cpp
* @author   Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     April, 2018
*
* @section  LICENSE
*
* Copyright (C) 2018, Daniel Strohmeier and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @note Notes:
* - Some of this code was adapted from mne-python (https://martinos.org/mne) with permission from Alexandre Gramfort.
* - QtConcurrent can be used to speed up computation.
*
* @brief     Coherency class declaration.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "coherency.h"
#include "network/networknode.h"
#include "network/networkedge.h"
#include "network/network.h"

#include <utils/spectral.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QtConcurrent>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <unsupported/Eigen/FFT>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace CONNECTIVITYLIB;
using namespace Eigen;
using namespace UTILSLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

Coherency::Coherency()
{
}

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

QVector<MatrixXcd> Coherency::computeCoherency(const QList<MatrixXd> &matDataList,
                                               int iNfft,
                                               const QString &sWindowType)
{
    // Check that iNfft >= signal length
    int iSignalLength = matDataList.at(0).cols();
    if (iNfft < iSignalLength) {
        iNfft = iSignalLength;
    }

    // Generate tapers
    QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iSignalLength, sWindowType);

    // Initialize vecPsdAvg and vecCsdAvg
    int iNRows = matDataList.at(0).rows();
    int iNFreqs = int(floor(iNfft / 2.0)) + 1;

    // Generate tapered spectra, PSD, and CSD and sum over epoch
    // This part could be parallelized with QtConcurrent::mappedReduced
    QList<AbstractMetricInputData> lData;
    for (int i = 0; i < matDataList.size(); ++i) {
        AbstractMetricInputData dataTemp;
        dataTemp.matInputData = matDataList.at(i);
        dataTemp.iNRows = iNRows;
        dataTemp.iNFreqs = iNFreqs;
        dataTemp.iNfft = iNfft;
        dataTemp.tapers = tapers;

        lData.append(dataTemp);
    }

//    // Sequential
//    AbstractMetricResultData finalResult;

//    for (int i = 0; i < lData.length(); ++i) {
//        reduce(finalResult, compute(lData.at(i)));
//    }

    // Parallel
    QFuture<AbstractMetricResultData> result = QtConcurrent::mappedReduced(lData,
                                                                           compute,
                                                                           reduce);
    result.waitForFinished();

    AbstractMetricResultData finalResult = result.result();

    QVector<MatrixXcd> vecCoherency;
    finalResult.matPsdAvg = finalResult.matPsdAvg.cwiseSqrt();

    for (int i = 0; i < iNRows; ++i) {
        MatrixXd matPSDtmp = MatrixXd::Zero(iNRows, iNFreqs);
        for(int j = 0; j < iNRows; ++j){
            matPSDtmp.row(j) = finalResult.matPsdAvg.row(i).cwiseProduct(finalResult.matPsdAvg.row(j));
        }
        vecCoherency.append(finalResult.vecCsdAvg.at(i).cwiseQuotient(matPSDtmp));
    }

    return vecCoherency;
}

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

AbstractMetricResultData Coherency::compute(const AbstractMetricInputData& inputData)
{
    MatrixXd data = inputData.matInputData;

    MatrixXd matPsdAvg = MatrixXd::Zero(inputData.iNRows, inputData.iNFreqs);

    QVector<MatrixXcd> vecCsdAvg;

    //Remove mean
    for (int i = 0; i < data.rows(); ++i) {
        data.row(i).array() -= data.row(i).mean();
    }

    // This part could be parallelized with QtConcurrent::mapped
    QVector<Eigen::MatrixXcd> vecTapSpectra = Spectral::computeTaperedSpectraMatrix(data,
                                                                                inputData.tapers.first,
                                                                                inputData.iNfft,
                                                                                false);

    // This part could be parallelized with QtConcurrent::mappedReduced
    for (int j = 0; j < inputData.iNRows; ++j) {
        RowVectorXd vecTmpPsd = Spectral::psdFromTaperedSpectra(vecTapSpectra.at(j),
                                                                inputData.tapers.second,
                                                                inputData.iNfft,
                                                                1.0);
        matPsdAvg.row(j) = vecTmpPsd;
    }

    // This part could be parallelized with QtConcurrent::mappedReduced
    for (int j = 0; j < inputData.iNRows; ++j) {
        MatrixXcd matCsd = MatrixXcd(inputData.iNRows, inputData.iNFreqs);
        for (int k = 0; k < inputData.iNRows; ++k) {
            matCsd.row(k) = Spectral::csdFromTaperedSpectra(vecTapSpectra.at(j),
                                                            vecTapSpectra.at(k),
                                                            inputData.tapers.second,
                                                            inputData.tapers.second,
                                                            inputData.iNfft,
                                                            1.0);
        }

        vecCsdAvg.append(matCsd);
    }

    AbstractMetricResultData resultData;
    resultData.iNFreqs = inputData.iNFreqs;
    resultData.iNRows = inputData.iNRows;
    resultData.matPsdAvg = matPsdAvg;
    resultData.vecCsdAvg = vecCsdAvg;

    return resultData;
}

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

void Coherency::reduce(AbstractMetricResultData& finalData,
                       const AbstractMetricResultData& resultData)
{
    if(finalData.matPsdAvg.rows() == 0 || finalData.matPsdAvg.cols() == 0) {
        finalData.matPsdAvg = resultData.matPsdAvg;
    } else {
        finalData.matPsdAvg += resultData.matPsdAvg;
    }

    if(finalData.vecCsdAvg.isEmpty()) {
        finalData.vecCsdAvg = resultData.vecCsdAvg;
    } else {
        for (int j = 0; j < finalData.vecCsdAvg.size(); ++j) {
            finalData.vecCsdAvg[j] += resultData.vecCsdAvg.at(j);
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/message_box.h"

#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_signal.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"

#define ANSI_FOREGROUND_RED   "\x1b[31m"
#define ANSI_FOREGROUND_BLACK "\x1b[30m"
#define ANSI_TEXT_BOLD        "\x1b[1m"
#define ANSI_BACKGROUND_GRAY  "\x1b[47m"
#define ANSI_RESET            "\x1b[0m"

namespace atom {

namespace {

class GtkMessageBox {
 public:
  GtkMessageBox(NativeWindow* parent_window,
                MessageBoxType type,
                const std::vector<std::string>& buttons,
                const std::string& title,
                const std::string& message,
                const std::string& detail,
                const gfx::ImageSkia& icon)
      : dialog_scope_(parent_window),
        cancel_id_(0) {
    // Create dialog.
    dialog_ = gtk_message_dialog_new(
        nullptr,  // parent
        static_cast<GtkDialogFlags>(0),  // no flags
        GetMessageType(type),  // type
        GTK_BUTTONS_NONE,  // no buttons
        "%s", message.c_str());
    if (!detail.empty())
      gtk_message_dialog_format_secondary_text(
          GTK_MESSAGE_DIALOG(dialog_), "%s", detail.c_str());

    // Set dialog's icon.
    if (!icon.isNull()) {
      GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(*icon.bitmap());
      GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
      gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), image);
      gtk_widget_show(image);
      g_object_unref(pixbuf);
    }

    // Add buttons.
    for (size_t i = 0; i < buttons.size(); ++i) {
      gtk_dialog_add_button(GTK_DIALOG(dialog_),
                            TranslateToStock(i, buttons[i]),
                            i);
    }

    // Parent window.
    if (parent_window) {
      gfx::NativeWindow window = parent_window->GetNativeWindow();
      libgtk2ui::SetGtkTransientForAura(dialog_, window);
    }
  }

  ~GtkMessageBox() {
    gtk_widget_destroy(dialog_);
  }

  GtkMessageType GetMessageType(MessageBoxType type) {
    switch (type) {
      case MESSAGE_BOX_TYPE_INFORMATION:
        return GTK_MESSAGE_INFO;
      case MESSAGE_BOX_TYPE_WARNING:
        return GTK_MESSAGE_WARNING;
      case MESSAGE_BOX_TYPE_QUESTION:
        return GTK_MESSAGE_QUESTION;
      case MESSAGE_BOX_TYPE_ERROR:
        return GTK_MESSAGE_ERROR;
      default:
        return GTK_MESSAGE_OTHER;
    }
  }

  const char* TranslateToStock(int id, const std::string& text) {
    std::string lower = base::StringToLowerASCII(text);
    if (lower == "cancel") {
      cancel_id_ = id;
      return GTK_STOCK_CANCEL;
    } else if (lower == "no") {
      cancel_id_ = id;
      return GTK_STOCK_NO;
    } else if (lower == "ok") {
      return GTK_STOCK_OK;
    } else if (lower == "yes") {
      return GTK_STOCK_YES;
    } else {
      return text.c_str();
    }
  }

  void Show() {
    gtk_widget_show_all(dialog_);
    // We need to call gtk_window_present after making the widgets visible to
    // make sure window gets correctly raised and gets focus.
    int time = views::X11DesktopHandler::get()->wm_user_time_ms();
    gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
  }

  int RunSynchronous() {
    gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
    Show();
    int response = gtk_dialog_run(GTK_DIALOG(dialog_));
    if (response < 0)
      return cancel_id_;
    else
      return response;
  }

  void RunAsynchronous(const MessageBoxCallback& callback) {
    callback_ = callback;
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), nullptr);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnResponseDialogThunk), this);
    Show();
  }

  CHROMEGTK_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, int);

 private:
  atom::NativeWindow::DialogScope dialog_scope_;

  // The id to return when the dialog is closed without pressing buttons.
  int cancel_id_;

  GtkWidget* dialog_;
  MessageBoxCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(GtkMessageBox);
};

void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) {
  gtk_widget_hide_all(dialog_);

  if (response < 0)
    callback_.Run(cancel_id_);
  else
    callback_.Run(response);
  delete this;
}

}  // namespace

int ShowMessageBox(NativeWindow* parent,
                   MessageBoxType type,
                   const std::vector<std::string>& buttons,
                   const std::string& title,
                   const std::string& message,
                   const std::string& detail,
                   const gfx::ImageSkia& icon) {
  return GtkMessageBox(parent, type, buttons, title, message, detail,
                       icon).RunSynchronous();
}

void ShowMessageBox(NativeWindow* parent,
                    MessageBoxType type,
                    const std::vector<std::string>& buttons,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const gfx::ImageSkia& icon,
                    const MessageBoxCallback& callback) {
  (new GtkMessageBox(parent, type, buttons, title, message, detail,
                     icon))->RunAsynchronous(callback);
}

void ShowErrorBox(const base::string16& title, const base::string16& content) {
  if (Browser::Get()->is_ready()) {
    GtkMessageBox(nullptr, MESSAGE_BOX_TYPE_ERROR, { "OK" }, "Error",
                  base::UTF16ToUTF8(title).c_str(),
                  base::UTF16ToUTF8(content).c_str(),
                  gfx::ImageSkia()).RunSynchronous();
  } else {
    fprintf(stderr,
            ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY
            ANSI_FOREGROUND_RED  "%s\n"
            ANSI_FOREGROUND_BLACK "%s"
            ANSI_RESET "\n",
            base::UTF16ToUTF8(title).c_str(),
            base::UTF16ToUTF8(content).c_str());
  }
}

}  // namespace atom
<commit_msg>Make "title" work<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/message_box.h"

#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_signal.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"

#define ANSI_FOREGROUND_RED   "\x1b[31m"
#define ANSI_FOREGROUND_BLACK "\x1b[30m"
#define ANSI_TEXT_BOLD        "\x1b[1m"
#define ANSI_BACKGROUND_GRAY  "\x1b[47m"
#define ANSI_RESET            "\x1b[0m"

namespace atom {

namespace {

class GtkMessageBox {
 public:
  GtkMessageBox(NativeWindow* parent_window,
                MessageBoxType type,
                const std::vector<std::string>& buttons,
                const std::string& title,
                const std::string& message,
                const std::string& detail,
                const gfx::ImageSkia& icon)
      : dialog_scope_(parent_window),
        cancel_id_(0) {
    // Create dialog.
    dialog_ = gtk_message_dialog_new(
        nullptr,  // parent
        static_cast<GtkDialogFlags>(0),  // no flags
        GetMessageType(type),  // type
        GTK_BUTTONS_NONE,  // no buttons
        "%s", message.c_str());
    if (!detail.empty())
      gtk_message_dialog_format_secondary_text(
          GTK_MESSAGE_DIALOG(dialog_), "%s", detail.c_str());
    if (!title.empty())
      gtk_window_set_title(GTK_WINDOW(dialog_), title.c_str());

    // Set dialog's icon.
    if (!icon.isNull()) {
      GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(*icon.bitmap());
      GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
      gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), image);
      gtk_widget_show(image);
      g_object_unref(pixbuf);
    }

    // Add buttons.
    for (size_t i = 0; i < buttons.size(); ++i) {
      gtk_dialog_add_button(GTK_DIALOG(dialog_),
                            TranslateToStock(i, buttons[i]),
                            i);
    }

    // Parent window.
    if (parent_window) {
      gfx::NativeWindow window = parent_window->GetNativeWindow();
      libgtk2ui::SetGtkTransientForAura(dialog_, window);
    }
  }

  ~GtkMessageBox() {
    gtk_widget_destroy(dialog_);
  }

  GtkMessageType GetMessageType(MessageBoxType type) {
    switch (type) {
      case MESSAGE_BOX_TYPE_INFORMATION:
        return GTK_MESSAGE_INFO;
      case MESSAGE_BOX_TYPE_WARNING:
        return GTK_MESSAGE_WARNING;
      case MESSAGE_BOX_TYPE_QUESTION:
        return GTK_MESSAGE_QUESTION;
      case MESSAGE_BOX_TYPE_ERROR:
        return GTK_MESSAGE_ERROR;
      default:
        return GTK_MESSAGE_OTHER;
    }
  }

  const char* TranslateToStock(int id, const std::string& text) {
    std::string lower = base::StringToLowerASCII(text);
    if (lower == "cancel") {
      cancel_id_ = id;
      return GTK_STOCK_CANCEL;
    } else if (lower == "no") {
      cancel_id_ = id;
      return GTK_STOCK_NO;
    } else if (lower == "ok") {
      return GTK_STOCK_OK;
    } else if (lower == "yes") {
      return GTK_STOCK_YES;
    } else {
      return text.c_str();
    }
  }

  void Show() {
    gtk_widget_show_all(dialog_);
    // We need to call gtk_window_present after making the widgets visible to
    // make sure window gets correctly raised and gets focus.
    int time = views::X11DesktopHandler::get()->wm_user_time_ms();
    gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
  }

  int RunSynchronous() {
    gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
    Show();
    int response = gtk_dialog_run(GTK_DIALOG(dialog_));
    if (response < 0)
      return cancel_id_;
    else
      return response;
  }

  void RunAsynchronous(const MessageBoxCallback& callback) {
    callback_ = callback;
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), nullptr);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnResponseDialogThunk), this);
    Show();
  }

  CHROMEGTK_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, int);

 private:
  atom::NativeWindow::DialogScope dialog_scope_;

  // The id to return when the dialog is closed without pressing buttons.
  int cancel_id_;

  GtkWidget* dialog_;
  MessageBoxCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(GtkMessageBox);
};

void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) {
  gtk_widget_hide_all(dialog_);

  if (response < 0)
    callback_.Run(cancel_id_);
  else
    callback_.Run(response);
  delete this;
}

}  // namespace

int ShowMessageBox(NativeWindow* parent,
                   MessageBoxType type,
                   const std::vector<std::string>& buttons,
                   const std::string& title,
                   const std::string& message,
                   const std::string& detail,
                   const gfx::ImageSkia& icon) {
  return GtkMessageBox(parent, type, buttons, title, message, detail,
                       icon).RunSynchronous();
}

void ShowMessageBox(NativeWindow* parent,
                    MessageBoxType type,
                    const std::vector<std::string>& buttons,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const gfx::ImageSkia& icon,
                    const MessageBoxCallback& callback) {
  (new GtkMessageBox(parent, type, buttons, title, message, detail,
                     icon))->RunAsynchronous(callback);
}

void ShowErrorBox(const base::string16& title, const base::string16& content) {
  if (Browser::Get()->is_ready()) {
    GtkMessageBox(nullptr, MESSAGE_BOX_TYPE_ERROR, { "OK" }, "Error",
                  base::UTF16ToUTF8(title).c_str(),
                  base::UTF16ToUTF8(content).c_str(),
                  gfx::ImageSkia()).RunSynchronous();
  } else {
    fprintf(stderr,
            ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY
            ANSI_FOREGROUND_RED  "%s\n"
            ANSI_FOREGROUND_BLACK "%s"
            ANSI_RESET "\n",
            base::UTF16ToUTF8(title).c_str(),
            base::UTF16ToUTF8(content).c_str());
  }
}

}  // namespace atom
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_automation.hxx"

#ifndef _SBXCLASS_HXX //autogen
#include <basic/sbx.hxx>
#endif

#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif
#include <basic/testtool.hxx>
#include "testbasi.hxx"
//#include "app.hxx"
//#include "basic.hrc"
//#include "appbased.hxx"
#define P_FEHLERLISTE ((TestToolObj*)pTestObject)->GetFehlerListe()

//#include "status.hxx"
//#include "basic.hrc"

//#include "object.hxx"

#include <testapp.hxx>
#include <testtool.hxx>
#ifndef _SB_INTERN_HXX
//#include "sbintern.hxx"
#endif

//#include "comm_bas.hxx"
//#include "processw.hxx"

TYPEINIT1(TTBasic,MyBasic)

/*class MyFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
};

static SampleObjectFac aFac1;
static MyFactory aFac2;
static CommunicationFactory aComManFac;
static ProcessFactory aProcessFac;
static short nInst = 0;

SbxBase* MyFactory::Create( UINT16 nSbxId, UINT32 nCr )
{
    if( nCr == SBXCR_TEST && nSbxId == SBXID_MYBASIC )
        return new MyBasic;
    else
        return NULL;
} */

TTBasic::TTBasic() : MyBasic()
{
// Eigenes Objekt reinbraten
    TestToolObj* pTTO = new TestToolObj( CUniString("App"), this );
    pTTO->SetLogHdl( GenLogHdl() );
    pTTO->SetWinInfoHdl( GenWinInfoHdl() );
    pTTO->SetModuleWinExistsHdl( GenModuleWinExistsHdl() );
    pTTO->SetWriteStringHdl( GenWriteStringHdl() );
    pTTO->SetCErrorHdl( LINK( this, TTBasic, CErrorImpl ) );

    StartListeningTT( pTTO->GetTTBroadcaster() );

    pTestObject = pTTO;
    pTestObject->SetFlag( SBX_EXTSEARCH );
    Insert( pTestObject );
}

MyBasic* TTBasic::CreateMyBasic()
{
    return new TTBasic();
}

void TTBasic::LoadIniFile()
{
    ((TestToolObj*)pTestObject)->LoadIniFile();
}

SbTextType TTBasic::GetSymbolType( const String &rSymbol, BOOL bWasTTControl )
{
    return ((TestToolObj*)pTestObject)->GetSymbolType( rSymbol, bWasTTControl );
}

TTBasic::~TTBasic()
{
}

IMPL_LINK( TTBasic, CErrorImpl, ErrorEntry*, pData )
{
    return CError( pData->nError, pData->aText, pData->nLine, pData->nCol1, pData->nCol2 );
}

BOOL TTBasic::Compile( SbModule* p )
{
    p->SetComment( ((TestToolObj*)pTestObject)->GetRevision(p->GetSource()) );
    SbModule* pOldModule = GetCompileModule();
    SetCompileModule( p );
    p->SetSource( ((TestToolObj*)pTestObject)->PreCompile(p->GetSource()) );
    SetCompileModule( pOldModule );
    if ( ((TestToolObj*)pTestObject)->WasPrecompilerError() )
        return FALSE;
    return MyBasic::Compile( p );
}

const String TTBasic::GetSpechialErrorText()
{
    String nErrorText;
    if ( pTestObject && IS_ERROR() && GetErrorCode() == GET_ERROR()->nError )
    {
        nErrorText = GenRealString( GET_ERROR()->aText );
        nErrorText.AppendAscii( ": " );
        nErrorText += String::CreateFromInt64( GET_ERROR()->nError );
    }
    else
    {
        nErrorText = GetErrorText();
    }
    return nErrorText;
}

void TTBasic::ReportRuntimeError( AppBasEd *pEditWin )
{
    SbxVariableRef aDummy = new SbxVariable;
    aDummy->SetUserData( 24 );  // ID_MaybeAddErr
    ((TestToolObj*)pTestObject)->SFX_NOTIFY( pTestObject->GetBroadcaster(), xx, SbxHint( SBX_HINT_DATAWANTED, aDummy ), xx );
    aDummy->SetUserData( 18 );  // ID_ExceptLog
    ((TestToolObj*)pTestObject)->SFX_NOTIFY( pTestObject->GetBroadcaster(), xx, SbxHint( SBX_HINT_DATAWANTED, aDummy ), xx );
    MyBasic::ReportRuntimeError( pEditWin );
}

void TTBasic::DebugFindNoErrors( BOOL bDebugFindNoErrors )
{
    ((TestToolObj*)pTestObject)->DebugFindNoErrors( bDebugFindNoErrors );
}
<commit_msg>INTEGRATION: CWS gh14 (1.7.46); FILE MERGED 2007/05/25 11:33:38 gh 1.7.46.1: #i76946# parent not set anymore -> crash<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testbasi.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2007-06-19 14:35:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_automation.hxx"

#ifndef _SBXCLASS_HXX //autogen
#include <basic/sbx.hxx>
#endif

#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif
#include <basic/testtool.hxx>
#include "testbasi.hxx"
//#include "app.hxx"
//#include "basic.hrc"
//#include "appbased.hxx"
#define P_FEHLERLISTE TestToolObj::pFehlerListe

//#include "status.hxx"
//#include "basic.hrc"

//#include "object.hxx"

#include <testapp.hxx>
#include <testtool.hxx>
#ifndef _SB_INTERN_HXX
//#include "sbintern.hxx"
#endif

//#include "comm_bas.hxx"
//#include "processw.hxx"

TYPEINIT1(TTBasic,MyBasic)

/*class MyFactory : public SbxFactory
{
public:
    virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
};

static SampleObjectFac aFac1;
static MyFactory aFac2;
static CommunicationFactory aComManFac;
static ProcessFactory aProcessFac;
static short nInst = 0;

SbxBase* MyFactory::Create( UINT16 nSbxId, UINT32 nCr )
{
    if( nCr == SBXCR_TEST && nSbxId == SBXID_MYBASIC )
        return new MyBasic;
    else
        return NULL;
} */

TTBasic::TTBasic() : MyBasic()
{
// Eigenes Objekt reinbraten
    TestToolObj* pTTO = new TestToolObj( CUniString("App"), this );
    pTTO->SetLogHdl( GenLogHdl() );
    pTTO->SetWinInfoHdl( GenWinInfoHdl() );
    pTTO->SetModuleWinExistsHdl( GenModuleWinExistsHdl() );
    pTTO->SetWriteStringHdl( GenWriteStringHdl() );
    pTTO->SetCErrorHdl( LINK( this, TTBasic, CErrorImpl ) );

    StartListeningTT( pTTO->GetTTBroadcaster() );

    pTestObject = pTTO;
    pTestObject->SetFlag( SBX_EXTSEARCH );
    Insert( pTestObject );
}

MyBasic* TTBasic::CreateMyBasic()
{
    return new TTBasic();
}

void TTBasic::LoadIniFile()
{
    ((TestToolObj*)pTestObject)->LoadIniFile();
}

SbTextType TTBasic::GetSymbolType( const String &rSymbol, BOOL bWasTTControl )
{
    return ((TestToolObj*)pTestObject)->GetSymbolType( rSymbol, bWasTTControl );
}

TTBasic::~TTBasic()
{
}

IMPL_LINK( TTBasic, CErrorImpl, ErrorEntry*, pData )
{
    return CError( pData->nError, pData->aText, pData->nLine, pData->nCol1, pData->nCol2 );
}

BOOL TTBasic::Compile( SbModule* p )
{
    p->SetComment( ((TestToolObj*)pTestObject)->GetRevision(p->GetSource()) );
    SbModule* pOldModule = GetCompileModule();
    SetCompileModule( p );
    p->SetSource( ((TestToolObj*)pTestObject)->PreCompile(p->GetSource()) );
    SetCompileModule( pOldModule );
    if ( ((TestToolObj*)pTestObject)->WasPrecompilerError() )
        return FALSE;
    return MyBasic::Compile( p );
}

const String TTBasic::GetSpechialErrorText()
{
    String nErrorText;
    if ( pTestObject && IS_ERROR() && GetErrorCode() == GET_ERROR()->nError )
    {
        nErrorText = GenRealString( GET_ERROR()->aText );
        nErrorText.AppendAscii( ": " );
        nErrorText += String::CreateFromInt64( GET_ERROR()->nError );
    }
    else
    {
        nErrorText = GetErrorText();
    }
    return nErrorText;
}

void TTBasic::ReportRuntimeError( AppBasEd *pEditWin )
{
    SbxVariableRef aDummy = new SbxVariable;
    aDummy->SetUserData( 24 );  // ID_MaybeAddErr
    ((TestToolObj*)pTestObject)->SFX_NOTIFY( pTestObject->GetBroadcaster(), xx, SbxHint( SBX_HINT_DATAWANTED, aDummy ), xx );
    aDummy->SetUserData( 18 );  // ID_ExceptLog
    ((TestToolObj*)pTestObject)->SFX_NOTIFY( pTestObject->GetBroadcaster(), xx, SbxHint( SBX_HINT_DATAWANTED, aDummy ), xx );
    MyBasic::ReportRuntimeError( pEditWin );
}

void TTBasic::DebugFindNoErrors( BOOL bDebugFindNoErrors )
{
    ((TestToolObj*)pTestObject)->DebugFindNoErrors( bDebugFindNoErrors );
}
<|endoftext|>


<commit_before>
#include "StdRegions/StdRegions.hpp"
#include "LibUtilities/Foundations/Foundations.hpp"
#include <StdRegions/StdExpUtil.h>
#include <StdRegions/StdPrismExp.h>

#include <algorithm>
#include <iostream>
#include <limits>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
using namespace Nektar;

NekDouble Prism_sol(NekDouble x, NekDouble y, NekDouble z, int order1, int order2, int order3,
                  LibUtilities::BasisType bType_x, LibUtilities::BasisType bType_y, LibUtilities::BasisType bType_z);

// modification to deal with exact solution. Return 1 if integer < 0
static double  pow_loc(const double val, const int i)
{
  return (i < 0)? 1.0: pow(val,i);
}

using namespace Nektar::LibUtilities;
using namespace Nektar::StdRegions;

int main(int argc, char *argv[]) {
    if( argc != 10 ) {
        cerr << "Usage: StdPrismExpDemo Type_x Type_y Type_z numModes_x numModes_y numModes_z Qx Qy Qz" << endl;
        cerr << "Where type is an interger value which dictates the basis as:" << endl;
        cerr << "\t Ortho_A    = 1\n";
        cerr << "\t Ortho_B    = 2\n";
        cerr << "\t Ortho_C    = 3\n";
        cerr << "\t Modified_A = 4\n";
        cerr << "\t Modified_B = 5\n";
        cerr << "\t Modified_C = 6\n";
        cerr << "\t Fourier    = 7\n";
        cerr << "\t Lagrange   = 8\n";
        cerr << "\t Legendre   = 9\n";
        cerr << "\t Chebyshev  = 10\n";
        cerr << "\t Nodal Tet (Electro) = 13    (3D Nodal Electrostatic Points on a Tetrahedron)\n";
        cerr << "\n\n" << "Example: " << argv[0] << " 1 1 2 3 3 3 5 5 5" << endl;
        cerr << endl;

        exit(1);
    }

    StdRegions::ShapeType regionShape = ePrism;

    int bType_x_val = atoi(argv[1]);
    int bType_y_val = atoi(argv[2]);
    int bType_z_val = atoi(argv[3]);

    LibUtilities::BasisType   bType_x = static_cast<LibUtilities::BasisType>( bType_x_val );
    LibUtilities::BasisType   bType_y = static_cast<LibUtilities::BasisType>( bType_y_val );
    LibUtilities::BasisType   bType_z = static_cast<LibUtilities::BasisType>( bType_z_val );
    LibUtilities::PointsType  NodalType = LibUtilities::eNoPointsType;

    if( (bType_x_val == 13) || (bType_y_val == 13) || (bType_z_val == 13) )
    {
        bType_x =   LibUtilities::eOrtho_A;
        bType_y =   LibUtilities::eOrtho_B;
        bType_z =   LibUtilities::eOrtho_C;

        NodalType = LibUtilities::eNodalTetElec;
    }

    // Check to see that correct Expansions are used
    if( regionShape == StdRegions::ePrism )
    {
        if( (bType_x == LibUtilities::eOrtho_B) || (bType_x == LibUtilities::eModified_B) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 1 cannot be of type Ortho_B or Modified_B");
        }
        if( (bType_x == LibUtilities::eOrtho_C) || (bType_x == LibUtilities::eModified_C) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 1 cannot be of type Ortho_C or Modified_C");
        }
        if( (bType_y == LibUtilities::eOrtho_C) || (bType_y == LibUtilities::eModified_C) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 2 cannot be of type Ortho_C or Modified_C");
        }
    }

    int xModes   = atoi(argv[4]);
    int yModes   = atoi(argv[5]);
    int zModes   = atoi(argv[6]);
    int Qx = atoi(argv[7]);
    int Qy = atoi(argv[8]);
    int Qz = atoi(argv[9]);
    int P = xModes - 1, Q = yModes - 1, R = zModes - 1;

    Array<OneD, NekDouble> solution( Qx * Qy * Qz );
    Array<OneD, NekDouble> diff_solution( Qx * Qy * Qz );

    LibUtilities::PointsType    Qtype_x, Qtype_y, Qtype_z;
    Array<OneD,NekDouble> x = Array<OneD,NekDouble>( Qx * Qy * Qz );
    Array<OneD,NekDouble> y = Array<OneD,NekDouble>( Qx * Qy * Qz );
    Array<OneD,NekDouble> z = Array<OneD,NekDouble>( Qx * Qy * Qz );

  if(bType_x != LibUtilities::eFourier)
  {
      Qtype_x = LibUtilities::eGaussLobattoLegendre;
  }
  else
  {
      Qtype_x = LibUtilities::eFourierEvenlySpaced;
  }

  if(bType_y != LibUtilities::eFourier)
  {
      Qtype_y = LibUtilities::eGaussLobattoLegendre;
  }
  else
  {
      Qtype_y = LibUtilities::eFourierEvenlySpaced;
  }

  if(bType_z != LibUtilities::eFourier)
  {
      Qtype_z = LibUtilities::eGaussRadauMAlpha1Beta0;
  }
  else
  {
      Qtype_z = LibUtilities::eFourierEvenlySpaced;
  }

    //-----------------------------------------------
    // Define a 3D expansion based on basis definition

    StdRegions::StdExpansion3D *spe;

    if( regionShape == StdRegions::ePrism )
    {
        const LibUtilities::PointsKey   pointsKey_x( Qx, Qtype_x );
        const LibUtilities::PointsKey   pointsKey_y( Qy, Qtype_y );
        const LibUtilities::PointsKey   pointsKey_z( Qz, Qtype_z );

        const LibUtilities::BasisKey    basisKey_x( bType_x, xModes, pointsKey_x );
        const LibUtilities::BasisKey    basisKey_y( bType_y, yModes, pointsKey_y );
        const LibUtilities::BasisKey    basisKey_z( bType_z, zModes, pointsKey_z );

        if( bType_x_val < 10 ) {
            spe = new StdRegions::StdPrismExp( basisKey_x, basisKey_y, basisKey_z );
        } else {
            cerr << "Implement the next line!!!!!!" << endl;
            //spe = new StdRegions::StdNodalTetExp( basisKey_x, basisKey_y, basisKey_z, NodalType );
            exit(1);
        }

        spe->GetCoords(x,y,z);

        //----------------------------------------------
        // Define solution to be projected
        for(int n = 0; n < Qx * Qy * Qz; ++n) {
            solution[n]  = Prism_sol( x[n], y[n], z[n], P, Q, R, bType_x, bType_y, bType_z );
            //cout << "Prism_solution["<<n<<"] = " << solution[n] << ",  x = " << x[n] << ", y = " << y[n] << ", z = " << z[n] << endl;

        }
        //----------------------------------------------

    }

    //---------------------------------------------
    // Project onto Expansion
   spe->FwdTrans( solution, spe->UpdateCoeffs() );
    //---------------------------------------------

    //-------------------------------------------
    // Backward Transform Solution to get projected values
   spe->BwdTrans( spe->GetCoeffs(), spe->UpdatePhys() );
    //-------------------------------------------

    //--------------------------------------------
    // Calculate L_p error
   cout << "\n*****************************************************\n " << endl;
   cout << "L infinity error: " << spe->Linf(solution) << endl;
   cout << "L 2 error:        " << spe->L2  (solution) << endl;
   cout << "\n*****************************************************\n " << endl;
    //--------------------------------------------

    //-------------------------------------------
    // Evaulate solution at x = y = z = 0  and print error
    Array<OneD, NekDouble> t = Array<OneD, NekDouble>(3);

     t[0] = -0.39;
     t[1] = -0.25;
     t[2] = 0.5;

    if( regionShape == StdRegions::ePrism ) {
        solution[0] = Prism_sol( t[0], t[1], t[2], P, Q, R, bType_x, bType_y, bType_z );
    }

    NekDouble numericSolution = spe->PhysEvaluate(t);
    cout << "\n*****************************************************\n " << endl;
    cout << "Interpolation difference from actual solution at x = ( " <<
        t[0] << ", " << t[1] << ", " << t[2] << " ): " << numericSolution - solution[0] << endl;
    //-------------------------------------------
    cout << "numericSolution = " << numericSolution << endl;
    cout << "exact solution = " << solution[0] << endl;
    cout << "\n*****************************************************\n " << endl;

     // Testing the physical evaluate(u_phys): projection on to the polynomial space given by the prismatic basis function
    // The result of output should converge to the interpolation solution
    ConstArray<OneD, NekDouble> const& u_phys = spe->GetPhys();
    Array<OneD, NekDouble> prism_solution( Qx * Qy * Qz, 0.0 );
    cout << setprecision(4);
    for(int n = 0; n < Qx * Qy * Qz; ++n) {
        prism_solution[n]  = Prism_sol( x[n], y[n], z[n], P, Q, R, bType_x, bType_y, bType_z );
/*        cout << "prism_solution[" << setw(2)<<n<<"] = " << setw(8) << prism_solution[n] << ",  u_phys["<< setw(2) << n<<"] = " << setw(8) << u_phys[n]  <<
            ",               x = " << setw(8) << x[n] << ", y = " << setw(8) << y[n] << ", z = " << setw(8) << z[n] << endl;*/

        //cout << "         u_p["<<n<<"] = " <<      u_p[n] << endl;
    }
    cout << setprecision(9);

    return 0;
}

NekDouble Prism_sol(NekDouble x, NekDouble y, NekDouble z, int P, int Q, int R, LibUtilities::BasisType bType_x,
                  LibUtilities::BasisType bType_y, LibUtilities::BasisType bType_z ) {
    NekDouble sol = 0;

    // case 1 -- Common case
    if( (bType_x != LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier)  )
    {
        for(int p = 0; p <= P; ++p) {
            for(int q = 0; q <= Q; ++q) {
                for(int r = 0; r <= R - p; ++r) {
                    sol += pow(x,p) * pow(y,q) * pow(z,r);
                }
            }
        }
    } else  // case 2
    if((bType_x != LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z == LibUtilities::eFourier))
    {
        for(int i = 0; i <= P; ++i) {
            for(int j = 0; j <= Q; ++j) {
                for(int k = 0; k <= R/2; ++k) {
                    sol += pow(x,i) * pow(y,j) * sin(M_PI*k*z) + pow(x,i) * pow(y,j) * cos(M_PI*k*z);
                }
            }
        }
    }else // case 3
    if((bType_x == LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier))
    {
        for(int i = 0; i <= P/2; ++i) {
            for(int j = 0; j <= Q; ++j) {
                for(int k = 0; k <= R - i; ++k) {
                    sol += sin(M_PI*i*x)* pow(y,j) * pow(z,k) + cos(M_PI*i*x)* pow(y,j) * pow(z,k);
                }
            }
        }
    }
    else // case 4
    if((bType_x != LibUtilities::eFourier) && (bType_y == LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier))
    {
        for(int i = 0; i <= P; ++i) {
            for(int j = 0; j <= Q/2; ++j) {
                for(int k = 0; k <= R - i; ++k) {
                    sol += pow(x,i)*sin(M_PI*j*y)*pow(z,k) + pow(x,i)*cos(M_PI*j*y)*pow(z,k);
                }
            }
        }
    }

    return sol;
}<commit_msg>*** empty log message ***<commit_after>
#include "StdRegions/StdRegions.hpp"
#include "LibUtilities/Foundations/Foundations.hpp"
#include <StdRegions/StdExpUtil.h>
#include <StdRegions/StdPrismExp.h>

#include <algorithm>
#include <iostream>
#include <limits>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
using namespace Nektar;

NekDouble Prism_sol(NekDouble x, NekDouble y, NekDouble z, int order1, int order2, int order3,
                  LibUtilities::BasisType bType_x, LibUtilities::BasisType bType_y, LibUtilities::BasisType bType_z);

// modification to deal with exact solution. Return 1 if integer < 0
static double  pow_loc(const double val, const int i)
{
  return (i < 0)? 1.0: pow(val,i);
}

using namespace Nektar::LibUtilities;
using namespace Nektar::StdRegions;

int main(int argc, char *argv[]) {
    if( argc != 10 ) {
        cerr << "Usage: StdPrismExpDemo Type_x Type_y Type_z numModes_x numModes_y numModes_z Qx Qy Qz" << endl;
        cerr << "Where type is an interger value which dictates the basis as:" << endl;
        cerr << "\t Ortho_A    = 1\n";
        cerr << "\t Ortho_B    = 2\n";
        cerr << "\t Ortho_C    = 3\n";
        cerr << "\t Modified_A = 4\n";
        cerr << "\t Modified_B = 5\n";
        cerr << "\t Modified_C = 6\n";
        cerr << "\t Fourier    = 7\n";
        cerr << "\t Lagrange   = 8\n";
        cerr << "\t Legendre   = 9\n";
        cerr << "\t Chebyshev  = 10\n";
        cerr << "\t Nodal Tet (Electro) = 13    (3D Nodal Electrostatic Points on a Tetrahedron)\n";
        cerr << "\n\n" << "Example: " << argv[0] << " 1 1 2 3 3 3 5 5 5" << endl;
        cerr << endl;

        exit(1);
    }

    StdRegions::ShapeType regionShape = ePrism;

    int bType_x_val = atoi(argv[1]);
    int bType_y_val = atoi(argv[2]);
    int bType_z_val = atoi(argv[3]);

    LibUtilities::BasisType   bType_x = static_cast<LibUtilities::BasisType>( bType_x_val );
    LibUtilities::BasisType   bType_y = static_cast<LibUtilities::BasisType>( bType_y_val );
    LibUtilities::BasisType   bType_z = static_cast<LibUtilities::BasisType>( bType_z_val );
    LibUtilities::PointsType  NodalType = LibUtilities::eNoPointsType;

    if( (bType_x_val == 13) || (bType_y_val == 13) || (bType_z_val == 13) )
    {
        bType_x =   LibUtilities::eOrtho_A;
        bType_y =   LibUtilities::eOrtho_B;
        bType_z =   LibUtilities::eOrtho_C;

        NodalType = LibUtilities::eNodalTetElec;
    }

    // Check to see that correct Expansions are used
    if( regionShape == StdRegions::ePrism )
    {
        if( (bType_x == LibUtilities::eOrtho_B) || (bType_x == LibUtilities::eModified_B) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 1 cannot be of type Ortho_B or Modified_B");
        }
        if( (bType_x == LibUtilities::eOrtho_C) || (bType_x == LibUtilities::eModified_C) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 1 cannot be of type Ortho_C or Modified_C");
        }
        if( (bType_y == LibUtilities::eOrtho_C) || (bType_y == LibUtilities::eModified_C) ) {
            NEKERROR(ErrorUtil::efatal, "Basis 2 cannot be of type Ortho_C or Modified_C");
        }
    }

    int xModes   = atoi(argv[4]);
    int yModes   = atoi(argv[5]);
    int zModes   = atoi(argv[6]);
    int Qx = atoi(argv[7]);
    int Qy = atoi(argv[8]);
    int Qz = atoi(argv[9]);
    int P = xModes - 1, Q = yModes - 1, R = zModes - 1;

    Array<OneD, NekDouble> solution( Qx * Qy * Qz );
    Array<OneD, NekDouble> diff_solution( Qx * Qy * Qz );

    LibUtilities::PointsType    Qtype_x, Qtype_y, Qtype_z;
    Array<OneD,NekDouble> x = Array<OneD,NekDouble>( Qx * Qy * Qz );
    Array<OneD,NekDouble> y = Array<OneD,NekDouble>( Qx * Qy * Qz );
    Array<OneD,NekDouble> z = Array<OneD,NekDouble>( Qx * Qy * Qz );

  if(bType_x != LibUtilities::eFourier)
  {
      Qtype_x = LibUtilities::eGaussLobattoLegendre;
  }
  else
  {
      Qtype_x = LibUtilities::eFourierEvenlySpaced;
  }

  if(bType_y != LibUtilities::eFourier)
  {
      Qtype_y = LibUtilities::eGaussLobattoLegendre;
  }
  else
  {
      Qtype_y = LibUtilities::eFourierEvenlySpaced;
  }

  if(bType_z != LibUtilities::eFourier)
  {
      Qtype_z = LibUtilities::eGaussRadauMAlpha1Beta0;
  }
  else
  {
      Qtype_z = LibUtilities::eFourierEvenlySpaced;
  }

    //-----------------------------------------------
    // Define a 3D expansion based on basis definition

    StdRegions::StdExpansion3D *spe;

    if( regionShape == StdRegions::ePrism )
    {
        const LibUtilities::PointsKey   pointsKey_x( Qx, Qtype_x );
        const LibUtilities::PointsKey   pointsKey_y( Qy, Qtype_y );
        const LibUtilities::PointsKey   pointsKey_z( Qz, Qtype_z );

        const LibUtilities::BasisKey    basisKey_x( bType_x, xModes, pointsKey_x );
        const LibUtilities::BasisKey    basisKey_y( bType_y, yModes, pointsKey_y );
        const LibUtilities::BasisKey    basisKey_z( bType_z, zModes, pointsKey_z );

        if( bType_x_val < 10 ) {
            spe = new StdRegions::StdPrismExp( basisKey_x, basisKey_y, basisKey_z );
        } else {
            cerr << "Implement the next line!!!!!!" << endl;
            //spe = new StdRegions::StdNodalTetExp( basisKey_x, basisKey_y, basisKey_z, NodalType );
            exit(1);
        }

        spe->GetCoords(x,y,z);

        //----------------------------------------------
        // Define solution to be projected
        for(int n = 0; n < Qx * Qy * Qz; ++n) {
            solution[n]  = Prism_sol( x[n], y[n], z[n], P, Q, R, bType_x, bType_y, bType_z );
            //cout << "Prism_solution["<<n<<"] = " << solution[n] << ",  x = " << x[n] << ", y = " << y[n] << ", z = " << z[n] << endl;

        }
        //----------------------------------------------

    }

    //---------------------------------------------
    // Project onto Expansion
   spe->FwdTrans( solution, spe->UpdateCoeffs() );
    //---------------------------------------------

    //-------------------------------------------
    // Backward Transform Solution to get projected values
   spe->BwdTrans( spe->GetCoeffs(), spe->UpdatePhys() );
    //-------------------------------------------

    //--------------------------------------------
    // Calculate L_p error
   cout << "\n*****************************************************\n " << endl;
   cout << "L infinity error: " << spe->Linf(solution) << endl;
   cout << "L 2 error:        " << spe->L2  (solution) << endl;
   cout << "\n*****************************************************\n " << endl;
    //--------------------------------------------

    //-------------------------------------------
    // Evaulate solution at x = y = z = 0  and print error
    Array<OneD, NekDouble> t = Array<OneD, NekDouble>(3);

     t[0] = -0.39;
     t[1] = -0.25;
     t[2] = 0.5;

    if( regionShape == StdRegions::ePrism ) {
        solution[0] = Prism_sol( t[0], t[1], t[2], P, Q, R, bType_x, bType_y, bType_z );
    }

    NekDouble numericSolution = spe->PhysEvaluate(t);
    cout << "\n*****************************************************\n " << endl;
    cout << "Interpolation difference from actual solution at x = ( " <<
        t[0] << ", " << t[1] << ", " << t[2] << " ): " << numericSolution - solution[0] << endl;
    //-------------------------------------------
    cout << "numericSolution = " << numericSolution << endl;
    cout << "exact solution = " << solution[0] << endl;
    cout << "\n*****************************************************\n " << endl;

     // Testing the physical evaluate(u_phys): projection on to the polynomial space given by the prismatic basis function
    // The result of output should converge to the interpolation solution
    ConstArray<OneD, NekDouble> const& u_phys = spe->GetPhys();
    Array<OneD, NekDouble> prism_solution( Qx * Qy * Qz, 0.0 );
    cout << setprecision(4);
    for(int n = 0; n < Qx * Qy * Qz; ++n) {
        prism_solution[n]  = Prism_sol( x[n], y[n], z[n], P, Q, R, bType_x, bType_y, bType_z );
/*        cout << "prism_solution[" << setw(2)<<n<<"] = " << setw(8) << prism_solution[n] << ",  u_phys["<< setw(2) << n<<"] = " << setw(8) << u_phys[n]  <<
            ",               x = " << setw(8) << x[n] << ", y = " << setw(8) << y[n] << ", z = " << setw(8) << z[n] << endl;*/

        //cout << "         u_p["<<n<<"] = " <<      u_p[n] << endl;
    }
    cout << setprecision(9);

    return 0;
}

NekDouble Prism_sol(NekDouble x, NekDouble y, NekDouble z, int P, int Q, int R, LibUtilities::BasisType bType_x,
                  LibUtilities::BasisType bType_y, LibUtilities::BasisType bType_z ) {
    NekDouble sol = 0;

    // case 1 -- Common case
    if( (bType_x != LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier)  )
    {
        for(int p = 0; p <= P; ++p) {
            for(int q = 0; q <= Q; ++q) {
                for(int r = 0; r <= R - p; ++r) {
                    sol += pow(x,p) * pow(y,q) * pow(z,r);
                }
            }
        }
    } else  // case 2
    if((bType_x != LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z == LibUtilities::eFourier))
    {
        for(int i = 0; i <= P; ++i) {
            for(int j = 0; j <= Q; ++j) {
                for(int k = 0; k <= R/2; ++k) {
                    sol += pow(x,i) * pow(y,j) * sin(M_PI*k*z) + pow(x,i) * pow(y,j) * cos(M_PI*k*z);
                }
            }
        }
    }else // case 3
    if((bType_x == LibUtilities::eFourier) && (bType_y != LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier))
    {
        for(int i = 0; i <= P/2; ++i) {
            for(int j = 0; j <= Q; ++j) {
                for(int k = 0; k <= R - i; ++k) {
                    sol += sin(M_PI*i*x)* pow(y,j) * pow(z,k) + cos(M_PI*i*x)* pow(y,j) * pow(z,k);
                }
            }
        }
    }
    else // case 4
    if((bType_x != LibUtilities::eFourier) && (bType_y == LibUtilities::eFourier) && (bType_z != LibUtilities::eFourier))
    {
        for(int i = 0; i <= P; ++i) {
            for(int j = 0; j <= Q/2; ++j) {
                for(int k = 0; k <= R - i; ++k) {
                    sol += pow(x,i)*sin(M_PI*j*y)*pow(z,k) + pow(x,i)*cos(M_PI*j*y)*pow(z,k);
                }
            }
        }
    }

    return sol;
}
<|endoftext|>


<commit_before>/*
  TMP36.h - Library for reading the temperature of a TMP36.
  Created by Maurice (Mausy5043) Hendrix, FEB2015

  MIT license
*/

#include "TMP36.h"

TMP36::TMP36(int pin, int samples, float ref5v)
{
  _pin = pin;
  _samples = samples;
  _ref5v = ref5v;
}

void TMP36::begin()
{
  // set up the pin!
  pinMode(_pin, INPUT);
  _invsamples =  1/_samples;
  //_lastreadtime = 0;
}

float TMP36::readTemperature(void)
{
  int cntSamples = 0;
  int sumSamples = 0;
  float measurement = 0.0;

  // add up the pre-defined number of _samples for Sample Averaging
  for (cntSamples = 0; cntSamples < _samples; cntSamples++)
  {
    sumSamples += analogRead(_pin);
    // minimum delay on analog pins is 100ms
    delay(110);
  }
  // measurement = (float)sumSamples / (float)cntSamples; // Calculate avg raw value.
  measurement = (float)sumSamples * (float)_invsamples; // Calculate avg raw value.
  measurement = map(measurement * 10, 0, 10230, 0, _ref5v * 10000) * 0.0001;
  return 100 * measurement - 50.0;
}
<commit_msg>20150218.1009<commit_after>/*
  TMP36.h - Library for reading the temperature of a TMP36.
  Created by Maurice (Mausy5043) Hendrix, FEB2015

  MIT license
*/

#include "TMP36.h"

TMP36::TMP36(int pin, int samples, float ref5v)
{
  _pin = pin;
  _samples = samples;
  _ref5v = ref5v;
}

void TMP36::begin()
{
  // set up the pin!
  pinMode(_pin, INPUT);
  _invsamples =  1.0/(float)_samples;
  //_lastreadtime = 0;
}

float TMP36::readTemperature(void)
{
  int cntSamples = 0;
  int sumSamples = 0;
  float measurement = 0.0;

  // add up the pre-defined number of _samples for Sample Averaging
  for (cntSamples = 0; cntSamples < _samples; cntSamples++)
  {
    sumSamples += analogRead(_pin);
    // minimum delay on analog pins is 100ms
    delay(110);
  }
  //measurement = (float)sumSamples / (float)cntSamples; // Calculate avg raw value.
  measurement = (float)sumSamples * _invsamples; // Calculate avg raw value.
  measurement = map(measurement * 10, 0, 10230, 0, _ref5v * 10000) * 0.0001;
  return 100 * measurement - 50.0;
}
<|endoftext|>


<commit_before><commit_msg>Fix traceline to compile on Windows.<commit_after><|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2008, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Willow Garage 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/StateManifold.h"
#include "ompl/base/ProjectionEvaluator.h"
#include "ompl/util/Exception.h"
#include "ompl/util/RandomNumbers.h"
#include <cmath>
#include <cstring>
#include <limits>

ompl::base::ProjectionMatrix::Matrix ompl::base::ProjectionMatrix::ComputeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)
{
    RNG rng;

    Matrix projection(to);
    for (unsigned int i = 0 ; i < to ; ++i)
    {
	projection[i].resize(from);
	for (unsigned int j = 0 ; j < from ; ++j)
	    projection[i][j] = rng.gaussian01();
    }

    for (unsigned int i = 1 ; i < to ; ++i)
    {
	std::valarray<double> &row = projection[i];
	for (unsigned int j = 0 ; j < i ; ++j)
	{
	    std::valarray<double> &prevRow = projection[j];
	    // subtract projection
	    row -= (row * prevRow).sum() * prevRow;
	}
	// normalize
	row /= sqrt((row * row).sum());
    }

    // if we need to apply scaling, do so
    if (scale.size() == from)
    {
	for (unsigned int i = 0 ; i < to ; ++i)
	    for (unsigned int j = 0 ; j < from ; ++j)
	    {
		if (fabs(scale[i]) < std::numeric_limits<double>::epsilon())
		    throw Exception("Scaling factor must be non-zero");
		projection[i][j] /= scale[i];
	    }
    }

    return projection;
}

void ompl::base::ProjectionMatrix::computeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)
{
    mat = ComputeRandom(from, to, scale);
}

void ompl::base::ProjectionMatrix::project(const double *from, double *to) const
{
    for (unsigned int i = 0 ; i < mat.size() ; ++i)
    {
	const std::valarray<double> &vec = mat[i];
	const unsigned int dim = vec.size();
	double *pos = to + i;
	*pos = 0.0;
	for (unsigned int j = 0 ; j < dim ; ++j)
	    *pos += from[j] * vec[j];
    }
}

void ompl::base::ProjectionMatrix::print(std::ostream &out) const
{
    for (unsigned int i = 0 ; i < mat.size() ; ++i)
    {
	const std::valarray<double> &vec = mat[i];
	const unsigned int dim = vec.size();
	for (unsigned int j = 0 ; j < dim ; ++j)
	    out << vec[j] << " ";
	out << std::endl;
    }
}

void ompl::base::ProjectionEvaluator::setCellDimensions(const std::vector<double> &cellDimensions)
{
    cellDimensions_ = cellDimensions;
    checkCellDimensions();
}

void ompl::base::ProjectionEvaluator::checkCellDimensions(void) const
{
    if (getDimension() <= 0)
	throw Exception("Dimension of projection needs to be larger than 0");
    if (cellDimensions_.size() != getDimension())
	throw Exception("Number of dimensions in projection space does not match number of cell dimensions");
}

void ompl::base::ProjectionEvaluator::inferCellDimensions(void)
{
    static const unsigned int TEST_STEPS = 100;
    unsigned int dim = getDimension();
    if (dim > 0)
    {
	ManifoldStateSamplerPtr sampler = manifold_->allocStateSampler();
	State *s = manifold_->allocState();
	EuclideanProjection proj(dim);

	std::vector<double> low(dim, std::numeric_limits<double>::infinity());
	std::vector<double> high(dim, -std::numeric_limits<double>::infinity());

	for (unsigned int i = 0 ; i < TEST_STEPS ; ++i)
	{
	    sampler->sampleUniform(s);
	    project(s, proj);
	    for (unsigned int j = 0 ; j < dim ; ++j)
	    {
		if (low[j] > proj.values[j])
		    low[j] = proj.values[j];
		if (high[j] < proj.values[j])
		    high[j] = proj.values[j];
	    }
	}

	manifold_->freeState(s);

	cellDimensions_.resize(dim);
	for (unsigned int j = 0 ; j < dim ; ++j)
	    cellDimensions_[j] = (high[j] - low[j]) / 10.0;
    }
}

void ompl::base::ProjectionEvaluator::setup(void)
{
    if (cellDimensions_.size() == 0 && getDimension() > 0)
	inferCellDimensions();
    checkCellDimensions();
}

void ompl::base::ProjectionEvaluator::computeCoordinates(const EuclideanProjection &projection, ProjectionCoordinates &coord) const
{
    unsigned int dim = getDimension();
    coord.resize(dim);
    for (unsigned int i = 0 ; i < dim ; ++i)
	coord[i] = (int)floor(projection.values[i]/cellDimensions_[i]);
}

void ompl::base::ProjectionEvaluator::printSettings(std::ostream &out) const
{
    out << "Projection of dimension " << getDimension() << std::endl;
    out << "Cell dimensions: [";
    for (unsigned int i = 0 ; i < cellDimensions_.size() ; ++i)
    {
	out << cellDimensions_[i];
	if (i + 1 < cellDimensions_.size())
	    out << ' ';
    }
    out << ']' << std::endl;
}

void ompl::base::ProjectionEvaluator::printProjection(const EuclideanProjection &projection, std::ostream &out) const
{
    unsigned int d = getDimension();
    if (d > 0)
    {
	--d;
	for (unsigned int i = 0 ; i < d ; ++i)
	    out << projection.values[i] << ' ';
	out << projection.values[d] << std::endl;
    }
    else
	out << "NULL" << std::endl;
}

void ompl::base::CompoundProjectionEvaluator::addProjectionEvaluator(const ProjectionEvaluatorPtr &proj)
{
    components_.push_back(proj);
    computeProjection();
}

void ompl::base::CompoundProjectionEvaluator::computeProjection(void)
{
    compoundDimension_ = 0;
    std::vector<double> scale;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
    {
	compoundDimension_ += components_[i]->getDimension();
	scale.insert(scale.end(), components_[i]->getCellDimensions().begin(), components_[i]->getCellDimensions().end());
    }

    if (compoundDimension_ > 2 && components_.size() > 1)
	dimension_ = std::max(2, (int)ceil(log((double)compoundDimension_)));
    else
	dimension_ = compoundDimension_;

    if (dimension_ < compoundDimension_)
	projection_.computeRandom(compoundDimension_, dimension_, scale);
    cellDimensions_.clear();
}

unsigned int ompl::base::CompoundProjectionEvaluator::getDimension(void) const
{
    return dimension_;
}

void ompl::base::CompoundProjectionEvaluator::project(const State *state, EuclideanProjection &projection) const
{
    // project all states to one big vector
    EuclideanProjection all(compoundDimension_);
    double *start = all.values;
    unsigned int p = 0;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
    {
	components_[i]->project(state->as<CompoundState>()->components[i], all);
	all.values += components_[i]->getDimension();
    }
    all.values = start;

    if (compoundDimension_ > dimension_)
	// project to lower dimension
	projection_.project(all.values, projection.values);
    else
	memcpy(projection.values, all.values, sizeof(double) * dimension_);
}

void ompl::base::CompoundProjectionEvaluator::printSettings(std::ostream &out) const
{
    out << "Compound projection [" << std::endl;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
	components_[i]->printSettings(out);
    out << "]" << std::endl;
    out << "  projected to " << dimension_ << " elements" << std::endl;
    if (compoundDimension_ > dimension_)
    {
	out << "  using a projection matrix:" << std::endl;
	projection_.print(out);
    }
    else
	out << "  (copy of contained projections)" << std::endl;
}
<commit_msg>one more warning for the projection evaluator<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2008, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Willow Garage 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/StateManifold.h"
#include "ompl/base/ProjectionEvaluator.h"
#include "ompl/util/Exception.h"
#include "ompl/util/RandomNumbers.h"
#include "ompl/util/Console.h"
#include <cmath>
#include <cstring>
#include <limits>

ompl::base::ProjectionMatrix::Matrix ompl::base::ProjectionMatrix::ComputeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)
{
    RNG rng;

    Matrix projection(to);
    for (unsigned int i = 0 ; i < to ; ++i)
    {
	projection[i].resize(from);
	for (unsigned int j = 0 ; j < from ; ++j)
	    projection[i][j] = rng.gaussian01();
    }

    for (unsigned int i = 1 ; i < to ; ++i)
    {
	std::valarray<double> &row = projection[i];
	for (unsigned int j = 0 ; j < i ; ++j)
	{
	    std::valarray<double> &prevRow = projection[j];
	    // subtract projection
	    row -= (row * prevRow).sum() * prevRow;
	}
	// normalize
	row /= sqrt((row * row).sum());
    }

    // if we need to apply scaling, do so
    if (scale.size() == from)
    {
	for (unsigned int i = 0 ; i < to ; ++i)
	    for (unsigned int j = 0 ; j < from ; ++j)
	    {
		if (fabs(scale[i]) < std::numeric_limits<double>::epsilon())
		    throw Exception("Scaling factor must be non-zero");
		projection[i][j] /= scale[i];
	    }
    }

    return projection;
}

void ompl::base::ProjectionMatrix::computeRandom(const unsigned int from, const unsigned int to, const std::vector<double> &scale)
{
    mat = ComputeRandom(from, to, scale);
}

void ompl::base::ProjectionMatrix::project(const double *from, double *to) const
{
    for (unsigned int i = 0 ; i < mat.size() ; ++i)
    {
	const std::valarray<double> &vec = mat[i];
	const unsigned int dim = vec.size();
	double *pos = to + i;
	*pos = 0.0;
	for (unsigned int j = 0 ; j < dim ; ++j)
	    *pos += from[j] * vec[j];
    }
}

void ompl::base::ProjectionMatrix::print(std::ostream &out) const
{
    for (unsigned int i = 0 ; i < mat.size() ; ++i)
    {
	const std::valarray<double> &vec = mat[i];
	const unsigned int dim = vec.size();
	for (unsigned int j = 0 ; j < dim ; ++j)
	    out << vec[j] << " ";
	out << std::endl;
    }
}

void ompl::base::ProjectionEvaluator::setCellDimensions(const std::vector<double> &cellDimensions)
{
    cellDimensions_ = cellDimensions;
    checkCellDimensions();
}

void ompl::base::ProjectionEvaluator::checkCellDimensions(void) const
{
    if (getDimension() <= 0)
	throw Exception("Dimension of projection needs to be larger than 0");
    if (cellDimensions_.size() != getDimension())
	throw Exception("Number of dimensions in projection space does not match number of cell dimensions");
}

void ompl::base::ProjectionEvaluator::inferCellDimensions(void)
{
    static const unsigned int TEST_STEPS = 100;
    unsigned int dim = getDimension();
    if (dim > 0)
    {
	ManifoldStateSamplerPtr sampler = manifold_->allocStateSampler();
	State *s = manifold_->allocState();
	EuclideanProjection proj(dim);

	std::vector<double> low(dim, std::numeric_limits<double>::infinity());
	std::vector<double> high(dim, -std::numeric_limits<double>::infinity());

	for (unsigned int i = 0 ; i < TEST_STEPS ; ++i)
	{
	    sampler->sampleUniform(s);
	    project(s, proj);
	    for (unsigned int j = 0 ; j < dim ; ++j)
	    {
		if (low[j] > proj.values[j])
		    low[j] = proj.values[j];
		if (high[j] < proj.values[j])
		    high[j] = proj.values[j];
	    }
	}

	manifold_->freeState(s);

	cellDimensions_.resize(dim);
	for (unsigned int j = 0 ; j < dim ; ++j)
        {
            cellDimensions_[j] = (high[j] - low[j]) / 10.0;
            if (cellDimensions_[j] < std::numeric_limits<double>::epsilon())
            {
                cellDimensions_[j] = 1.0;
                msg::Interface msg;
                msg.warn("Inferred cell size for dimension %u of a projection for manifold %s is 0. Setting arbitrary value of 1 instead.",
                         j, manifold_->getName().c_str());
            }
        }
    }
}

void ompl::base::ProjectionEvaluator::setup(void)
{
    if (cellDimensions_.size() == 0 && getDimension() > 0)
	inferCellDimensions();
    checkCellDimensions();
}

void ompl::base::ProjectionEvaluator::computeCoordinates(const EuclideanProjection &projection, ProjectionCoordinates &coord) const
{
    unsigned int dim = getDimension();
    coord.resize(dim);
    for (unsigned int i = 0 ; i < dim ; ++i)
	coord[i] = (int)floor(projection.values[i]/cellDimensions_[i]);
}

void ompl::base::ProjectionEvaluator::printSettings(std::ostream &out) const
{
    out << "Projection of dimension " << getDimension() << std::endl;
    out << "Cell dimensions: [";
    for (unsigned int i = 0 ; i < cellDimensions_.size() ; ++i)
    {
	out << cellDimensions_[i];
	if (i + 1 < cellDimensions_.size())
	    out << ' ';
    }
    out << ']' << std::endl;
}

void ompl::base::ProjectionEvaluator::printProjection(const EuclideanProjection &projection, std::ostream &out) const
{
    unsigned int d = getDimension();
    if (d > 0)
    {
	--d;
	for (unsigned int i = 0 ; i < d ; ++i)
	    out << projection.values[i] << ' ';
	out << projection.values[d] << std::endl;
    }
    else
	out << "NULL" << std::endl;
}

void ompl::base::CompoundProjectionEvaluator::addProjectionEvaluator(const ProjectionEvaluatorPtr &proj)
{
    components_.push_back(proj);
    computeProjection();
}

void ompl::base::CompoundProjectionEvaluator::computeProjection(void)
{
    compoundDimension_ = 0;
    std::vector<double> scale;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
    {
	compoundDimension_ += components_[i]->getDimension();
	scale.insert(scale.end(), components_[i]->getCellDimensions().begin(), components_[i]->getCellDimensions().end());
    }

    if (compoundDimension_ > 2 && components_.size() > 1)
	dimension_ = std::max(2, (int)ceil(log((double)compoundDimension_)));
    else
	dimension_ = compoundDimension_;

    if (dimension_ < compoundDimension_)
	projection_.computeRandom(compoundDimension_, dimension_, scale);
    cellDimensions_.clear();
}

unsigned int ompl::base::CompoundProjectionEvaluator::getDimension(void) const
{
    return dimension_;
}

void ompl::base::CompoundProjectionEvaluator::project(const State *state, EuclideanProjection &projection) const
{
    // project all states to one big vector
    EuclideanProjection all(compoundDimension_);
    double *start = all.values;
    unsigned int p = 0;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
    {
	components_[i]->project(state->as<CompoundState>()->components[i], all);
	all.values += components_[i]->getDimension();
    }
    all.values = start;

    if (compoundDimension_ > dimension_)
	// project to lower dimension
	projection_.project(all.values, projection.values);
    else
	memcpy(projection.values, all.values, sizeof(double) * dimension_);
}

void ompl::base::CompoundProjectionEvaluator::printSettings(std::ostream &out) const
{
    out << "Compound projection [" << std::endl;
    for (unsigned int i = 0 ; i < components_.size() ; ++i)
	components_[i]->printSettings(out);
    out << "]" << std::endl;
    out << "  projected to " << dimension_ << " elements" << std::endl;
    if (compoundDimension_ > dimension_)
    {
	out << "  using a projection matrix:" << std::endl;
	projection_.print(out);
    }
    else
	out << "  (copy of contained projections)" << std::endl;
}
<|endoftext|>


<commit_before>///
/// @file  pi_deleglise_rivat_parallel3.cpp
/// @brief Parallel implementation of the Deleglise-Rivat prime
///        counting algorithm. This implementation is identical to
///        pi_deleglise_rivat_parallel2(x) but uses 128-bit integers.
///
///        This implementation is based on the paper:
///        Tomás Oliveira e Silva, Computing pi(x): the combinatorial
///        method, Revista do DETUA, vol. 4, no. 6, March 2006,
///        pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <int128.hpp>
#include <S1.hpp>
#include "S2.hpp"

#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

/// Calculate the contribution of the special leaves.
/// @pre y > 0 && c > 1
///
template <typename P, typename F>
int128_t S2(uint128_t x,
            int64_t y,
            int64_t z,
            int64_t c,
            vector<P>& primes,
            FactorTable<F>& factors,
            int threads)
{
  int128_t S2_total = 0;

  threads = validate_threads(threads, z);
  PiTable pi(y);

  S2_total += S2_trivial(x, y, z, c, pi, primes, threads);
  S2_total += S2_easy(x, y, z, c, pi, primes, threads);
  S2_total += S2_sieve(x, y, z, c, pi, primes, factors, threads);

  return S2_total;
}

/// alpha is a tuning factor which should grow like (log(x))^3
/// for the Deleglise-Rivat prime counting algorithm.
///
double compute_alpha(int128_t x)
{
  double d = (double) x;
  double alpha = log(d) * log(d) * log(d) / 1000;
  return in_between(1, alpha, iroot<6>(x));
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat_parallel3(int128_t x, int threads)
{
  if (x < 2)
    return 0;

  if (x > to_maxint(primecount::max()))
    throw primecount_error("pi(x): x must be <= " + max());

  double alpha = compute_alpha(x);
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = (int64_t) (x / y);
  int64_t pi_y;
  int64_t c;

  if (print_status())
  {
    cout << endl;
    cout << "=== pi_deleglise_rivat_parallel3(x) ===" << endl;
    cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << PhiTiny::max_a() << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }

  int128_t p2 = P2(x, y, threads);
  int128_t s1, s2;

  if (y <= FactorTable<uint16_t>::max())
  {
    // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable
    // which uses ~ (y / 2) bytes of memory

    vector<uint32_t> primes = generate_primes<uint32_t>(y);
    FactorTable<uint16_t> factors(y);

    pi_y = primes.size() - 1;
    c = min(pi_y, PhiTiny::max_a());
    s1 = S1(x, y, c, primes[c], factors, threads);
    s2 = S2(x, y, z, c, primes, factors, threads);
  }
  else
  {
    // if y >= 2^32 we need to use 64-bit primes and a 32-bit
    // FactorTable which uses ~ y bytes of memory

    vector<int64_t> primes = generate_primes<int64_t>(y);
    FactorTable<uint32_t> factors(y);

    pi_y = primes.size() - 1;
    c = min(pi_y, PhiTiny::max_a());
    s1 = S1(x, y, c, primes[c], factors, threads);
    s2 = S2(x, y, z, c, primes, factors, threads);
  }

  int128_t phi = s1 + s2;
  int128_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace
<commit_msg>Update pi_deleglise_rivat_parallel3.cpp<commit_after>///
/// @file  pi_deleglise_rivat_parallel3.cpp
/// @brief Parallel implementation of the Deleglise-Rivat prime
///        counting algorithm. This implementation is identical to
///        pi_deleglise_rivat_parallel2(x) but uses 128-bit integers.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <generate.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <int128.hpp>
#include <S1.hpp>
#include "S2.hpp"

#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

/// Calculate the contribution of the special leaves.
/// @pre y > 0 && c > 1
///
template <typename P, typename F>
int128_t S2(uint128_t x,
            int64_t y,
            int64_t z,
            int64_t c,
            vector<P>& primes,
            FactorTable<F>& factors,
            int threads)
{
  int128_t S2_total = 0;

  threads = validate_threads(threads, z);
  PiTable pi(y);

  S2_total += S2_trivial(x, y, z, c, pi, primes, threads);
  S2_total += S2_easy(x, y, z, c, pi, primes, threads);
  S2_total += S2_sieve(x, y, z, c, pi, primes, factors, threads);

  return S2_total;
}

/// alpha is a tuning factor which should grow like (log(x))^3
/// for the Deleglise-Rivat prime counting algorithm.
///
double compute_alpha(int128_t x)
{
  double d = (double) x;
  double alpha = log(d) * log(d) * log(d) / 1000;
  return in_between(1, alpha, iroot<6>(x));
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat_parallel3(int128_t x, int threads)
{
  if (x < 2)
    return 0;

  if (x > to_maxint(primecount::max()))
    throw primecount_error("pi(x): x must be <= " + max());

  double alpha = compute_alpha(x);
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = (int64_t) (x / y);
  int64_t pi_y;
  int64_t c;

  if (print_status())
  {
    cout << endl;
    cout << "=== pi_deleglise_rivat_parallel3(x) ===" << endl;
    cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << PhiTiny::max_a() << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }

  int128_t p2 = P2(x, y, threads);
  int128_t s1, s2;

  if (y <= FactorTable<uint16_t>::max())
  {
    // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable
    // which uses ~ (y / 2) bytes of memory

    vector<uint32_t> primes = generate_primes<uint32_t>(y);
    FactorTable<uint16_t> factors(y);

    pi_y = primes.size() - 1;
    c = min(pi_y, PhiTiny::max_a());
    s1 = S1(x, y, c, primes[c], factors, threads);
    s2 = S2(x, y, z, c, primes, factors, threads);
  }
  else
  {
    // if y >= 2^32 we need to use 64-bit primes and a 32-bit
    // FactorTable which uses ~ y bytes of memory

    vector<int64_t> primes = generate_primes<int64_t>(y);
    FactorTable<uint32_t> factors(y);

    pi_y = primes.size() - 1;
    c = min(pi_y, PhiTiny::max_a());
    s1 = S1(x, y, c, primes[c], factors, threads);
    s2 = S2(x, y, z, c, primes, factors, threads);
  }

  int128_t phi = s1 + s2;
  int128_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace
<|endoftext|>