<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * Copyright (c) 2007-2008 The Florida State University
 * 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 copyright holders 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.
 *
 * Authors: Ali Saidi
 *          Gabe Black
 */

#ifndef __ARM_FAULTS_HH__
#define __ARM_FAULTS_HH__

#include "arch/arm/miscregs.hh"
#include "arch/arm/types.hh"
#include "config/full_system.hh"
#include "sim/faults.hh"

// The design of the "name" and "vect" functions is in sim/faults.hh

namespace ArmISA
{
typedef const Addr FaultOffset;

class ArmFault : public FaultBase
{
  protected:
    Addr getVector(ThreadContext *tc);

  public:
    enum StatusEncoding
    {
        // Fault Status register encodings
        // ARM ARM B3.9.4
        AlignmentFault = 0x1,
        DebugEvent = 0x2,
        AccessFlag0 = 0x3,
        InstructionCacheMaintenance = 0x4,
        Translation0 = 0x5,
        AccessFlag1 = 0x6,
        Translation1 = 0x7,
        SynchronousExternalAbort0 = 0x8,
        Domain0 = 0x9,
        SynchronousExternalAbort1 = 0xa,
        Domain1 = 0xb,
        TranslationTableWalkExtAbt0 = 0xc,
        Permission0 = 0xd,
        TranslationTableWalkExtAbt1 = 0xe,
        Permission1 = 0xf,
        AsynchronousExternalAbort = 0x16,
        MemoryAccessAsynchronousParityError = 0x18,
        MemoryAccessSynchronousParityError = 0x19,
        TranslationTableWalkPrtyErr0 = 0x1c,
        TranslationTableWalkPrtyErr1 = 0x1e,
    };

    struct FaultVals
    {
        const FaultName name;
        const FaultOffset offset;
        const OperatingMode nextMode;
        const uint8_t armPcOffset;
        const uint8_t thumbPcOffset;
        const bool abortDisable;
        const bool fiqDisable;
        FaultStat count;
    };

#if FULL_SYSTEM
    void invoke(ThreadContext *tc);
#endif
    virtual FaultStat& countStat() = 0;
    virtual FaultOffset offset() = 0;
    virtual OperatingMode nextMode() = 0;
    virtual uint8_t armPcOffset() = 0;
    virtual uint8_t thumbPcOffset() = 0;
    virtual bool abortDisable() = 0;
    virtual bool fiqDisable() = 0;
};

template<typename T>
class ArmFaultVals : public ArmFault
{
  protected:
    static FaultVals vals;

  public:
    FaultName name() const { return vals.name; }
    FaultStat & countStat() {return vals.count;}
    FaultOffset offset() { return vals.offset; }
    OperatingMode nextMode() { return vals.nextMode; }
    uint8_t armPcOffset() { return vals.armPcOffset; }
    uint8_t thumbPcOffset() { return vals.thumbPcOffset; }
    bool abortDisable() { return vals.abortDisable; }
    bool fiqDisable() { return vals.fiqDisable; }
};

class Reset : public ArmFaultVals<Reset>
#if FULL_SYSTEM
{
  public:
    void invoke(ThreadContext *tc);
};
#else
{};
#endif //FULL_SYSTEM

class UndefinedInstruction : public ArmFaultVals<UndefinedInstruction>
{
#if !FULL_SYSTEM
  protected:
    ExtMachInst machInst;
    bool unknown;
    const char *mnemonic;

  public:
    UndefinedInstruction(ExtMachInst _machInst,
                         bool _unknown,
                         const char *_mnemonic = NULL) :
        machInst(_machInst), unknown(_unknown), mnemonic(_mnemonic)
    {
    }

    void invoke(ThreadContext *tc);
#endif
};

class SupervisorCall : public ArmFaultVals<SupervisorCall>
{
#if !FULL_SYSTEM
  protected:
    ExtMachInst machInst;

  public:
    SupervisorCall(ExtMachInst _machInst) : machInst(_machInst)
    {}

    void invoke(ThreadContext *tc);
#endif
};

template <class T>
class AbortFault : public ArmFaultVals<T>
{
  protected:
    Addr faultAddr;
    bool write;
    uint8_t domain;
    uint8_t status;

  public:
    AbortFault(Addr _faultAddr, bool _write,
            uint8_t _domain, uint8_t _status) :
        faultAddr(_faultAddr), write(_write),
        domain(_domain), status(_status)
    {}

    void invoke(ThreadContext *tc);
};

class PrefetchAbort : public AbortFault<PrefetchAbort>
{
  public:
    static const MiscRegIndex FsrIndex = MISCREG_IFSR;
    static const MiscRegIndex FarIndex = MISCREG_IFAR;

    PrefetchAbort(Addr _addr, uint8_t _status) :
        AbortFault<PrefetchAbort>(_addr, false, 0, _status)
    {}
};

class DataAbort : public AbortFault<DataAbort>
{
  public:
    static const MiscRegIndex FsrIndex = MISCREG_DFSR;
    static const MiscRegIndex FarIndex = MISCREG_DFAR;

    DataAbort(Addr _addr, uint8_t _domain, bool _write, uint8_t _status) :
        AbortFault<DataAbort>(_addr, _write, _domain, _status)
    {}
};

class Interrupt : public ArmFaultVals<Interrupt> {};
class FastInterrupt : public ArmFaultVals<FastInterrupt> {};

} // ArmISA namespace

#endif // __ARM_FAULTS_HH__
<commit_msg>ARM: DFSR status value for sync external data abort is expected to be 0x8 in ARMv7<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * Copyright (c) 2007-2008 The Florida State University
 * 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 copyright holders 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.
 *
 * Authors: Ali Saidi
 *          Gabe Black
 */

#ifndef __ARM_FAULTS_HH__
#define __ARM_FAULTS_HH__

#include "arch/arm/miscregs.hh"
#include "arch/arm/types.hh"
#include "config/full_system.hh"
#include "sim/faults.hh"

// The design of the "name" and "vect" functions is in sim/faults.hh

namespace ArmISA
{
typedef const Addr FaultOffset;

class ArmFault : public FaultBase
{
  protected:
    Addr getVector(ThreadContext *tc);

  public:
    enum StatusEncoding
    {
        // Fault Status register encodings
        // ARM ARM B3.9.4
        AlignmentFault = 0x1,
        DebugEvent = 0x2,
        AccessFlag0 = 0x3,
        InstructionCacheMaintenance = 0x4,
        Translation0 = 0x5,
        AccessFlag1 = 0x6,
        Translation1 = 0x7,
        SynchronousExternalAbort0 = 0x8,
        Domain0 = 0x9,
        SynchronousExternalAbort1 = 0x8,
        Domain1 = 0xb,
        TranslationTableWalkExtAbt0 = 0xc,
        Permission0 = 0xd,
        TranslationTableWalkExtAbt1 = 0xe,
        Permission1 = 0xf,
        AsynchronousExternalAbort = 0x16,
        MemoryAccessAsynchronousParityError = 0x18,
        MemoryAccessSynchronousParityError = 0x19,
        TranslationTableWalkPrtyErr0 = 0x1c,
        TranslationTableWalkPrtyErr1 = 0x1e,
    };

    struct FaultVals
    {
        const FaultName name;
        const FaultOffset offset;
        const OperatingMode nextMode;
        const uint8_t armPcOffset;
        const uint8_t thumbPcOffset;
        const bool abortDisable;
        const bool fiqDisable;
        FaultStat count;
    };

#if FULL_SYSTEM
    void invoke(ThreadContext *tc);
#endif
    virtual FaultStat& countStat() = 0;
    virtual FaultOffset offset() = 0;
    virtual OperatingMode nextMode() = 0;
    virtual uint8_t armPcOffset() = 0;
    virtual uint8_t thumbPcOffset() = 0;
    virtual bool abortDisable() = 0;
    virtual bool fiqDisable() = 0;
};

template<typename T>
class ArmFaultVals : public ArmFault
{
  protected:
    static FaultVals vals;

  public:
    FaultName name() const { return vals.name; }
    FaultStat & countStat() {return vals.count;}
    FaultOffset offset() { return vals.offset; }
    OperatingMode nextMode() { return vals.nextMode; }
    uint8_t armPcOffset() { return vals.armPcOffset; }
    uint8_t thumbPcOffset() { return vals.thumbPcOffset; }
    bool abortDisable() { return vals.abortDisable; }
    bool fiqDisable() { return vals.fiqDisable; }
};

class Reset : public ArmFaultVals<Reset>
#if FULL_SYSTEM
{
  public:
    void invoke(ThreadContext *tc);
};
#else
{};
#endif //FULL_SYSTEM

class UndefinedInstruction : public ArmFaultVals<UndefinedInstruction>
{
#if !FULL_SYSTEM
  protected:
    ExtMachInst machInst;
    bool unknown;
    const char *mnemonic;

  public:
    UndefinedInstruction(ExtMachInst _machInst,
                         bool _unknown,
                         const char *_mnemonic = NULL) :
        machInst(_machInst), unknown(_unknown), mnemonic(_mnemonic)
    {
    }

    void invoke(ThreadContext *tc);
#endif
};

class SupervisorCall : public ArmFaultVals<SupervisorCall>
{
#if !FULL_SYSTEM
  protected:
    ExtMachInst machInst;

  public:
    SupervisorCall(ExtMachInst _machInst) : machInst(_machInst)
    {}

    void invoke(ThreadContext *tc);
#endif
};

template <class T>
class AbortFault : public ArmFaultVals<T>
{
  protected:
    Addr faultAddr;
    bool write;
    uint8_t domain;
    uint8_t status;

  public:
    AbortFault(Addr _faultAddr, bool _write,
            uint8_t _domain, uint8_t _status) :
        faultAddr(_faultAddr), write(_write),
        domain(_domain), status(_status)
    {}

    void invoke(ThreadContext *tc);
};

class PrefetchAbort : public AbortFault<PrefetchAbort>
{
  public:
    static const MiscRegIndex FsrIndex = MISCREG_IFSR;
    static const MiscRegIndex FarIndex = MISCREG_IFAR;

    PrefetchAbort(Addr _addr, uint8_t _status) :
        AbortFault<PrefetchAbort>(_addr, false, 0, _status)
    {}
};

class DataAbort : public AbortFault<DataAbort>
{
  public:
    static const MiscRegIndex FsrIndex = MISCREG_DFSR;
    static const MiscRegIndex FarIndex = MISCREG_DFAR;

    DataAbort(Addr _addr, uint8_t _domain, bool _write, uint8_t _status) :
        AbortFault<DataAbort>(_addr, _write, _domain, _status)
    {}
};

class Interrupt : public ArmFaultVals<Interrupt> {};
class FastInterrupt : public ArmFaultVals<FastInterrupt> {};

} // ArmISA namespace

#endif // __ARM_FAULTS_HH__
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     Mai, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh 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.
*
*
* @brief    Example of reading BEM data
*
*/

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

#include <iostream>
#include <mne/mne.h>

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

#include <QtCore/QCoreApplication>
#include <QCommandLineParser>

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

using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Read BEM Example");
    parser.addHelpOption();
    QCommandLineOption sampleBEMFileOption("f", "Path to BEM <file>.", "file", "./MNE-sample-data/subjects/sample/bem/sample-head.fif");
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-all-src.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif"
    parser.addOption(sampleBEMFileOption);
    parser.process(app);

    //########################################################################################
    // Read the BEM
    QFile t_fileBem(parser.value(sampleBEMFileOption));
    MNEBem t_Bem(t_fileBem);

    if( t_Bem.size() > 0 )
    {
        qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(0,0) << t_Bem[0].tri_nn(0,1) << t_Bem[0].tri_nn(0,2);
        qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(2,0) << t_Bem[0].tri_nn(2,1) << t_Bem[0].tri_nn(2,2);
    }

    // Write the BEM
    QFile t_fileBemTest("./MNE-sample-data/subjects/sample/bem/sample-head-test.fif");
    t_Bem.write(t_fileBemTest);
    t_fileBemTest.close();

    MNEBem t_BemTest (t_fileBemTest) ;

    if( t_BemTest.size() > 0 )
    {
        qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(0,0) << t_BemTest[0].tri_nn(0,1) << t_BemTest[0].tri_nn(0,2);
        qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(2,0) << t_BemTest[0].tri_nn(2,1) << t_BemTest[0].tri_nn(2,2);
    }

    qDebug() << "Put your stuff your interest in here";

    return app.exec();
}
<commit_msg>[LIB-45] read Bem from Iso2Mesh in examples/readBEM/main.cpp<commit_after>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     Mai, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh 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.
*
*
* @brief    Example of reading BEM data
*
*/

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

#include <iostream>
#include <mne/mne.h>
#include <utils/ioutils.h>

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

#include <QtCore/QCoreApplication>
#include <QCommandLineParser>

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

using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Read BEM Example");
    parser.addHelpOption();
    QCommandLineOption sampleBEMFileOption("f", "Path to BEM <file>.", "file", "./MNE-sample-data/subjects/sample/bem/sample-head.fif");
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-all-src.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif"
//    "./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif"
    parser.addOption(sampleBEMFileOption);
    parser.process(app);

    //########################################################################################
    // Read the BEM
    QFile t_fileBem(parser.value(sampleBEMFileOption));
    MNEBem t_Bem(t_fileBem);

    if( t_Bem.size() > 0 )
    {
        qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(0,0) << t_Bem[0].tri_nn(0,1) << t_Bem[0].tri_nn(0,2);
        qDebug() << "t_Bem[0].tri_nn:" << t_Bem[0].tri_nn(2,0) << t_Bem[0].tri_nn(2,1) << t_Bem[0].tri_nn(2,2);
        qDebug() << "t_Bem[0].rr:" << t_Bem[0].rr(2,0) << t_Bem[0].rr(2,1) << t_Bem[0].rr(2,2);
    }

    //Read and write Iso2Mesh Bem
    QString folder = "C:/Users/Jana/Documents/MATLAB/AVG4-0Years_segmented_BEM3/";

    MatrixXd help;

    MNEBem t_BemIso2Mesh;
    MNEBemSurface  p_Brain;
    p_Brain.id = FIFFV_BEM_SURF_ID_BRAIN;
    QString path=folder;
    IOUtils::read_eigen_matrix(help, path.append("brain_vert.txt"));
    p_Brain.rr= help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help, path.append("brain_tri.txt"));
    p_Brain.tris = help.cast<int>();
    p_Brain.np = p_Brain.rr.rows();
    p_Brain.ntri = p_Brain.tris.rows();
    p_Brain.addTriangleData();
    p_Brain.addVertexNormals();
    t_BemIso2Mesh<<p_Brain;

    MNEBemSurface  p_Skull;
    p_Skull.id = FIFFV_BEM_SURF_ID_SKULL;
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("skull_vert.txt"));
    p_Skull.rr =  help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("skull_tri.txt"));
    p_Skull.tris =  help.cast<int>();
    p_Skull.np = p_Skull.rr.rows();
    p_Skull.ntri = p_Skull.tris.rows();
    p_Skull.addTriangleData();
    p_Skull.addVertexNormals();
    t_BemIso2Mesh<<p_Skull;

    MNEBemSurface  p_Head;
    p_Head.id = FIFFV_BEM_SURF_ID_HEAD;
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("head_vert.txt"));
    p_Head.rr =  help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("head_tri.txt"));
    p_Head.tris =  help.cast<int>();
    p_Head.np = p_Head.rr.rows();
    p_Head.ntri = p_Head.tris.rows();
    p_Head.addTriangleData();
    p_Head.addVertexNormals();
    t_BemIso2Mesh<<p_Head;

    QFile t_fileIso2MeshBem("./Iso2MeshBem/AVG4-0Years_segmented_BEM3.fiff");
    t_BemIso2Mesh.write(t_fileIso2MeshBem);
    t_fileIso2MeshBem.close();

    // Write the BEM
    QFile t_fileBemTest("./MNE-sample-data/subjects/sample/bem/sample-head-test.fif");
    t_Bem.write(t_fileBemTest);
    t_fileBemTest.close();

    MNEBem t_BemTest (t_fileBemTest) ;

    if( t_BemTest.size() > 0 )
    {
        qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(0,0) << t_BemTest[0].tri_nn(0,1) << t_BemTest[0].tri_nn(0,2);
        qDebug() << "t_BemTest[0].tri_nn:" << t_BemTest[0].tri_nn(2,0) << t_BemTest[0].tri_nn(2,1) << t_BemTest[0].tri_nn(2,2);
    }

    qDebug() << "Put your stuff your interest in here";

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


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__

#include "base/misc.hh"
#include "sim/faults.hh"

namespace X86ISA
{
    class X86Fault : public FaultBase
    {
      protected:
        const char * name()
        {
            return "generic_x86_fault";
        }

        void invoke(ThreadContext * tc)
        {
            panic("X86 faults are not implemented!");
        }
    };

    class UnimpInstFault : public FaultBase
    {
      public:
        const char * name()
        {
            return "unimplemented_micro";
        }

        void invoke(ThreadContext * tc)
        {
            panic("Unimplemented instruction!");
        }
    };

    static inline Fault genPageTableFault(Addr va)
    {
        panic("Page table fault not implemented in x86!\n");
    }

    static inline Fault genMachineCheckFault()
    {
        panic("Machine check fault not implemented in x86!\n");
    }

    static inline Fault genAlignmentFault()
    {
        panic("Alignment fault not implemented (or for the most part existant) in x86!\n");
    }
};

#endif // __ARCH_X86_FAULTS_HH__
<commit_msg>Make the "name" function const.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__

#include "base/misc.hh"
#include "sim/faults.hh"

namespace X86ISA
{
    class X86Fault : public FaultBase
    {
      protected:
        const char * name() const
        {
            return "generic_x86_fault";
        }

        void invoke(ThreadContext * tc)
        {
            panic("X86 faults are not implemented!");
        }
    };

    class UnimpInstFault : public FaultBase
    {
      public:
        const char * name() const
        {
            return "unimplemented_micro";
        }

        void invoke(ThreadContext * tc)
        {
            panic("Unimplemented instruction!");
        }
    };

    static inline Fault genPageTableFault(Addr va)
    {
        panic("Page table fault not implemented in x86!\n");
    }

    static inline Fault genMachineCheckFault()
    {
        panic("Machine check fault not implemented in x86!\n");
    }

    static inline Fault genAlignmentFault()
    {
        panic("Alignment fault not implemented (or for the most part existant) in x86!\n");
    }
};

#endif // __ARCH_X86_FAULTS_HH__
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2009-2012, 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 Willow Garage, Inc. 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.
 *
 */

#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

#include <pcl/io/pcd_io.h>
#include <pcl/pcl_macros.h>

#include <pcl/console/print.h>
#include <pcl/console/parse.h>

#include <pcl/outofcore/outofcore.h>
#include <pcl/outofcore/outofcore_impl.h>

// todo: Read clouds as PointCloud2 so we don't need to define PointT explicitly.
//       This also requires our octree to take PointCloud2 as an input.
typedef pcl::PointXYZRGBA PointT;

using namespace pcl;
using namespace pcl::outofcore;

using pcl::console::parse_argument;
using pcl::console::parse_file_extension_argument;
using pcl::console::find_switch;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;

#include <boost/foreach.hpp>

typedef octree_base<octree_disk_container<PointT> , PointT> octree_disk;

const int OCTREE_DEPTH (0);
const int OCTREE_RESOLUTION (1);

PointCloud<PointT>::Ptr
getCloudFromFile (boost::filesystem::path pcd_path)
{
  // Read PCD file
  PointCloud<PointT>::Ptr cloud (new PointCloud<PointT> ());

  print_info ("Reading: %s ", pcd_path.c_str ());

  if (io::loadPCDFile<PointT> (pcd_path.string (), *cloud) == -1) //* load the file
  {
    PCL_ERROR ("Couldn't read file\n");
    exit (-1);
  }

  print_info ("(%d)\n", (cloud->width * cloud->height));
  return cloud;
}

int
outofcoreProcess (std::vector<boost::filesystem::path> pcd_paths, boost::filesystem::path root_dir,
                  int depth, double resolution, int build_octree_with, bool gen_lod, bool overwrite)
{
  // Bounding box min/max pts
  PointT min_pt, max_pt;

  // Iterate over all pcd files resizing min/max
  for (size_t i = 0; i < pcd_paths.size (); i++)
  {

    // Get cloud
    PointCloud<PointT>::Ptr cloud = getCloudFromFile (pcd_paths[i]);

    PointT tmp_min_pt, tmp_max_pt;

    if (i == 0)
    {
      // Get initial min/max
      getMinMax3D (*cloud, min_pt, max_pt);
    }
    else
    {
      getMinMax3D (*cloud, tmp_min_pt, tmp_max_pt);

      // Resize new min
      if (tmp_min_pt.x < min_pt.x)
        min_pt.x = tmp_min_pt.x;
      if (tmp_min_pt.y < min_pt.y)
        min_pt.y = tmp_min_pt.y;
      if (tmp_min_pt.z < min_pt.z)
        min_pt.z = tmp_min_pt.z;

      // Resize new max
      if (tmp_max_pt.x > max_pt.x)
        max_pt.x = tmp_max_pt.x;
      if (tmp_max_pt.y > max_pt.y)
        max_pt.y = tmp_max_pt.y;
      if (tmp_max_pt.z > max_pt.z)
        max_pt.z = tmp_max_pt.z;
    }
  }

  std::cout << "Bounds: " << min_pt << " - " << max_pt << std::endl;

  // The bounding box of the root node of the out-of-core octree must be specified
  const double bounding_box_min[3] = {min_pt.x, min_pt.y, min_pt.z};
  const double bounding_box_max[3] = {max_pt.x, max_pt.y, max_pt.z};

//arbitrarily large bounding box
//  const double bounding_box_min[3] = { -1e8, -1e8, -1e8 };
//  const double bounding_box_max[3] = { 1e8, 1e8, 1e8 };

  //specify the directory and the root node's meta data file with a
  //".oct_idx" extension (currently it must be this extension)
  boost::filesystem::path octree_path_on_disk (root_dir / "tree.oct_idx");

  print_info ("Writing: %s\n", octree_path_on_disk.c_str ());
  //make sure there isn't an octree there already
  if (boost::filesystem::exists (octree_path_on_disk))
  {
    if (overwrite)
    {
      boost::filesystem::remove_all (root_dir);
    }
    else
    {
      PCL_ERROR ("There's already an octree in the default location. Check the tree directory\n");
      return (-1);
    }
  }

  octree_disk *outofcore_octree;

  //create the out-of-core data structure (typedef'd above)
  if (build_octree_with == OCTREE_DEPTH)
  {
    outofcore_octree = new octree_disk (depth, bounding_box_min, bounding_box_max, octree_path_on_disk, "ECEF");
  }
  else
  {
    outofcore_octree = new octree_disk (bounding_box_min, bounding_box_max, resolution, octree_path_on_disk, "ECEF");
  }

  uint64_t total_pts = 0;

  // Iterate over all pcd files adding points to the octree
  for (size_t i = 0; i < pcd_paths.size (); i++)
  {

    PointCloud<PointT>::Ptr cloud = getCloudFromFile (pcd_paths[i]);

    uint64_t pts = 0;

    //load the points into the outofcore octree
    if (gen_lod)
    {
      print_info ("  Generating LODs\n");
      pts = outofcore_octree->addPointCloud_and_genLOD (cloud);
    }
    else
    {
      pts = outofcore_octree->addPointCloud (cloud);
    }
    print_info ("Successfully added %lu points\n",pts);
    assert ( pts == cloud->points.size () );

    total_pts += pts;
  }

  print_info ("Added a total of %lu from %d clouds\n",total_pts, pcd_paths.size ());

  double x, y;
  outofcore_octree->getBinDimension (x, y);

  print_info ("  Depth: %i\n", outofcore_octree->getDepth ());
  print_info ("  Resolution: [%f, %f]\n", x, y);

  //free outofcore data structure; the destructor forces buffer flush to disk
  delete outofcore_octree;

  return 0;
}

void
printHelp (int, char **argv)
{
  print_info ("This program is used to process pcd fiels into an outofcore data structure viewable by the");
  print_info ("pcl_outofcore_viewer\n\n");
  print_info ("%s <options> <input>.pcd <output_tree_dir>\n", argv[0]);
  print_info ("\n");
  print_info ("Options:\n");
  print_info ("\t -depth <resolution>           \t Octree depth\n");
  print_info ("\t -resolution <resolution>      \t Octree resolution\n");
  print_info ("\t -gen_lod                      \t Generate octree LODs\n");
  print_info ("\t -overwrite                    \t Overwrite existing octree\n");
  print_info ("\t -h                            \t Display help\n");
  print_info ("\n");
}

int
main (int argc, char* argv[])
{
  // Check for help (-h) flag
  if (argc > 1)
  {
    if (find_switch (argc, argv, "-h"))
    {
      printHelp (argc, argv);
      return (-1);
    }
  }

  // If no arguments specified
  if (argc - 1 < 1)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Defaults
  int depth = 4;
  double resolution = .1;
  bool gen_lod = false;
  bool overwrite = false;
  int build_octree_with = OCTREE_DEPTH;

  // If both depth and resolution specified
  if (find_switch (argc, argv, "-depth") && find_switch (argc, argv, "-resolution"))
  {
    PCL_ERROR ("Both -depth and -resolution specified, please specify one (Mutually exclusive)\n");
  }
  // Just resolution specified (Update how we build the tree)
  else if (find_switch (argc, argv, "-resolution"))
  {
    build_octree_with = OCTREE_RESOLUTION;
  }

  // Parse options
  parse_argument (argc, argv, "-depth", depth);
  parse_argument (argc, argv, "-resolution", resolution);
  gen_lod = find_switch (argc, argv, "-gen_lod");
  overwrite = find_switch (argc, argv, "-overwrite");

  // Parse non-option arguments for pcd files
  std::vector<int> file_arg_indices = parse_file_extension_argument (argc, argv, ".pcd");

  std::vector<boost::filesystem::path> pcd_paths;
  for (size_t i = 0; i < file_arg_indices.size (); i++)
  {
    boost::filesystem::path pcd_path (argv[file_arg_indices[i]]);
    if (!boost::filesystem::exists (pcd_path))
    {
      PCL_WARN ("File %s doesn't exist", pcd_path.string ().c_str ());
      continue;
    }
    pcd_paths.push_back (pcd_path);

  }

  // Check if we should process any files
  if (pcd_paths.size () < 1)
  {
    PCL_ERROR ("No .pcd files specified\n");
    return -1;
  }

  // Get root directory
  boost::filesystem::path root_dir (argv[argc - 1]);

  // Check if a root directory was specified, use directory of pcd file
  if (root_dir.extension () == ".pcd")
    root_dir = root_dir.parent_path () / "tree";

  return outofcoreProcess (pcd_paths, root_dir, depth, resolution, build_octree_with, gen_lod, overwrite);
}
<commit_msg>keep the default point type XYZ in outofcore_process for now<commit_after>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2009-2012, 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 Willow Garage, Inc. 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.
 *
 */

#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

#include <pcl/io/pcd_io.h>
#include <pcl/pcl_macros.h>

#include <pcl/console/print.h>
#include <pcl/console/parse.h>

#include <pcl/outofcore/outofcore.h>
#include <pcl/outofcore/outofcore_impl.h>

// todo: Read clouds as PointCloud2 so we don't need to define PointT explicitly.
//       This also requires our octree to take PointCloud2 as an input.
typedef pcl::PointXYZ PointT;

using namespace pcl;
using namespace pcl::outofcore;

using pcl::console::parse_argument;
using pcl::console::parse_file_extension_argument;
using pcl::console::find_switch;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;

#include <boost/foreach.hpp>

typedef octree_base<octree_disk_container<PointT> , PointT> octree_disk;

const int OCTREE_DEPTH (0);
const int OCTREE_RESOLUTION (1);

PointCloud<PointT>::Ptr
getCloudFromFile (boost::filesystem::path pcd_path)
{
  // Read PCD file
  PointCloud<PointT>::Ptr cloud (new PointCloud<PointT> ());

  print_info ("Reading: %s ", pcd_path.c_str ());

  if (io::loadPCDFile<PointT> (pcd_path.string (), *cloud) == -1) //* load the file
  {
    PCL_ERROR ("Couldn't read file\n");
    exit (-1);
  }

  print_info ("(%d)\n", (cloud->width * cloud->height));
  return cloud;
}

int
outofcoreProcess (std::vector<boost::filesystem::path> pcd_paths, boost::filesystem::path root_dir,
                  int depth, double resolution, int build_octree_with, bool gen_lod, bool overwrite)
{
  // Bounding box min/max pts
  PointT min_pt, max_pt;

  // Iterate over all pcd files resizing min/max
  for (size_t i = 0; i < pcd_paths.size (); i++)
  {

    // Get cloud
    PointCloud<PointT>::Ptr cloud = getCloudFromFile (pcd_paths[i]);

    PointT tmp_min_pt, tmp_max_pt;

    if (i == 0)
    {
      // Get initial min/max
      getMinMax3D (*cloud, min_pt, max_pt);
    }
    else
    {
      getMinMax3D (*cloud, tmp_min_pt, tmp_max_pt);

      // Resize new min
      if (tmp_min_pt.x < min_pt.x)
        min_pt.x = tmp_min_pt.x;
      if (tmp_min_pt.y < min_pt.y)
        min_pt.y = tmp_min_pt.y;
      if (tmp_min_pt.z < min_pt.z)
        min_pt.z = tmp_min_pt.z;

      // Resize new max
      if (tmp_max_pt.x > max_pt.x)
        max_pt.x = tmp_max_pt.x;
      if (tmp_max_pt.y > max_pt.y)
        max_pt.y = tmp_max_pt.y;
      if (tmp_max_pt.z > max_pt.z)
        max_pt.z = tmp_max_pt.z;
    }
  }

  std::cout << "Bounds: " << min_pt << " - " << max_pt << std::endl;

  // The bounding box of the root node of the out-of-core octree must be specified
  const double bounding_box_min[3] = {min_pt.x, min_pt.y, min_pt.z};
  const double bounding_box_max[3] = {max_pt.x, max_pt.y, max_pt.z};

//arbitrarily large bounding box
//  const double bounding_box_min[3] = { -1e8, -1e8, -1e8 };
//  const double bounding_box_max[3] = { 1e8, 1e8, 1e8 };

  //specify the directory and the root node's meta data file with a
  //".oct_idx" extension (currently it must be this extension)
  boost::filesystem::path octree_path_on_disk (root_dir / "tree.oct_idx");

  print_info ("Writing: %s\n", octree_path_on_disk.c_str ());
  //make sure there isn't an octree there already
  if (boost::filesystem::exists (octree_path_on_disk))
  {
    if (overwrite)
    {
      boost::filesystem::remove_all (root_dir);
    }
    else
    {
      PCL_ERROR ("There's already an octree in the default location. Check the tree directory\n");
      return (-1);
    }
  }

  octree_disk *outofcore_octree;

  //create the out-of-core data structure (typedef'd above)
  if (build_octree_with == OCTREE_DEPTH)
  {
    outofcore_octree = new octree_disk (depth, bounding_box_min, bounding_box_max, octree_path_on_disk, "ECEF");
  }
  else
  {
    outofcore_octree = new octree_disk (bounding_box_min, bounding_box_max, resolution, octree_path_on_disk, "ECEF");
  }

  uint64_t total_pts = 0;

  // Iterate over all pcd files adding points to the octree
  for (size_t i = 0; i < pcd_paths.size (); i++)
  {

    PointCloud<PointT>::Ptr cloud = getCloudFromFile (pcd_paths[i]);

    uint64_t pts = 0;

    //load the points into the outofcore octree
    if (gen_lod)
    {
      print_info ("  Generating LODs\n");
      pts = outofcore_octree->addPointCloud_and_genLOD (cloud);
    }
    else
    {
      pts = outofcore_octree->addPointCloud (cloud);
    }
    print_info ("Successfully added %lu points\n",pts);
    assert ( pts == cloud->points.size () );

    total_pts += pts;
  }

  print_info ("Added a total of %lu from %d clouds\n",total_pts, pcd_paths.size ());

  double x, y;
  outofcore_octree->getBinDimension (x, y);

  print_info ("  Depth: %i\n", outofcore_octree->getDepth ());
  print_info ("  Resolution: [%f, %f]\n", x, y);

  //free outofcore data structure; the destructor forces buffer flush to disk
  delete outofcore_octree;

  return 0;
}

void
printHelp (int, char **argv)
{
  print_info ("This program is used to process pcd fiels into an outofcore data structure viewable by the");
  print_info ("pcl_outofcore_viewer\n\n");
  print_info ("%s <options> <input>.pcd <output_tree_dir>\n", argv[0]);
  print_info ("\n");
  print_info ("Options:\n");
  print_info ("\t -depth <resolution>           \t Octree depth\n");
  print_info ("\t -resolution <resolution>      \t Octree resolution\n");
  print_info ("\t -gen_lod                      \t Generate octree LODs\n");
  print_info ("\t -overwrite                    \t Overwrite existing octree\n");
  print_info ("\t -h                            \t Display help\n");
  print_info ("\n");
}

int
main (int argc, char* argv[])
{
  // Check for help (-h) flag
  if (argc > 1)
  {
    if (find_switch (argc, argv, "-h"))
    {
      printHelp (argc, argv);
      return (-1);
    }
  }

  // If no arguments specified
  if (argc - 1 < 1)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Defaults
  int depth = 4;
  double resolution = .1;
  bool gen_lod = false;
  bool overwrite = false;
  int build_octree_with = OCTREE_DEPTH;

  // If both depth and resolution specified
  if (find_switch (argc, argv, "-depth") && find_switch (argc, argv, "-resolution"))
  {
    PCL_ERROR ("Both -depth and -resolution specified, please specify one (Mutually exclusive)\n");
  }
  // Just resolution specified (Update how we build the tree)
  else if (find_switch (argc, argv, "-resolution"))
  {
    build_octree_with = OCTREE_RESOLUTION;
  }

  // Parse options
  parse_argument (argc, argv, "-depth", depth);
  parse_argument (argc, argv, "-resolution", resolution);
  gen_lod = find_switch (argc, argv, "-gen_lod");
  overwrite = find_switch (argc, argv, "-overwrite");

  // Parse non-option arguments for pcd files
  std::vector<int> file_arg_indices = parse_file_extension_argument (argc, argv, ".pcd");

  std::vector<boost::filesystem::path> pcd_paths;
  for (size_t i = 0; i < file_arg_indices.size (); i++)
  {
    boost::filesystem::path pcd_path (argv[file_arg_indices[i]]);
    if (!boost::filesystem::exists (pcd_path))
    {
      PCL_WARN ("File %s doesn't exist", pcd_path.string ().c_str ());
      continue;
    }
    pcd_paths.push_back (pcd_path);

  }

  // Check if we should process any files
  if (pcd_paths.size () < 1)
  {
    PCL_ERROR ("No .pcd files specified\n");
    return -1;
  }

  // Get root directory
  boost::filesystem::path root_dir (argv[argc - 1]);

  // Check if a root directory was specified, use directory of pcd file
  if (root_dir.extension () == ".pcd")
    root_dir = root_dir.parent_path () / "tree";

  return outofcoreProcess (pcd_paths, root_dir, depth, resolution, build_octree_with, gen_lod, overwrite);
}
<|endoftext|>


<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */

#include "arch/base.h"

#include "granary/base/base.h"
#include "granary/base/lock.h"

#include "granary/breakpoint.h"

#include "os/memory.h"

#define O_CREAT       0100
#define O_RDONLY      00
#define O_RDWR        02
#define O_CLOEXEC     02000000

#define PROT_READ     0x1
#define PROT_WRITE    0x2
#define PROT_EXEC     0x4

#define MAP_PRIVATE   0x02
#define MAP_ANONYMOUS 0x20

extern "C" {

extern int open(const char *__file, int __oflag, void *);
extern void *mmap(void *__addr, size_t __len, int __prot, int __flags,
                  int __fd, long __offset);
extern int munmap(void *__addr, size_t __len);
extern int mprotect(void *__addr, size_t __len, int __prot);
extern int mlock(const void *__addr, size_t __len);

}  // extern C
namespace granary {
namespace os {
#ifdef GRANARY_TARGET_test
namespace {

static int code_cache_fd = -1;
static FineGrainedLock code_cache_fd_lock;

// Initialize a temporary file descriptor for this code cache. This is so that
// in user space, we can associate the code cache with something in
// `/proc/self/maps`. This isn't needed for the correct function of Granary but
// instead helps to enable recursive instrumentation (Granary instrumenting
// Granary).
static void InitCodeCacheFD(void) {
  FineGrainedLocked locker(&code_cache_fd_lock);
  if (-1 == code_cache_fd) {
    code_cache_fd = open("/dev/zero", O_RDONLY, nullptr);
    GRANARY_ASSERT(-1 != code_cache_fd);
  }
}

}  // namespace
#endif  // GRANARY_TARGET_test

// Initialize the Granary heap.
void InitHeap(void) {}

// Allocates `num` number of pages from the OS with `MEMORY_READ_WRITE`
// protection.
void *AllocatePages(int num, MemoryIntent intent) {
  auto prot = PROT_READ | PROT_WRITE;
  auto flags = MAP_PRIVATE;
  auto fd = -1;

#ifdef GRANARY_TARGET_test
  if (MemoryIntent::EXECUTABLE == intent) {
    prot |= PROT_EXEC;
    if (GRANARY_UNLIKELY(-1 == code_cache_fd)) {
      InitCodeCacheFD();
    }
    fd = code_cache_fd;

  } else {
    flags |= MAP_ANONYMOUS;
  }
#else
  flags |= MAP_ANONYMOUS;
#endif

  auto num_bytes = static_cast<size_t>(arch::PAGE_SIZE_BYTES * num);
  auto ret = mmap(nullptr, num_bytes, prot, flags, fd, 0);
  if (MemoryIntent::EXECUTABLE == intent) {
    mlock(ret, num_bytes);
  }
  return ret;
}

// Frees `num` pages back to the OS.
void FreePages(void *addr, int num, MemoryIntent) {
  munmap(addr, static_cast<size_t>(arch::PAGE_SIZE_BYTES * num));
}

// Changes the memory protection of some pages.
void ProtectPages(void *addr, int num, MemoryProtection prot) {
  int prot_bits(0);
  if (MemoryProtection::EXECUTABLE == prot) {
    prot_bits = PROT_EXEC | PROT_READ | PROT_WRITE;
  } else if (MemoryProtection::READ_ONLY == prot) {
    prot_bits = PROT_READ;
  } else if (MemoryProtection::READ_WRITE == prot) {
    prot_bits = PROT_READ | PROT_WRITE;
  } else {
    prot_bits = 0; //  MEMORY_INACCESSIBLE
  }
  mprotect(
      addr,
      static_cast<size_t>(arch::PAGE_SIZE_BYTES * num),
      prot_bits);
}

}  // namespace os
}  // namespace granary
<commit_msg>Left a minor bug in the code where for debug and release builds I wasn't making mmaped memory executable.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */

#include "arch/base.h"

#include "granary/base/base.h"
#include "granary/base/lock.h"

#include "granary/breakpoint.h"

#include "os/memory.h"

#define O_CREAT       0100
#define O_RDONLY      00
#define O_RDWR        02
#define O_CLOEXEC     02000000

#define PROT_READ     0x1
#define PROT_WRITE    0x2
#define PROT_EXEC     0x4

#define MAP_PRIVATE   0x02
#define MAP_ANONYMOUS 0x20

extern "C" {

extern int open(const char *__file, int __oflag, void *);
extern void *mmap(void *__addr, size_t __len, int __prot, int __flags,
                  int __fd, long __offset);
extern int munmap(void *__addr, size_t __len);
extern int mprotect(void *__addr, size_t __len, int __prot);
extern int mlock(const void *__addr, size_t __len);

}  // extern C
namespace granary {
namespace os {
#ifdef GRANARY_TARGET_test
namespace {

static int code_cache_fd = -1;
static FineGrainedLock code_cache_fd_lock;

// Initialize a temporary file descriptor for this code cache. This is so that
// in user space, we can associate the code cache with something in
// `/proc/self/maps`. This isn't needed for the correct function of Granary but
// instead helps to enable recursive instrumentation (Granary instrumenting
// Granary).
static void InitCodeCacheFD(void) {
  FineGrainedLocked locker(&code_cache_fd_lock);
  if (-1 == code_cache_fd) {
    code_cache_fd = open("/dev/zero", O_RDONLY, nullptr);
    GRANARY_ASSERT(-1 != code_cache_fd);
  }
}

}  // namespace
#endif  // GRANARY_TARGET_test

// Initialize the Granary heap.
void InitHeap(void) {}

// Allocates `num` number of pages from the OS with `MEMORY_READ_WRITE`
// protection.
void *AllocatePages(int num, MemoryIntent intent) {
  auto prot = PROT_READ | PROT_WRITE;
  auto flags = MAP_PRIVATE;
  auto fd = -1;

  if (MemoryIntent::EXECUTABLE == intent) {
    prot |= PROT_EXEC;
  }

#ifdef GRANARY_TARGET_test
  if (MemoryIntent::EXECUTABLE == intent) {
    if (GRANARY_UNLIKELY(-1 == code_cache_fd)) {
      InitCodeCacheFD();
    }
    fd = code_cache_fd;

  } else {
    flags |= MAP_ANONYMOUS;
  }
#else
  flags |= MAP_ANONYMOUS;
#endif

  auto num_bytes = static_cast<size_t>(arch::PAGE_SIZE_BYTES * num);
  auto ret = mmap(nullptr, num_bytes, prot, flags, fd, 0);
  if (MemoryIntent::EXECUTABLE == intent) {
    mlock(ret, num_bytes);
  }
  return ret;
}

// Frees `num` pages back to the OS.
void FreePages(void *addr, int num, MemoryIntent) {
  munmap(addr, static_cast<size_t>(arch::PAGE_SIZE_BYTES * num));
}

// Changes the memory protection of some pages.
void ProtectPages(void *addr, int num, MemoryProtection prot) {
  int prot_bits(0);
  if (MemoryProtection::EXECUTABLE == prot) {
    prot_bits = PROT_EXEC | PROT_READ | PROT_WRITE;
  } else if (MemoryProtection::READ_ONLY == prot) {
    prot_bits = PROT_READ;
  } else if (MemoryProtection::READ_WRITE == prot) {
    prot_bits = PROT_READ | PROT_WRITE;
  } else {
    prot_bits = 0; //  MEMORY_INACCESSIBLE
  }
  mprotect(
      addr,
      static_cast<size_t>(arch::PAGE_SIZE_BYTES * num),
      prot_bits);
}

}  // namespace os
}  // namespace granary
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif

#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/space/lagrangespace.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "../interface.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper;

// forward, to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapperTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRangeCols = 1.
 */
template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
{
public:
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > derived_type;
  typedef GridPartImp                   GridPartType;
  static const int                      polOrder = polynomialOrder;
  dune_static_assert((polOrder >= 1), "ERROR: wrong polOrder given!");
private:
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRange = 1;
  static const unsigned int             dimRangeCols = 1;
private:
  typedef Dune::Fem::FunctionSpace< DomainFieldType, RangeFieldType, dimDomain, dimRange > FunctionSpaceType;
public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, GridPartType, polOrder > BackendType;
  typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType;
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper< typename BackendType::BaseFunctionSetType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
}; // class SpaceWrappedFemContinuousLagrangeTraits< ..., 1, 1 >

template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public SpaceInterface< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > >
{
  typedef SpaceInterface< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > > BaseType;
public:
  typedef FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridPartType GridPartType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

public:
  FemWrapper(const GridPartType& gridP)
    : gridPart_(gridP)
    , backend_(const_cast< GridPartType& >(gridPart_))
    , mapper_(backend_.mapper())
    , tmpMappedRows_(mapper_.maxNumDofs())
    , tmpMappedCols_(mapper_.maxNumDofs())
  {}

  ~FemWrapper() {}

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend_, entity);
  }

  template< class R >
  void localConstraints(const EntityType& /*entity*/,
                        Constraints::LocalDefault< R >& /*ret*/) const
  {
    dune_static_assert(Dune::AlwaysFalse< R >::value, "ERROR: not implemented for arbitrary constraints!");
  }

  void localConstraints(const EntityType& entity,
                        Constraints::Dirichlet< typename GridPartType::IntersectionType, RangeFieldType, true >& ret) const
  {
    const auto& lagrangePointSet = backend_.lagrangePointSet(entity);
    std::set< size_t > localDirichletDofs;
    // loop over all intersections
    const auto& gridBoundary = ret.gridBoundary();
    const auto intersectionEndIt = gridPart_.iend(entity);
    for (auto intersectionIt = gridPart_.ibegin(entity); intersectionIt !=intersectionEndIt; ++intersectionIt) {
      const auto& intersection = *intersectionIt;
      // only work on dirichlet intersections
      if (gridBoundary.dirichlet(intersection)) {
        // get local face number of boundary intersection
        const int intersectionIndex = intersection.indexInInside();
        // iterate over face dofs and set unit row
        const auto faceDofEndIt = lagrangePointSet.template endSubEntity< 1 >(intersectionIndex);
        for (auto faceDofIt = lagrangePointSet.template beginSubEntity< 1 >(intersectionIndex);
             faceDofIt != faceDofEndIt;
             ++faceDofIt) {
          const size_t localDofIndex = *faceDofIt;
          localDirichletDofs.insert(localDofIndex);
        } // iterate over face dofs and set unit row
      } // only work on dirichlet intersections
    } // loop over all intersections
    const BaseFunctionSetType basis = baseFunctionSet(entity);
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = basis.size();
      ret.setSize(numRows, numCols);
      mapper_.globalIndices(entity, tmpMappedRows_);
      mapper_.globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      const RangeFieldType one(1);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = one;
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... localConstraints(..., Dirichlet< ..., true >)

  void localConstraints(const EntityType& entity,
                        Constraints::Dirichlet< typename GridPartType::IntersectionType, RangeFieldType, false >& ret) const
  {
    const auto& lagrangePointSet = backend_.lagrangePointSet(entity);
    std::set< size_t > localDirichletDofs;
    // loop over all intersections
    const auto& gridBoundary = ret.gridBoundary();
    const auto intersectionEndIt = gridPart_.iend(entity);
    for (auto intersectionIt = gridPart_.ibegin(entity); intersectionIt !=intersectionEndIt; ++intersectionIt) {
      const auto& intersection = *intersectionIt;
      // only work on dirichlet intersections
      if (gridBoundary.dirichlet(intersection)) {
        // get local face number of boundary intersection
        const int intersectionIndex = intersection.indexInInside();
        // iterate over face dofs and set unit row
        const auto faceDofEndIt = lagrangePointSet.template endSubEntity< 1 >(intersectionIndex);
        for (auto faceDofIt = lagrangePointSet.template beginSubEntity< 1 >(intersectionIndex);
             faceDofIt != faceDofEndIt;
             ++faceDofIt) {
          const size_t localDofIndex = *faceDofIt;
          localDirichletDofs.insert(localDofIndex);
        } // iterate over face dofs and set unit row
      } // only work on dirichlet intersections
    } // loop over all intersections
    const BaseFunctionSetType basis = baseFunctionSet(entity);
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = basis.size();
      ret.setSize(numRows, numCols);
      mapper_.globalIndices(entity, tmpMappedRows_);
      mapper_.globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... localConstraints(..., Dirichlet< ..., false >)

  using BaseType::computePattern;

  template< class LocalGridPartType, class OtherSpaceType >
  PatternType* computePattern(const LocalGridPartType& localGridPart,
                              const OtherSpaceType& otherSpace) const
  {
    return BaseType::computeVolumePattern(localGridPart, otherSpace);
  }

private:
  const GridPartType& gridPart_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class FemWrapper< ..., 1, 1 >

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
<commit_msg>[space.continuouslagrange.fem] updated to new requrements<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif

#include <memory>

#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/space/lagrangespace.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "../interface.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapper;

// forward, to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class FemWrapperTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRangeCols = 1.
 */
template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
{
public:
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > derived_type;
  typedef GridPartImp                   GridPartType;
  static const int                      polOrder = polynomialOrder;
  dune_static_assert((polOrder >= 1), "ERROR: wrong polOrder given!");
private:
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRange = 1;
  static const unsigned int             dimRangeCols = 1;
private:
  typedef Dune::Fem::FunctionSpace< DomainFieldType, RangeFieldType, dimDomain, dimRange > FunctionSpaceType;
public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, GridPartType, polOrder > BackendType;
  typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType;
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper< typename BackendType::BaseFunctionSetType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType;
}; // class SpaceWrappedFemContinuousLagrangeTraits< ..., 1, 1 >

template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public SpaceInterface< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > >
{
  typedef SpaceInterface< FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > > BaseType;
  typedef FemWrapper< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >                         ThisType;
public:
  typedef FemWrapperTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridPartType GridPartType;
  static const int                      polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

  FemWrapper(const std::shared_ptr< const GridPartType >& gridP)
    : gridPart_(gridP)
    , backend_(std::make_shared< BackendType >(const_cast< GridPartType& >(*(gridPart_))))
    , mapper_(std::make_shared< MapperType >(backend_->mapper()))
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  FemWrapper(const ThisType& other)
    : gridPart_(other.gridPart_)
    , backend_(other.backend_)
    , mapper_(other.mapper_)
    , tmpMappedRows_(mapper_->maxNumDofs())
    , tmpMappedCols_(mapper_->maxNumDofs())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      gridPart_ = other.gridPart_;
      backend_ = other.backend_;
      mapper_ = other.mapper_;
    }
    return *this;
  }

  ~FemWrapper() {}

  const std::shared_ptr< const GridPartType >& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return *backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(*backend_, entity);
  }

  template< class R >
  void localConstraints(const EntityType& /*entity*/,
                        Constraints::LocalDefault< R >& /*ret*/) const
  {
    dune_static_assert(Dune::AlwaysFalse< R >::value, "ERROR: not implemented for arbitrary constraints!");
  }

  void localConstraints(const EntityType& entity,
                        Constraints::Dirichlet< typename GridPartType::IntersectionType, RangeFieldType, true >& ret) const
  {
    const auto& lagrangePointSet = backend_->lagrangePointSet(entity);
    std::set< size_t > localDirichletDofs;
    // loop over all intersections
    const auto& gridBoundary = ret.gridBoundary();
    const auto intersectionEndIt = gridPart_->iend(entity);
    for (auto intersectionIt = gridPart_->ibegin(entity); intersectionIt !=intersectionEndIt; ++intersectionIt) {
      const auto& intersection = *intersectionIt;
      // only work on dirichlet intersections
      if (gridBoundary.dirichlet(intersection)) {
        // get local face number of boundary intersection
        const int intersectionIndex = intersection.indexInInside();
        // iterate over face dofs and set unit row
        const auto faceDofEndIt = lagrangePointSet.template endSubEntity< 1 >(intersectionIndex);
        for (auto faceDofIt = lagrangePointSet.template beginSubEntity< 1 >(intersectionIndex);
             faceDofIt != faceDofEndIt;
             ++faceDofIt) {
          const size_t localDofIndex = *faceDofIt;
          localDirichletDofs.insert(localDofIndex);
        } // iterate over face dofs and set unit row
      } // only work on dirichlet intersections
    } // loop over all intersections
    const BaseFunctionSetType basis = baseFunctionSet(entity);
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = basis.size();
      ret.setSize(numRows, numCols);
      mapper_->globalIndices(entity, tmpMappedRows_);
      mapper_->globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      const RangeFieldType one(1);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = one;
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... localConstraints(..., Dirichlet< ..., true >)

  void localConstraints(const EntityType& entity,
                        Constraints::Dirichlet< typename GridPartType::IntersectionType, RangeFieldType, false >& ret) const
  {
    const auto& lagrangePointSet = backend_->lagrangePointSet(entity);
    std::set< size_t > localDirichletDofs;
    // loop over all intersections
    const auto& gridBoundary = ret.gridBoundary();
    const auto intersectionEndIt = gridPart_->iend(entity);
    for (auto intersectionIt = gridPart_->ibegin(entity); intersectionIt !=intersectionEndIt; ++intersectionIt) {
      const auto& intersection = *intersectionIt;
      // only work on dirichlet intersections
      if (gridBoundary.dirichlet(intersection)) {
        // get local face number of boundary intersection
        const int intersectionIndex = intersection.indexInInside();
        // iterate over face dofs and set unit row
        const auto faceDofEndIt = lagrangePointSet.template endSubEntity< 1 >(intersectionIndex);
        for (auto faceDofIt = lagrangePointSet.template beginSubEntity< 1 >(intersectionIndex);
             faceDofIt != faceDofEndIt;
             ++faceDofIt) {
          const size_t localDofIndex = *faceDofIt;
          localDirichletDofs.insert(localDofIndex);
        } // iterate over face dofs and set unit row
      } // only work on dirichlet intersections
    } // loop over all intersections
    const BaseFunctionSetType basis = baseFunctionSet(entity);
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = basis.size();
      ret.setSize(numRows, numCols);
      mapper_->globalIndices(entity, tmpMappedRows_);
      mapper_->globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... localConstraints(..., Dirichlet< ..., false >)

  using BaseType::computePattern;

  template< class LocalGridPartType, class OtherSpaceType >
  PatternType* computePattern(const LocalGridPartType& localGridPart,
                              const OtherSpaceType& otherSpace) const
  {
    return BaseType::computeCodim0Pattern(localGridPart, otherSpace);
  }

private:
  std::shared_ptr< const GridPartType > gridPart_;
  std::shared_ptr< const BackendType > backend_;
  std::shared_ptr< const MapperType > mapper_;
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class FemWrapper< ..., 1, 1 >

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_HH
<|endoftext|>