<commit_before>#include <iostream>
#include "PlanGenerator.h"
#include "PX4Driver.h"
#include "WorkspaceParser.h"
using namespace std;

#define SIMULATOR_PORT 14550

WS_Coord shiftBy = WS_Coord(25, 25, 0);

WS_Coord PlannerToGazebo(WS_Coord coord) {
    return WS_Coord(coord.x - shiftBy.x, coord.y - shiftBy.y, coord.z - shiftBy.z);
}

WS_Coord GazeboToPlanner(WS_Coord coord) {
    return WS_Coord(coord.x + shiftBy.x, coord.y + shiftBy.y, coord.z + shiftBy.z);
}

int main(int argc, char const *argv[])
{

    PX4API *px4 = new PX4API(SIMULATOR_PORT);
    char filename[] = "traj.csv";
    PX4Logger *px4logger = new PX4Logger(10, filename, true, vector<bool>{true, true, true});
    double eps = 1;

    usleep(2500000);
    px4->Arm();
    usleep(2500000);
    px4->StartAutopilot(0,0,-3); //takeoff
    usleep(5000000);

    px4logger->Start();

    //test OMPL planner
    vector<WS_Coord> destinations = {
        WS_Coord(0, 0, 3),
        WS_Coord(6.9, 13.6, 4),
        WS_Coord(18.8, 13.3, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(18.7, -2.3, 6),
        WS_Coord(0.69, -2.8, 3),
        WS_Coord(-20.5, -6, 6),
        WS_Coord(-21, -16, 4),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(-6.8, -22, 4),
        WS_Coord(1.17, -16.4, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(-20.52, -0.59, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(18.78, -2.31, 6),
        WS_Coord(17.72, -22.08, 2),
        WS_Coord(0.69, -2.8, 3),
        WS_Coord(1.17, -16.4, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
    };

    OMPLPLanner* planner = new OMPLPLanner(argv[1], PLANNER_RRTSTAR, OBJECTIVE_PATHLENGTH);
    for(int i = 0; i< destinations.size()-1; i++)
    {

        vector<WS_Coord> path = planner->GeneratePlan(1, GazeboToPlanner(destinations.at(i)), GazeboToPlanner(destinations.at(i+1)));
        //convert the path into goto of length less than 10
        vector<WS_Coord> pathNew = path;//ConvertToSmallGotos(path);

        for (int count = 0; count < pathNew.size(); count++)
        {
            WS_Coord shifted = PlannerToGazebo(pathNew.at(count));
            cout << shifted.ToString() << endl;
            px4->GoTo(shifted.y, shifted.x, -shifted.z, 1);
        }
    }

    px4logger->Stop();
    px4logger->ToCSV();

	return 0;
}
<commit_msg>update<commit_after>#include <iostream>
#include "PlanGenerator.h"
#include "PX4Driver.h"
#include "WorkspaceParser.h"
using namespace std;

#define SIMULATOR_PORT 14550

WS_Coord shiftBy = WS_Coord(25, 25, 0);

WS_Coord PlannerToGazebo(WS_Coord coord) {
    return WS_Coord(coord.x - shiftBy.x, coord.y - shiftBy.y, coord.z - shiftBy.z);
}

WS_Coord GazeboToPlanner(WS_Coord coord) {
    return WS_Coord(coord.x + shiftBy.x, coord.y + shiftBy.y, coord.z + shiftBy.z);
}

int main(int argc, char const *argv[])
{

    InitializeLogger();
    PX4API *px4 = new PX4API(SIMULATOR_PORT);
    char filename[] = "traj.csv";
    PX4Logger *px4logger = new PX4Logger(10, filename, true, vector<bool>{true, true, true});
    double eps = 1;

    usleep(2500000);
    px4->Arm();
    usleep(2500000);
    px4->StartAutopilot(0,0,-3); //takeoff
    usleep(5000000);

    px4logger->Start();

    //test OMPL planner
    vector<WS_Coord> destinations = {
        WS_Coord(0, 0, 3),
        WS_Coord(6.9, 13.6, 4),
        WS_Coord(18.8, 13.3, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(18.7, -2.3, 6),
        WS_Coord(0.69, -2.8, 3),
        WS_Coord(-20.5, -6, 6),
        WS_Coord(-21, -16, 4),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(-6.8, -22, 4),
        WS_Coord(1.17, -16.4, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
        WS_Coord(-20.52, -0.59, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(18.78, -2.31, 6),
        WS_Coord(17.72, -22.08, 2),
        WS_Coord(0.69, -2.8, 3),
        WS_Coord(1.17, -16.4, 5),
        WS_Coord(0.69, -2.81, 6),
        WS_Coord(-5.3, 18.3, 5),
        WS_Coord(-21.56, 15.12, 4),
    };

    OMPLPLanner* planner = new OMPLPLanner(argv[1], PLANNER_RRTSTAR, OBJECTIVE_PATHLENGTH);
    for(int i = 0; i< destinations.size()-1; i++)
    {

        vector<WS_Coord> path = planner->GeneratePlan(1, GazeboToPlanner(destinations.at(i)), GazeboToPlanner(destinations.at(i+1)));
        //convert the path into goto of length less than 10
        vector<WS_Coord> pathNew = path;//ConvertToSmallGotos(path);

        for (int count = 0; count < pathNew.size(); count++)
        {
            WS_Coord shifted = PlannerToGazebo(pathNew.at(count));
            cout << shifted.ToString() << endl;
            px4->GoTo(shifted.y, shifted.x, -shifted.z, 1);
        }
    }

    px4logger->Stop();
    px4logger->ToCSV();

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pagepar.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:47:23 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SC_PAGEPAR_HXX
#define SC_PAGEPAR_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

//-----------------------------------------------------------------------

struct ScPageTableParam
{
    BOOL    bNotes;
    BOOL    bGrid;
    BOOL    bHeaders;
    BOOL    bCharts;
    BOOL    bObjects;
    BOOL    bDrawings;
    BOOL    bFormulas;
    BOOL    bNullVals;
    BOOL    bTopDown;
    BOOL    bLeftRight;
    BOOL    bSkipEmpty;
    BOOL    bScaleNone;
    BOOL    bScaleAll;
    BOOL    bScaleTo;
    BOOL    bScalePageNum;
    USHORT  nScaleAll;
    USHORT  nScaleWidth;
    USHORT  nScaleHeight;
    USHORT  nScalePageNum;
    USHORT  nFirstPageNo;

    ScPageTableParam();
    ~ScPageTableParam();

    BOOL                operator==  ( const ScPageTableParam& r ) const;
    void                Reset       ();
};

struct ScPageAreaParam
{
    BOOL    bPrintArea;
    BOOL    bRepeatRow;
    BOOL    bRepeatCol;
    ScRange aPrintArea;
    ScRange aRepeatRow;
    ScRange aRepeatCol;

    ScPageAreaParam();
    ~ScPageAreaParam();

    BOOL                operator==  ( const ScPageAreaParam& r ) const;
    void                Reset       ();
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.700); FILE MERGED 2008/04/01 12:35:59 thb 1.4.700.2: #i85898# Stripping all external header guards 2008/03/31 17:13:32 rt 1.4.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: pagepar.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_PAGEPAR_HXX
#define SC_PAGEPAR_HXX

#include "global.hxx"
#include "address.hxx"

//-----------------------------------------------------------------------

struct ScPageTableParam
{
    BOOL    bNotes;
    BOOL    bGrid;
    BOOL    bHeaders;
    BOOL    bCharts;
    BOOL    bObjects;
    BOOL    bDrawings;
    BOOL    bFormulas;
    BOOL    bNullVals;
    BOOL    bTopDown;
    BOOL    bLeftRight;
    BOOL    bSkipEmpty;
    BOOL    bScaleNone;
    BOOL    bScaleAll;
    BOOL    bScaleTo;
    BOOL    bScalePageNum;
    USHORT  nScaleAll;
    USHORT  nScaleWidth;
    USHORT  nScaleHeight;
    USHORT  nScalePageNum;
    USHORT  nFirstPageNo;

    ScPageTableParam();
    ~ScPageTableParam();

    BOOL                operator==  ( const ScPageTableParam& r ) const;
    void                Reset       ();
};

struct ScPageAreaParam
{
    BOOL    bPrintArea;
    BOOL    bRepeatRow;
    BOOL    bRepeatCol;
    ScRange aPrintArea;
    ScRange aRepeatRow;
    ScRange aRepeatCol;

    ScPageAreaParam();
    ~ScPageAreaParam();

    BOOL                operator==  ( const ScPageAreaParam& r ) const;
    void                Reset       ();
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: servuno.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-10 13:10:06 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SC_SERVUNO_HXX
#define SC_SERVUNO_HXX

#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

class String;
class ScDocShell;

//! AutoFormat wirklich hier oder besser global??????

#define SC_SERVICE_SHEET        0
#define SC_SERVICE_URLFIELD     1
#define SC_SERVICE_PAGEFIELD    2
#define SC_SERVICE_PAGESFIELD   3
#define SC_SERVICE_DATEFIELD    4
#define SC_SERVICE_TIMEFIELD    5
#define SC_SERVICE_TITLEFIELD   6
#define SC_SERVICE_FILEFIELD    7
#define SC_SERVICE_SHEETFIELD   8
#define SC_SERVICE_CELLSTYLE    9
#define SC_SERVICE_PAGESTYLE    10
#define SC_SERVICE_AUTOFORMAT   11
#define SC_SERVICE_CELLRANGES   12

//  drawing layer tables
#define SC_SERVICE_GRADTAB      13
#define SC_SERVICE_HATCHTAB     14
#define SC_SERVICE_BITMAPTAB    15
#define SC_SERVICE_TRGRADTAB    16
#define SC_SERVICE_MARKERTAB    17
#define SC_SERVICE_DASHTAB      18
#define SC_SERVICE_NUMRULES     19

#define SC_SERVICE_DOCDEFLTS    20
#define SC_SERVICE_DRAWDEFLTS   21

#define SC_SERVICE_DOCSPRSETT   22
#define SC_SERVICE_DOCCONF      23

#define SC_SERVICE_IMAP_RECT    24
#define SC_SERVICE_IMAP_CIRC    25
#define SC_SERVICE_IMAP_POLY    26

// #100263# Support creation of GraphicObjectResolver and EmbeddedObjectResolver
#define SC_SERVICE_EXPORT_GOR   27
#define SC_SERVICE_IMPORT_GOR   28
#define SC_SERVICE_EXPORT_EOR   29
#define SC_SERVICE_IMPORT_EOR   30

#define SC_SERVICE_VALBIND      31
#define SC_SERVICE_LISTCELLBIND 32
#define SC_SERVICE_LISTSOURCE   33

#define SC_SERVICE_CELLADDRESS  34
#define SC_SERVICE_RANGEADDRESS 35

#define SC_SERVICE_SHEETDOCSET  36

// BM
#define SC_SERVICE_CHDATAPROV   37

#define SC_SERVICE_FORMULAPARS  38
#define SC_SERVICE_OPCODEMAPPER 39

#define SC_SERVICE_COUNT        40
#define SC_SERVICE_INVALID      USHRT_MAX

class ScServiceProvider
{
public:
                            // pDocShell wird nicht fuer alle Services benoetigt
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                            MakeInstance( sal_uInt16 nType, ScDocShell* pDocShell );
    static ::com::sun::star::uno::Sequence<rtl::OUString> GetAllServiceNames();
    static String           GetProviderName(sal_uInt16 nObjectType);
    static sal_uInt16       GetProviderType(const String& rServiceName);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.13.96); FILE MERGED 2008/04/01 15:29:42 thb 1.13.96.3: #i85898# Stripping all external header guards 2008/04/01 12:36:01 thb 1.13.96.2: #i85898# Stripping all external header guards 2008/03/31 17:13:34 rt 1.13.96.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: servuno.hxx,v $
 * $Revision: 1.14 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_SERVUNO_HXX
#define SC_SERVUNO_HXX

#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Sequence.hxx>

class String;
class ScDocShell;

//! AutoFormat wirklich hier oder besser global??????

#define SC_SERVICE_SHEET        0
#define SC_SERVICE_URLFIELD     1
#define SC_SERVICE_PAGEFIELD    2
#define SC_SERVICE_PAGESFIELD   3
#define SC_SERVICE_DATEFIELD    4
#define SC_SERVICE_TIMEFIELD    5
#define SC_SERVICE_TITLEFIELD   6
#define SC_SERVICE_FILEFIELD    7
#define SC_SERVICE_SHEETFIELD   8
#define SC_SERVICE_CELLSTYLE    9
#define SC_SERVICE_PAGESTYLE    10
#define SC_SERVICE_AUTOFORMAT   11
#define SC_SERVICE_CELLRANGES   12

//  drawing layer tables
#define SC_SERVICE_GRADTAB      13
#define SC_SERVICE_HATCHTAB     14
#define SC_SERVICE_BITMAPTAB    15
#define SC_SERVICE_TRGRADTAB    16
#define SC_SERVICE_MARKERTAB    17
#define SC_SERVICE_DASHTAB      18
#define SC_SERVICE_NUMRULES     19

#define SC_SERVICE_DOCDEFLTS    20
#define SC_SERVICE_DRAWDEFLTS   21

#define SC_SERVICE_DOCSPRSETT   22
#define SC_SERVICE_DOCCONF      23

#define SC_SERVICE_IMAP_RECT    24
#define SC_SERVICE_IMAP_CIRC    25
#define SC_SERVICE_IMAP_POLY    26

// #100263# Support creation of GraphicObjectResolver and EmbeddedObjectResolver
#define SC_SERVICE_EXPORT_GOR   27
#define SC_SERVICE_IMPORT_GOR   28
#define SC_SERVICE_EXPORT_EOR   29
#define SC_SERVICE_IMPORT_EOR   30

#define SC_SERVICE_VALBIND      31
#define SC_SERVICE_LISTCELLBIND 32
#define SC_SERVICE_LISTSOURCE   33

#define SC_SERVICE_CELLADDRESS  34
#define SC_SERVICE_RANGEADDRESS 35

#define SC_SERVICE_SHEETDOCSET  36

// BM
#define SC_SERVICE_CHDATAPROV   37

#define SC_SERVICE_FORMULAPARS  38
#define SC_SERVICE_OPCODEMAPPER 39

#define SC_SERVICE_COUNT        40
#define SC_SERVICE_INVALID      USHRT_MAX

class ScServiceProvider
{
public:
                            // pDocShell wird nicht fuer alle Services benoetigt
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                            MakeInstance( sal_uInt16 nType, ScDocShell* pDocShell );
    static ::com::sun::star::uno::Sequence<rtl::OUString> GetAllServiceNames();
    static String           GetProviderName(sal_uInt16 nObjectType);
    static sal_uInt16       GetProviderType(const String& rServiceName);
};

#endif

<|endoftext|>


<commit_before>//
// Created by david on 2019-05-27.
//

//#define EIGEN_USE_MKL_ALL
//#define EIGEN_USE_BLAS
//#define EIGEN_USE_LAPACKE_STRICT

//#define EIGEN_DONT_VECTORIZE
//#define EIGEN_DONT_ALIGN_STATICALLY

//#define EIGEN_MAX_ALIGN_BYTES 0
//#define EIGEN_ENABLE_AVX512
#define EIGEN_UNALIGNED_VECTORIZE 0
#define EIGEN_DONT_ALIGN
#define EIGEN_MALLOC_ALREADY_ALIGNED 0

//#include <complex.h>
//#undef I

#include <Eigen/SVD>
#include <Eigen/QR>
#include <math/class_svd_wrapper.h>

double class_SVD::get_truncation_error(){
    return truncation_error;
}

void class_SVD::setThreshold(double newThreshold) {
    SVDThreshold = newThreshold;
}

/*! \brief Performs SVD on a matrix
 *  This function is defined in cpp to avoid long compilation times when having Eigen::BDCSVD included everywhere in headers.
 *  Performs rigorous checks to ensure stability of DMRG.
*   \param mat_ptr Pointer to the matrix. Supported are double * and std::complex<double> *
*   \param rows Rows of the matrix
*   \param cols Columns of the matrix
*   \param rank_max Maximum number of singular values
*   \return The U, S, and V matrices (with S as a vector) extracted from the Eigen::BCDSVD SVD object.
*/
template<typename Scalar>
std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
class_SVD::do_svd(const Scalar * mat_ptr, long rows, long cols, long rank_max){
    auto mat = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows,cols);
    if (rows <= 0)              throw std::runtime_error("SVD error: rows() == 0");
    if (cols <= 0)              throw std::runtime_error("SVD error: cols() == 0");
    if (not mat.allFinite())    throw std::runtime_error("SVD error: matrix has inf's or nan's");
    if (mat.isZero(0))          throw std::runtime_error("SVD error: matrix is all zeros");
    Eigen::BDCSVD<MatrixType<Scalar>> SVD;
    SVD.setThreshold(SVDThreshold);
    SVD.compute(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);
    long rank = std::min(SVD.rank(),rank_max);
    truncation_error = SVD.singularValues().normalized().tail(SVD.nonzeroSingularValues()-rank).squaredNorm();

    if (SVD.rank() <= 0
    or not SVD.matrixU().leftCols(rank).allFinite()
    or not SVD.singularValues().head(rank).allFinite()
    or not SVD.matrixV().leftCols(rank).allFinite() )
    {
        std::cerr   << "SVD error \n"
                    << "  SVDThreshold     = " << SVDThreshold << '\n'
                    << "  Truncation Error = " << truncation_error << '\n'
                    << "  Rank             = " << rank << '\n'
                    << "  U all finite     : " << std::boolalpha << SVD.matrixU().leftCols(rank).allFinite() << '\n'
                    << "  S all finite     : " << std::boolalpha << SVD.singularValues().head(rank).allFinite() << '\n'
                    << "  V all finite     : " << std::boolalpha << SVD.matrixV().leftCols(rank).allFinite() << '\n';
        throw std::runtime_error("SVD error:  Erroneous results");
    }

//    std::cout << "Singular values           : " << SVD.singularValues().transpose() << std::endl;
//    std::cout << "Singular values after norm: " << SVD.singularValues().head(rank).normalized().transpose() << std::endl;
//    std::cout << "Rank                      : " << rank << std::endl;
//    std::cout << "Threshold                 : " << SVDThreshold << std::endl;
//    std::cout << "Truncation error          : " << truncation_error << std::endl;

    return std::make_tuple(
            SVD.matrixU().leftCols(rank),
            SVD.singularValues().head(rank),
            SVD.matrixV().leftCols(rank).adjoint(),
            rank
            );
}

//! \relates class_SVD
//! \brief force instantiation of do_svd for type 'double'
template std::tuple<class_SVD::MatrixType<double>, class_SVD::VectorType<double>,class_SVD::MatrixType<double> , long>
class_SVD::do_svd(const double *, long, long, long);

using cplx = std::complex<double>;
//! \relates class_SVD
//! \brief force instantiation of do_svd for type 'std::complex<double>'
template std::tuple<class_SVD::MatrixType<cplx>, class_SVD::VectorType<cplx>,class_SVD::MatrixType<cplx> , long>
class_SVD::do_svd(const cplx *, long, long, long);

template<typename Scalar>
Eigen::Tensor<Scalar, 2>
class_SVD::pseudo_inverse(const Eigen::Tensor<Scalar, 2> &tensor){
    if (tensor.dimension(0) <= 0)  {throw std::runtime_error("pseudo_inverse error: Dimension is zero: tensor.dimension(0)");}
    if (tensor.dimension(1) <= 0)  {throw std::runtime_error("pseudo_inverse error: Dimension is zero: tensor.dimension(1)");}
    Eigen::Map<const MatrixType<Scalar>> mat (tensor.data(), tensor.dimension(0), tensor.dimension(1));
    return Textra::Matrix_to_Tensor2(mat.completeOrthogonalDecomposition().pseudoInverse() );
}

//! \relates class_SVD
//! \brief force instantiation of pseudo_inverse for type 'double'
template Eigen::Tensor<double, 2> class_SVD::pseudo_inverse(const Eigen::Tensor<double, 2> &tensor);
//! \relates class_SVD
//! \brief force instantiation of pseudo_inverse for type 'std::complex<double>'
template Eigen::Tensor<cplx, 2>   class_SVD::pseudo_inverse(const Eigen::Tensor<cplx  , 2> &tensor);<commit_msg>Trying my own Eigen fork to fix SVD segfault<commit_after>//
// Created by david on 2019-05-27.
//

//#define EIGEN_USE_MKL_ALL
//#define EIGEN_USE_BLAS
//#define EIGEN_USE_LAPACKE_STRICT

//#define EIGEN_DONT_VECTORIZE
//#define EIGEN_DONT_ALIGN_STATICALLY

//#define EIGEN_MAX_ALIGN_BYTES 0
//#define EIGEN_ENABLE_AVX512
//#define EIGEN_UNALIGNED_VECTORIZE 0
//#define EIGEN_DONT_ALIGN
//#define EIGEN_MALLOC_ALREADY_ALIGNED 0

//#include <complex.h>
//#undef I

//For svd debugging
#include <h5pp/h5pp.h>
#include <simulation/nmspc_settings.h>

#include <Eigen/SVD>
#include <Eigen/QR>
#include <math/class_svd_wrapper.h>

double class_SVD::get_truncation_error(){
    return truncation_error;
}

void class_SVD::setThreshold(double newThreshold) {
    SVDThreshold = newThreshold;
}

/*! \brief Performs SVD on a matrix
 *  This function is defined in cpp to avoid long compilation times when having Eigen::BDCSVD included everywhere in headers.
 *  Performs rigorous checks to ensure stability of DMRG.
*   \param mat_ptr Pointer to the matrix. Supported are double * and std::complex<double> *
*   \param rows Rows of the matrix
*   \param cols Columns of the matrix
*   \param rank_max Maximum number of singular values
*   \return The U, S, and V matrices (with S as a vector) extracted from the Eigen::BCDSVD SVD object.
*/
template<typename Scalar>
std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
class_SVD::do_svd(const Scalar * mat_ptr, long rows, long cols, long rank_max){
    auto mat = Eigen::Map<const MatrixType<Scalar>>(mat_ptr, rows,cols);
    if (rows <= 0)              throw std::runtime_error("SVD error: rows() == 0");
    if (cols <= 0)              throw std::runtime_error("SVD error: cols() == 0");
    if (not mat.allFinite())    throw std::runtime_error("SVD error: matrix has inf's or nan's");
    if (mat.isZero(0))          throw std::runtime_error("SVD error: matrix is all zeros");

    //Debugging, save matrix into h5 file
    std::string outputFilename      = "svdmatrix_" + std::to_string(settings::model::seed_init) + ".h5";
    size_t      logLevel  = 2;
    h5pp::File file(outputFilename,h5pp::AccessMode::READWRITE, h5pp::CreateMode::TRUNCATE,logLevel);

    Eigen::BDCSVD<MatrixType<Scalar>> SVD;
    SVD.setThreshold(SVDThreshold);
    SVD.compute(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);
    long rank = std::min(SVD.rank(),rank_max);
    truncation_error = SVD.singularValues().normalized().tail(SVD.nonzeroSingularValues()-rank).squaredNorm();

    if (SVD.rank() <= 0
    or not SVD.matrixU().leftCols(rank).allFinite()
    or not SVD.singularValues().head(rank).allFinite()
    or not SVD.matrixV().leftCols(rank).allFinite() )
    {
        std::cerr   << "SVD error \n"
                    << "  SVDThreshold     = " << SVDThreshold << '\n'
                    << "  Truncation Error = " << truncation_error << '\n'
                    << "  Rank             = " << rank << '\n'
                    << "  U all finite     : " << std::boolalpha << SVD.matrixU().leftCols(rank).allFinite() << '\n'
                    << "  S all finite     : " << std::boolalpha << SVD.singularValues().head(rank).allFinite() << '\n'
                    << "  V all finite     : " << std::boolalpha << SVD.matrixV().leftCols(rank).allFinite() << '\n';
        throw std::runtime_error("SVD error:  Erroneous results");
    }

//    std::cout << "Singular values           : " << SVD.singularValues().transpose() << std::endl;
//    std::cout << "Singular values after norm: " << SVD.singularValues().head(rank).normalized().transpose() << std::endl;
//    std::cout << "Rank                      : " << rank << std::endl;
//    std::cout << "Threshold                 : " << SVDThreshold << std::endl;
//    std::cout << "Truncation error          : " << truncation_error << std::endl;

    return std::make_tuple(
            SVD.matrixU().leftCols(rank),
            SVD.singularValues().head(rank),
            SVD.matrixV().leftCols(rank).adjoint(),
            rank
            );
}

//! \relates class_SVD
//! \brief force instantiation of do_svd for type 'double'
template std::tuple<class_SVD::MatrixType<double>, class_SVD::VectorType<double>,class_SVD::MatrixType<double> , long>
class_SVD::do_svd(const double *, long, long, long);

using cplx = std::complex<double>;
//! \relates class_SVD
//! \brief force instantiation of do_svd for type 'std::complex<double>'
template std::tuple<class_SVD::MatrixType<cplx>, class_SVD::VectorType<cplx>,class_SVD::MatrixType<cplx> , long>
class_SVD::do_svd(const cplx *, long, long, long);

template<typename Scalar>
Eigen::Tensor<Scalar, 2>
class_SVD::pseudo_inverse(const Eigen::Tensor<Scalar, 2> &tensor){
    if (tensor.dimension(0) <= 0)  {throw std::runtime_error("pseudo_inverse error: Dimension is zero: tensor.dimension(0)");}
    if (tensor.dimension(1) <= 0)  {throw std::runtime_error("pseudo_inverse error: Dimension is zero: tensor.dimension(1)");}
    Eigen::Map<const MatrixType<Scalar>> mat (tensor.data(), tensor.dimension(0), tensor.dimension(1));
    return Textra::Matrix_to_Tensor2(mat.completeOrthogonalDecomposition().pseudoInverse() );
}

//! \relates class_SVD
//! \brief force instantiation of pseudo_inverse for type 'double'
template Eigen::Tensor<double, 2> class_SVD::pseudo_inverse(const Eigen::Tensor<double, 2> &tensor);
//! \relates class_SVD
//! \brief force instantiation of pseudo_inverse for type 'std::complex<double>'
template Eigen::Tensor<cplx, 2>   class_SVD::pseudo_inverse(const Eigen::Tensor<cplx  , 2> &tensor);<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *             Copyright (C) 2000-2002 by the OpenSG Forum                   *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>
#include <boost/bind.hpp>

#include "OSGConfig.h"
#include "OSGGL.h"
#include "OSGGLEXT.h"
#include "OSGGLFuncProtos.h"

#include "OSGRenderBuffer.h"
#include "OSGWindow.h"
#include "OSGDrawEnv.h"
#include "OSGGLU.h"

OSG_BEGIN_NAMESPACE

UInt32 RenderBuffer::_uiFramebufferObjectExt             =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFramebufferMultiSampleExt        =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFramebufferMultiSampleCoverageNV =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFuncFramebufferRenderbuffer                =
    Window::invalidFunctionID;

UInt32  RenderBuffer::_uiFuncGenRenderbuffers                      =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncDeleteRenderbuffers                    =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncBindRenderbuffer                       =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorage                    =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorageMultiSample         =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorageMultiSampleCoverage =
    Window::invalidFunctionID;

// Documentation for this class is emited in the
// OSGRenderBufferBase.cpp file.
// To modify it, please change the .fcd file (OSGRenderBuffer.fcd) and
// regenerate the base file.

void RenderBuffer::bind(DrawEnv *pEnv, UInt32 index)
{
    Window *pWindow = pEnv->getWindow();

    pWindow->validateGLObject(getGLId(), pEnv);

    OSGGETGLFUNCBYID_GL3_ES( glFramebufferRenderbuffer,
                             osgGlFramebufferRenderbuffer,
                            _uiFuncFramebufferRenderbuffer,
                             pWindow);

    osgGlFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT,
                                 index,
                                 GL_RENDERBUFFER_EXT,
                                 pWindow->getGLObjectId(getGLId()));
}

void RenderBuffer::validate(DrawEnv *pEnv)
{
    Window *pWindow = pEnv->getWindow();

    pWindow->validateGLObject(getGLId(), pEnv);
}

/*----------------------- constructors & destructors ----------------------*/

RenderBuffer::RenderBuffer(void) :
    Inherited()
{
}

RenderBuffer::RenderBuffer(const RenderBuffer &source) :
    Inherited(source)
{
}

RenderBuffer::~RenderBuffer(void)
{
    if(getGLId() > 0)
        Window::destroyGLObject(getGLId(), 1);
}

/*----------------------------- class specific ----------------------------*/

void RenderBuffer::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

   if(ePhase == TypeObject::SystemPost)
    {
        _uiFramebufferObjectExt         =
            Window::registerExtension("GL_EXT_framebuffer_object");

        _uiFramebufferMultiSampleExt    =
            Window::registerExtension("GL_EXT_framebuffer_multisample");

        _uiFramebufferMultiSampleCoverageNV =
            Window::registerExtension("GL_NV_framebuffer_multisample_coverage");

        _uiFuncFramebufferRenderbuffer  =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glFramebufferRenderbufferEXT",
                _uiFramebufferObjectExt);

        _uiFuncGenRenderbuffers         =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glGenRenderbuffersEXT",
                _uiFramebufferObjectExt);

        _uiFuncDeleteRenderbuffers      =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glDeleteRenderbuffersEXT",
                _uiFramebufferObjectExt);

        _uiFuncRenderbufferStorage      =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glRenderbufferStorageEXT",
                _uiFramebufferObjectExt);

        _uiFuncBindRenderbuffer         =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glBindRenderbufferEXT",
                _uiFramebufferObjectExt);

        _uiFuncRenderbufferStorageMultiSample          =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glRenderbufferStorageMultisampleEXT",
                _uiFramebufferMultiSampleExt);

        _uiFuncRenderbufferStorageMultiSampleCoverage  =
            Window::registerFunction (
              OSG_DLSYM_UNDERSCORE"glRenderbufferStorageMultisampleCoverageNV",
             _uiFramebufferMultiSampleCoverageNV);
    }
}

void RenderBuffer::onCreate(const RenderBuffer *source)
{
    if(GlobalSystemState == Startup)
        return;

    setGLId(
        Window::registerGLObject(
            boost::bind(&RenderBuffer::handleGL,
                        RenderBufferMTUncountedPtr(this),
                        _1, _2, _3, _4),
            &RenderBuffer::handleDestroyGL));
}

void RenderBuffer::changed(ConstFieldMaskArg whichField,
                           UInt32            origin,
                           BitVector         details)
{
    Inherited::changed(whichField, origin, details);

    if(0x0000 != (whichField & (WidthFieldMask | HeightFieldMask)))
    {
        Window::reinitializeGLObject(getGLId());
    }
}

void RenderBuffer::dump(      UInt32    ,
                        const BitVector ) const
{
    SLOG << "Dump RenderBuffer NI" << std::endl;
}

void RenderBuffer::resizeBuffers(UInt32 uiWidth, UInt32 uiHeight)
{
    Inherited::resize(uiWidth, uiHeight);

    Window::reinitializeGLObject(getGLId());
}

GLenum RenderBuffer::getBufferFormat(void) const
{
    return _sfInternalFormat.getValue();
}

UInt32 RenderBuffer::handleGL(DrawEnv                 *pEnv,
                              UInt32                   osgid,
                              Window::GLObjectStatusE  mode,
                              UInt32                        )
{
    Window *pWindow = pEnv->getWindow();

    if(mode == Window::initialize || mode == Window::reinitialize ||
       mode == Window::needrefresh )
    {
        GLuint uiBufferId = 0;

        if(mode == Window::initialize)
        {
            OSGGETGLFUNCBYID_GL3_ES( glGenRenderbuffers,
                                     osgGlGenRenderbuffers,
                                    _uiFuncGenRenderbuffers,
                                     pWindow);

            osgGlGenRenderbuffers(1, &uiBufferId);

            pWindow->setGLObjectId(osgid, uiBufferId);
        }
        else
        {
            uiBufferId = pWindow->getGLObjectId(osgid);
        }

        OSGGETGLFUNCBYID_GL3_ES( glBindRenderbuffer,
                                 osgGlBindRenderbuffer,
                                _uiFuncBindRenderbuffer,
                                 pWindow);

        OSGGETGLFUNCBYID_GL3_ES( glRenderbufferStorage,
                                 osgGlRenderbufferStorage,
                                _uiFuncRenderbufferStorage,
                                 pWindow);

        osgGlBindRenderbuffer(GL_RENDERBUFFER_EXT, uiBufferId);

        GLenum internalFormat = getInternalFormat();

        if(internalFormat == GL_NONE && getImage() != NULL)
        {
            internalFormat = getImage()->getPixelFormat();
        }

        if(pWindow->hasExtOrVersion(
               _uiFramebufferMultiSampleCoverageNV,
               0x0300                             ) == true &&

           (_sfColorSamples   .getValue() != 0 ||
            _sfCoverageSamples.getValue() != 0  )             )
        {
            OSGGETGLFUNCBYID_EXT(
                 glRenderbufferStorageMultisampleCoverage,
                 osgGlRenderbufferStorageMultisampleCoverage,
                _uiFuncRenderbufferStorageMultiSampleCoverage,
                 pWindow);

            osgGlRenderbufferStorageMultisampleCoverage(
                GL_RENDERBUFFER_EXT,
                _sfCoverageSamples.getValue(),
                _sfColorSamples   .getValue(),
                internalFormat,
                getWidth(),
                getHeight());
        }
        else if(pWindow->hasExtOrVersion(
                    _uiFramebufferMultiSampleExt,
                     0x0300                     ) == true &&

           (_sfColorSamples   .getValue() != 0)            )
        {
            OSGGETGLFUNCBYID_GL3( glRenderbufferStorageMultisample,
                                  osgGlRenderbufferStorageMultisample,
                                 _uiFuncRenderbufferStorageMultiSample,
                                  pWindow                             );

            osgGlRenderbufferStorageMultisample(
                 GL_RENDERBUFFER_EXT,
                _sfColorSamples.getValue(),
                 internalFormat,
                 getWidth(),
                 getHeight()              );
        }
        else
        {
            osgGlRenderbufferStorage(GL_RENDERBUFFER_EXT,
                                     internalFormat,
                                     getWidth(),
                                     getHeight());
        }
    }

    return 0;
}

void RenderBuffer::handleDestroyGL(DrawEnv                 *pEnv,
                                   UInt32                   osgid,
                                   Window::GLObjectStatusE  mode)
{
    Window *pWindow = pEnv->getWindow();

    if(mode == Window::destroy)
    {
        GLuint uiBufferId =  pWindow->getGLObjectId(osgid);

        OSGGETGLFUNCBYID_GL3_ES( glDeleteRenderbuffers,
                                 osgGlDeleteRenderbuffers,
                                _uiFuncDeleteRenderbuffers,
                                 pWindow);

        osgGlDeleteRenderbuffers(1, &uiBufferId);

        pWindow->setGLObjectId(osgid, 0);
    }
    else if(mode == Window::finaldestroy)
    {
        //SWARNING << "Last texture user destroyed" << std::endl;
    }
}

void RenderBuffer::processPreDeactivate (DrawEnv *pEnv, UInt32 index)
{
    if(_sfReadBack.getValue() == true)
    {
        Image *pImg = this->getImage();

        if(pImg == NULL)
            return;

        if(pImg->getData() == NULL)
        {
            SINFO << "TextureBuffer::render: (Re)Allocating image "
                  << "for read-back."
                  << endLog;

            pImg->set(pImg->getPixelFormat(),
                      pImg->getWidth      (),
                      pImg->getHeight     (),
                      pImg->getDepth      (),
                      pImg->getMipMapCount(),
                      pImg->getFrameCount (),
                      pImg->getFrameDelay (),
                      NULL,
                      pImg->getDataType   (),
                      true,
                      pImg->getSideCount  () );
        }

        // select GL_COLORATTACHMENTn and read data into image
#ifndef OSG_OGL_ES2
        glReadBuffer(index);
#endif
        glReadPixels(0, 0,
                     pImg->getWidth      (),
                     pImg->getHeight     (),
                     pImg->getPixelFormat(),
                     pImg->getDataType   (),
                     pImg->editData      ());

#ifndef OSG_OGL_ES2
        glReadBuffer(GL_NONE);
#endif

        glErr("renderbuffer:predeactivate");
    }
}

void RenderBuffer::processPostDeactivate(DrawEnv *pEnv)
{
}

OSG_END_NAMESPACE
<commit_msg>fixed: typo<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *             Copyright (C) 2000-2002 by the OpenSG Forum                   *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>
#include <boost/bind.hpp>

#include "OSGConfig.h"
#include "OSGGL.h"
#include "OSGGLEXT.h"
#include "OSGGLFuncProtos.h"

#include "OSGRenderBuffer.h"
#include "OSGWindow.h"
#include "OSGDrawEnv.h"
#include "OSGGLU.h"

OSG_BEGIN_NAMESPACE

UInt32 RenderBuffer::_uiFramebufferObjectExt             =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFramebufferMultiSampleExt        =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFramebufferMultiSampleCoverageNV =
    Window::invalidExtensionID;

UInt32 RenderBuffer::_uiFuncFramebufferRenderbuffer                =
    Window::invalidFunctionID;

UInt32  RenderBuffer::_uiFuncGenRenderbuffers                      =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncDeleteRenderbuffers                    =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncBindRenderbuffer                       =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorage                    =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorageMultiSample         =
    Window::invalidFunctionID;

UInt32 RenderBuffer::_uiFuncRenderbufferStorageMultiSampleCoverage =
    Window::invalidFunctionID;

// Documentation for this class is emited in the
// OSGRenderBufferBase.cpp file.
// To modify it, please change the .fcd file (OSGRenderBuffer.fcd) and
// regenerate the base file.

void RenderBuffer::bind(DrawEnv *pEnv, UInt32 index)
{
    Window *pWindow = pEnv->getWindow();

    pWindow->validateGLObject(getGLId(), pEnv);

    OSGGETGLFUNCBYID_GL3_ES( glFramebufferRenderbuffer,
                             osgGlFramebufferRenderbuffer,
                            _uiFuncFramebufferRenderbuffer,
                             pWindow);

    osgGlFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT,
                                 index,
                                 GL_RENDERBUFFER_EXT,
                                 pWindow->getGLObjectId(getGLId()));
}

void RenderBuffer::validate(DrawEnv *pEnv)
{
    Window *pWindow = pEnv->getWindow();

    pWindow->validateGLObject(getGLId(), pEnv);
}

/*----------------------- constructors & destructors ----------------------*/

RenderBuffer::RenderBuffer(void) :
    Inherited()
{
}

RenderBuffer::RenderBuffer(const RenderBuffer &source) :
    Inherited(source)
{
}

RenderBuffer::~RenderBuffer(void)
{
    if(getGLId() > 0)
        Window::destroyGLObject(getGLId(), 1);
}

/*----------------------------- class specific ----------------------------*/

void RenderBuffer::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

   if(ePhase == TypeObject::SystemPost)
    {
        _uiFramebufferObjectExt         =
            Window::registerExtension("GL_EXT_framebuffer_object");

        _uiFramebufferMultiSampleExt    =
            Window::registerExtension("GL_EXT_framebuffer_multisample");

        _uiFramebufferMultiSampleCoverageNV =
            Window::registerExtension("GL_NV_framebuffer_multisample_coverage");

        _uiFuncFramebufferRenderbuffer  =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glFramebufferRenderbufferEXT",
                _uiFramebufferObjectExt);

        _uiFuncGenRenderbuffers         =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glGenRenderbuffersEXT",
                _uiFramebufferObjectExt);

        _uiFuncDeleteRenderbuffers      =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glDeleteRenderbuffersEXT",
                _uiFramebufferObjectExt);

        _uiFuncRenderbufferStorage      =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glRenderbufferStorageEXT",
                _uiFramebufferObjectExt);

        _uiFuncBindRenderbuffer         =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glBindRenderbufferEXT",
                _uiFramebufferObjectExt);

        _uiFuncRenderbufferStorageMultiSample          =
            Window::registerFunction (
                 OSG_DLSYM_UNDERSCORE"glRenderbufferStorageMultisampleEXT",
                _uiFramebufferMultiSampleExt);

        _uiFuncRenderbufferStorageMultiSampleCoverage  =
            Window::registerFunction (
              OSG_DLSYM_UNDERSCORE"glRenderbufferStorageMultisampleCoverageNV",
             _uiFramebufferMultiSampleCoverageNV);
    }
}

void RenderBuffer::onCreate(const RenderBuffer *source)
{
    if(GlobalSystemState == Startup)
        return;

    setGLId(
        Window::registerGLObject(
            boost::bind(&RenderBuffer::handleGL,
                        RenderBufferMTUncountedPtr(this),
                        _1, _2, _3, _4),
            &RenderBuffer::handleDestroyGL));
}

void RenderBuffer::changed(ConstFieldMaskArg whichField,
                           UInt32            origin,
                           BitVector         details)
{
    Inherited::changed(whichField, origin, details);

    if(0x0000 != (whichField & (WidthFieldMask | HeightFieldMask)))
    {
        Window::reinitializeGLObject(getGLId());
    }
}

void RenderBuffer::dump(      UInt32    ,
                        const BitVector ) const
{
    SLOG << "Dump RenderBuffer NI" << std::endl;
}

void RenderBuffer::resizeBuffers(UInt32 uiWidth, UInt32 uiHeight)
{
    Inherited::resize(uiWidth, uiHeight);

    Window::reinitializeGLObject(getGLId());
}

GLenum RenderBuffer::getBufferFormat(void) const
{
    return _sfInternalFormat.getValue();
}

UInt32 RenderBuffer::handleGL(DrawEnv                 *pEnv,
                              UInt32                   osgid,
                              Window::GLObjectStatusE  mode,
                              UInt32                        )
{
    Window *pWindow = pEnv->getWindow();

    if(mode == Window::initialize || mode == Window::reinitialize ||
       mode == Window::needrefresh )
    {
        GLuint uiBufferId = 0;

        if(mode == Window::initialize)
        {
            OSGGETGLFUNCBYID_GL3_ES( glGenRenderbuffers,
                                     osgGlGenRenderbuffers,
                                    _uiFuncGenRenderbuffers,
                                     pWindow);

            osgGlGenRenderbuffers(1, &uiBufferId);

            pWindow->setGLObjectId(osgid, uiBufferId);
        }
        else
        {
            uiBufferId = pWindow->getGLObjectId(osgid);
        }

        OSGGETGLFUNCBYID_GL3_ES( glBindRenderbuffer,
                                 osgGlBindRenderbuffer,
                                _uiFuncBindRenderbuffer,
                                 pWindow);

        OSGGETGLFUNCBYID_GL3_ES( glRenderbufferStorage,
                                 osgGlRenderbufferStorage,
                                _uiFuncRenderbufferStorage,
                                 pWindow);

        osgGlBindRenderbuffer(GL_RENDERBUFFER_EXT, uiBufferId);

        GLenum internalFormat = getInternalFormat();

        if(internalFormat == GL_NONE && getImage() != NULL)
        {
            internalFormat = getImage()->getPixelFormat();
        }

        if(pWindow->hasExtension(_uiFramebufferMultiSampleCoverageNV) == true &&

           (_sfColorSamples   .getValue() != 0 ||
            _sfCoverageSamples.getValue() != 0  )                         )
        {
            OSGGETGLFUNCBYID_EXT(
                 glRenderbufferStorageMultisampleCoverage,
                 osgGlRenderbufferStorageMultisampleCoverage,
                _uiFuncRenderbufferStorageMultiSampleCoverage,
                 pWindow);

            osgGlRenderbufferStorageMultisampleCoverage(
                GL_RENDERBUFFER_EXT,
                _sfCoverageSamples.getValue(),
                _sfColorSamples   .getValue(),
                internalFormat,
                getWidth(),
                getHeight());
        }
        else if(pWindow->hasExtOrVersion(
                    _uiFramebufferMultiSampleExt,
                     0x0300                     ) == true &&

           (_sfColorSamples   .getValue() != 0)            )
        {
            OSGGETGLFUNCBYID_GL3( glRenderbufferStorageMultisample,
                                  osgGlRenderbufferStorageMultisample,
                                 _uiFuncRenderbufferStorageMultiSample,
                                  pWindow                             );

            osgGlRenderbufferStorageMultisample(
                 GL_RENDERBUFFER_EXT,
                _sfColorSamples.getValue(),
                 internalFormat,
                 getWidth(),
                 getHeight()              );
        }
        else
        {
            osgGlRenderbufferStorage(GL_RENDERBUFFER_EXT,
                                     internalFormat,
                                     getWidth(),
                                     getHeight());
        }
    }

    return 0;
}

void RenderBuffer::handleDestroyGL(DrawEnv                 *pEnv,
                                   UInt32                   osgid,
                                   Window::GLObjectStatusE  mode)
{
    Window *pWindow = pEnv->getWindow();

    if(mode == Window::destroy)
    {
        GLuint uiBufferId =  pWindow->getGLObjectId(osgid);

        OSGGETGLFUNCBYID_GL3_ES( glDeleteRenderbuffers,
                                 osgGlDeleteRenderbuffers,
                                _uiFuncDeleteRenderbuffers,
                                 pWindow);

        osgGlDeleteRenderbuffers(1, &uiBufferId);

        pWindow->setGLObjectId(osgid, 0);
    }
    else if(mode == Window::finaldestroy)
    {
        //SWARNING << "Last texture user destroyed" << std::endl;
    }
}

void RenderBuffer::processPreDeactivate (DrawEnv *pEnv, UInt32 index)
{
    if(_sfReadBack.getValue() == true)
    {
        Image *pImg = this->getImage();

        if(pImg == NULL)
            return;

        if(pImg->getData() == NULL)
        {
            SINFO << "TextureBuffer::render: (Re)Allocating image "
                  << "for read-back."
                  << endLog;

            pImg->set(pImg->getPixelFormat(),
                      pImg->getWidth      (),
                      pImg->getHeight     (),
                      pImg->getDepth      (),
                      pImg->getMipMapCount(),
                      pImg->getFrameCount (),
                      pImg->getFrameDelay (),
                      NULL,
                      pImg->getDataType   (),
                      true,
                      pImg->getSideCount  () );
        }

        // select GL_COLORATTACHMENTn and read data into image
#ifndef OSG_OGL_ES2
        glReadBuffer(index);
#endif
        glReadPixels(0, 0,
                     pImg->getWidth      (),
                     pImg->getHeight     (),
                     pImg->getPixelFormat(),
                     pImg->getDataType   (),
                     pImg->editData      ());

#ifndef OSG_OGL_ES2
        glReadBuffer(GL_NONE);
#endif

        glErr("renderbuffer:predeactivate");
    }
}

void RenderBuffer::processPostDeactivate(DrawEnv *pEnv)
{
}

OSG_END_NAMESPACE
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "DebugOperatorNew.h"

#include "NaaliMainWindow.h"
#include "Framework.h"
#include "ConfigurationManager.h"

#include <QCloseEvent>
#include <QDesktopWidget>
#include <QApplication>

#include <utility>
#include <iostream>

#include "MemoryLeakCheck.h"

using namespace std;

NaaliMainWindow::NaaliMainWindow(Foundation::Framework *owner_)
:owner(owner_)
{
}

int NaaliMainWindow::DesktopWidth()
{
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
    {
        cerr << "Error: QApplication::desktop() returned null!";
        return 1024; // Just guess some value for desktop width.
    }
    int width = 0;
    for(int i = 0; i < desktop->screenCount(); ++i)
        width += desktop->screenGeometry(i).width();

    return width;
}

int NaaliMainWindow::DesktopHeight()
{
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
    {
        cerr << "Error: QApplication::desktop() returned null!";
        return 768; // Just guess some value for desktop height.
    }
    return desktop->screenGeometry().height();
}

void NaaliMainWindow::LoadWindowSettingsFromFile()
{
    int width = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_width", 800);
    int height = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_height", 600);
    int windowX = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_left", -1);
    int windowY = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_top", -1);
    bool maximized = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_maximized", false);
    bool fullscreen = owner->GetDefaultConfig().DeclareSetting("MainWindow", "fullscreen", false);

    width = max(1, min(DesktopWidth(), width));
    height = max(1, min(DesktopHeight(), height));
    windowX = max(0, min(DesktopWidth()-width, windowX));
    windowY = max(25, min(DesktopHeight()-height, windowY));

    resize(width, height);
    move(windowX, windowY);
}

void NaaliMainWindow::SaveWindowSettingsToFile()
{
    // The values (0, 25) and (-50, -20) below serve to artificially limit the main window positioning into awkward places.
    int windowX = max(0, min(DesktopWidth()-50, geometry().x()));
    int windowY = max(25, min(DesktopHeight()-20, geometry().y()));
    int width = max(1, min(DesktopWidth()-windowX, size().width()));
    int height = max(1, min(DesktopHeight()-windowY, size().height()));

    // If we are in windowed mode, store the window rectangle for next run.
    if (!isMaximized() && !isFullScreen())
    {
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_width", width);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_height", height);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_left", windowX);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_top", windowY);
    }
    owner->GetDefaultConfig().SetSetting("MainWindow", "window_maximized", isMaximized());
    owner->GetDefaultConfig().SetSetting("MainWindow", "fullscreen", isFullScreen());
}

void NaaliMainWindow::closeEvent(QCloseEvent *e)
{
    emit WindowCloseEvent();
    e->ignore();
}

void NaaliMainWindow::resizeEvent(QResizeEvent *e)
{
    emit WindowResizeEvent(width(), height());
}<commit_msg>Adding back main window title and version number to it from config.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "DebugOperatorNew.h"

#include "NaaliMainWindow.h"
#include "Framework.h"
#include "ConfigurationManager.h"

#include <QCloseEvent>
#include <QDesktopWidget>
#include <QApplication>
#include <QIcon>

#include <utility>
#include <iostream>

#include "MemoryLeakCheck.h"

using namespace std;

NaaliMainWindow::NaaliMainWindow(Foundation::Framework *owner_)
:owner(owner_)
{
}

int NaaliMainWindow::DesktopWidth()
{
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
    {
        cerr << "Error: QApplication::desktop() returned null!";
        return 1024; // Just guess some value for desktop width.
    }
    int width = 0;
    for(int i = 0; i < desktop->screenCount(); ++i)
        width += desktop->screenGeometry(i).width();

    return width;
}

int NaaliMainWindow::DesktopHeight()
{
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
    {
        cerr << "Error: QApplication::desktop() returned null!";
        return 768; // Just guess some value for desktop height.
    }
    return desktop->screenGeometry().height();
}

void NaaliMainWindow::LoadWindowSettingsFromFile()
{
    int width = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_width", 800);
    int height = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_height", 600);
    int windowX = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_left", -1);
    int windowY = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_top", -1);
    bool maximized = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_maximized", false);
    bool fullscreen = owner->GetDefaultConfig().DeclareSetting("MainWindow", "fullscreen", false);

    std::string title = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "window_title");
    std::string version_major = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "version_major");
    std::string version_minor = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "version_minor");

    setWindowTitle(QString("%1 %2.%3").arg(title.c_str(), version_major.c_str(), version_minor.c_str()));

    width = max(1, min(DesktopWidth(), width));
    height = max(1, min(DesktopHeight(), height));
    windowX = max(0, min(DesktopWidth()-width, windowX));
    windowY = max(25, min(DesktopHeight()-height, windowY));

    resize(width, height);
    move(windowX, windowY);
}

void NaaliMainWindow::SaveWindowSettingsToFile()
{
    // The values (0, 25) and (-50, -20) below serve to artificially limit the main window positioning into awkward places.
    int windowX = max(0, min(DesktopWidth()-50, geometry().x()));
    int windowY = max(25, min(DesktopHeight()-20, geometry().y()));
    int width = max(1, min(DesktopWidth()-windowX, size().width()));
    int height = max(1, min(DesktopHeight()-windowY, size().height()));

    // If we are in windowed mode, store the window rectangle for next run.
    if (!isMaximized() && !isFullScreen())
    {
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_width", width);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_height", height);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_left", windowX);
        owner->GetDefaultConfig().SetSetting("MainWindow", "window_top", windowY);
    }
    owner->GetDefaultConfig().SetSetting("MainWindow", "window_maximized", isMaximized());
    owner->GetDefaultConfig().SetSetting("MainWindow", "fullscreen", isFullScreen());
}

void NaaliMainWindow::closeEvent(QCloseEvent *e)
{
    emit WindowCloseEvent();
    e->ignore();
}

void NaaliMainWindow::resizeEvent(QResizeEvent *e)
{
    emit WindowResizeEvent(width(), height());
}<|endoftext|>


<commit_before>//
//  NSolver::assemble_system.cpp
//
//  Created by Lei Qiao on 15/8/9.
//  A work based on deal.II tutorial step-33.
//

#include <NSolver/solver/NSolver.h>

namespace NSFEMSolver
{
  using namespace dealii;

  // @sect4{NSolver::assemble_system}
  //
  // This and the following two functions are the meat of this program: They
  // assemble the linear system that results from applying Newton's method to
  // the nonlinear system of conservation equations.
  //
  // This first function puts all of the assembly pieces together in a routine
  // that dispatches the correct piece for each cell/face.  The actual
  // implementation of the assembly on these objects is done in the following
  // functions.
  //
  // At the top of the function we do the usual housekeeping: allocate
  // FEValues, FEFaceValues, and FESubfaceValues objects necessary to do the
  // integrations on cells, faces, and subfaces (in case of adjoining cells on
  // different refinement levels). Note that we don't need all information
  // (like values, gradients, or real locations of quadrature points) for all
  // of these objects, so we only let the FEValues classes whatever is
  // actually necessary by specifying the minimal set of UpdateFlags. For
  // example, when using a FEFaceValues object for the neighboring cell we
  // only need the shape values: Given a specific face, the quadrature points
  // and JxW values are the same as for the current cells, and
  // the normal vectors are known to be the negative of the normal vectors of
  // the current cell.
  template <int dim>
  void NSolver<dim>::assemble_system()
  {
    const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;

    std::vector<types::global_dof_index> dof_indices (dofs_per_cell);
    std::vector<types::global_dof_index> dof_indices_neighbor (dofs_per_cell);

    //MMS: update quadrature points for evaluation of manufactured solution.
    const UpdateFlags update_flags               = update_values
                                                   | update_gradients
                                                   | update_q_points
                                                   | update_JxW_values
                                                   | update_quadrature_points;
    const UpdateFlags face_update_flags          = update_values
                                                   | update_gradients
                                                   | update_q_points
                                                   | update_JxW_values
                                                   | update_normal_vectors
                                                   | update_quadrature_points;
    const UpdateFlags neighbor_face_update_flags = update_values;

    FEValues<dim>        fe_v (*mapping_ptr, fe, quadrature,
                               update_flags);
    FEFaceValues<dim>    fe_v_face (*mapping_ptr, fe, face_quadrature,
                                    face_update_flags);
    FESubfaceValues<dim> fe_v_subface (*mapping_ptr, fe, face_quadrature,
                                       face_update_flags);
    FEFaceValues<dim>    fe_v_face_neighbor (*mapping_ptr, fe, face_quadrature,
                                             neighbor_face_update_flags);
    FESubfaceValues<dim> fe_v_subface_neighbor (*mapping_ptr, fe, face_quadrature,
                                                neighbor_face_update_flags);

    // Then loop over all cells, initialize the FEValues object for the current
    // cell and call the function that assembles the problem on this cell.
    typename DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
    for (; cell!=endc; ++cell)
      if (cell->is_locally_owned())
        {
          fe_v.reinit (cell);
          cell->get_dof_indices (dof_indices);

          assemble_cell_term (fe_v, dof_indices);

          // Then loop over all the faces of this cell.  If a face is part of
          // the external boundary, then assemble boundary conditions there (the
          // fifth argument to assemble_face_terms indicates
          // whether we are working on an external or internal face; if it is an
          // external face, the fourth argument denoting the degrees of freedom
          // indices of the neighbor is ignored, so we pass an empty vector):
          for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no)
            {
              const bool face_is_at_boundary = cell->at_boundary (face_no);
              FEFaceValuesBase<dim> *ptr_fe_v_face_this = 0;
              FEFaceValuesBase<dim> *ptr_fe_v_face_neighbor = 0;
              unsigned int boundary_id = numbers::invalid_unsigned_int;
              double face_diameter = -1.0;
              bool need_to_compute_face_flux = true;

              // Loop through all sub components of current face and set proper parameters for
              // function assemble_face_term().
              // The following statement means, if the face has children, loop through all of
              // its children; if not, treat itself as its only child.
              const unsigned int n_subfaces =
                cell->face (face_no)->has_children() ?
                cell->face (face_no)->n_children() : 1;
              for (unsigned int subface_no=0; subface_no < n_subfaces; ++subface_no)
                {
                  if (face_is_at_boundary)
                    {
                      need_to_compute_face_flux = true;

                      fe_v_face.reinit (cell, face_no);
                      ptr_fe_v_face_this     = &fe_v_face;
                      ptr_fe_v_face_neighbor = ptr_fe_v_face_this;
                      std::fill (dof_indices_neighbor.begin(),
                                 dof_indices_neighbor.end(),
                                 numbers::invalid_unsigned_int);
                      boundary_id = cell->face (face_no)->boundary_id();
                      face_diameter = cell->face (face_no)->diameter();
                    }

                  // The alternative is that we are dealing with an internal face. There
                  // are two cases that we need to distinguish: that this is a normal
                  // face between two cells at the same refinement level, and that it is
                  // a face between two cells of the different refinement levels.
                  //
                  // In the first case, there is nothing we need to do: we are using a
                  // continuous finite element, and face terms do not appear in the
                  // bilinear form in this case. The second case usually does not lead
                  // to face terms either if we enforce hanging node constraints
                  // strongly (as in all previous tutorial programs so far whenever we
                  // used continuous finite elements -- this enforcement is done by the
                  // ConstraintMatrix class together with
                  // DoFTools::make_hanging_node_constraints). In the current program,
                  // however, we opt to enforce continuity weakly at faces between cells
                  // of different refinement level, for two reasons: (i) because we can,
                  // and more importantly (ii) because we would have to thread the
                  // automatic differentiation we use to compute the elements of the
                  // Newton matrix from the residual through the operations of the
                  // ConstraintMatrix class. This would be possible, but is not trivial,
                  // and so we choose this alternative approach.
                  //
                  // What needs to be decided is which side of an interface between two
                  // cells of different refinement level we are sitting on.
                  //
                  // Let's take the case where the neighbor is more refined first. We
                  // then have to loop over the children of the face of the current cell
                  // and integrate on each of them. We sprinkle a couple of assertions
                  // into the code to ensure that our reasoning trying to figure out
                  // which of the neighbor's children's faces coincides with a given
                  // subface of the current cell's faces is correct -- a bit of
                  // defensive programming never hurts.
                  //
                  // We then call the function that integrates over faces; since this is
                  // an internal face, the fifth argument is false, and the sixth one is
                  // ignored so we pass an invalid value again:
                  else
                    {
                      const typename DoFHandler<dim>::cell_iterator
                      neighbor = cell->neighbor (face_no);

                      // Make sure not subtracting two unsigned integers.
                      const int this_cell_level = cell->level();
                      const int neighbor_active_cell_level = neighbor->level() + neighbor->has_children();
                      switch (this_cell_level-neighbor_active_cell_level)
                        {
                        case -1:
                        {
                          need_to_compute_face_flux = true;
                          // This cell is one level coarser than neighbor. So we have several subfaces
                          // to deal with. The outer loop will take care of the walking.
                          const unsigned int neighbor_face_no = cell->neighbor_of_neighbor (face_no);

                          const typename DoFHandler<dim>::active_cell_iterator neighbor_child =
                            cell->neighbor_child_on_subface (face_no, subface_no);

                          // Make sure we are talking about the same subface.
                          Assert (neighbor_child->face (neighbor_face_no) ==
                                  cell->face (face_no)->child (subface_no),
                                  ExcInternalError());

                          fe_v_subface.reinit (cell, face_no, subface_no);
                          fe_v_face_neighbor.reinit (neighbor_child, neighbor_face_no);
                          ptr_fe_v_face_this     = &fe_v_subface;
                          ptr_fe_v_face_neighbor = &fe_v_face_neighbor;

                          neighbor_child->get_dof_indices (dof_indices_neighbor);

                          boundary_id = numbers::invalid_unsigned_int;
                          face_diameter = neighbor_child->face (neighbor_face_no)->diameter();
                          break;
                        }
                        case 0:
                        {
                          // This cell and neighbor cell are at same level
                          need_to_compute_face_flux = false;
                          break;
                        }
                        case 1:
                        {
                          need_to_compute_face_flux = true;
                          // This cell is one level finer than neighbor. So we are now
                          // on a subface of neighbor cell.
                          const std::pair<unsigned int, unsigned int>
                          faceno_subfaceno = cell->neighbor_of_coarser_neighbor (face_no);
                          const unsigned int &neighbor_face_no    = faceno_subfaceno.first;
                          const unsigned int &neighbor_subface_no = faceno_subfaceno.second;

                          // Make sure we are talking about the same subface.
                          Assert (neighbor->neighbor_child_on_subface (neighbor_face_no,
                                                                       neighbor_subface_no)
                                  == cell,
                                  ExcInternalError());

                          fe_v_face.reinit (cell, face_no);
                          fe_v_subface_neighbor.reinit (neighbor,
                                                        neighbor_face_no,
                                                        neighbor_subface_no);
                          ptr_fe_v_face_this     = &fe_v_face;
                          ptr_fe_v_face_neighbor = &fe_v_subface_neighbor;

                          neighbor->get_dof_indices (dof_indices_neighbor);

                          boundary_id = numbers::invalid_unsigned_int;
                          face_diameter = cell->face (face_no)->diameter();
                          break;
                        }
                        default:
                        {
                          Assert (false,
                                  ExcMessage ("Refinement level difference between face neighbor cells can't greater than 1."));
                          break;
                        }
                        } // End switch level difference
                    } // End if (face_is_at_boundary) ... else.
                  if (need_to_compute_face_flux)
                    {
                      assemble_face_term (face_no,
                                          *ptr_fe_v_face_this,
                                          *ptr_fe_v_face_neighbor,
                                          dof_indices,
                                          dof_indices_neighbor,
                                          face_is_at_boundary,
                                          boundary_id,
                                          face_diameter);
                    }
                } // End for all subfaces
            } // End for all faces
        } // End for all active cells
    if (parameters->laplacian_continuation > 0.0 &&
        continuation_coeff_laplacian > 0.0)
      {
        apply_laplacian_continuation();
      }
    // After all this assembling, notify the Trilinos matrix object that the
    // matrix is done:
    system_matrix.compress (VectorOperation::add);
    right_hand_side.compress (VectorOperation::add);
    physical_residual.compress (VectorOperation::add);

    return;
  }

#include "NSolver.inst"
}
<commit_msg>always call apply_laplacian_continuation()<commit_after>//
//  NSolver::assemble_system.cpp
//
//  Created by Lei Qiao on 15/8/9.
//  A work based on deal.II tutorial step-33.
//

#include <NSolver/solver/NSolver.h>

namespace NSFEMSolver
{
  using namespace dealii;

  // @sect4{NSolver::assemble_system}
  //
  // This and the following two functions are the meat of this program: They
  // assemble the linear system that results from applying Newton's method to
  // the nonlinear system of conservation equations.
  //
  // This first function puts all of the assembly pieces together in a routine
  // that dispatches the correct piece for each cell/face.  The actual
  // implementation of the assembly on these objects is done in the following
  // functions.
  //
  // At the top of the function we do the usual housekeeping: allocate
  // FEValues, FEFaceValues, and FESubfaceValues objects necessary to do the
  // integrations on cells, faces, and subfaces (in case of adjoining cells on
  // different refinement levels). Note that we don't need all information
  // (like values, gradients, or real locations of quadrature points) for all
  // of these objects, so we only let the FEValues classes whatever is
  // actually necessary by specifying the minimal set of UpdateFlags. For
  // example, when using a FEFaceValues object for the neighboring cell we
  // only need the shape values: Given a specific face, the quadrature points
  // and JxW values are the same as for the current cells, and
  // the normal vectors are known to be the negative of the normal vectors of
  // the current cell.
  template <int dim>
  void NSolver<dim>::assemble_system()
  {
    const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;

    std::vector<types::global_dof_index> dof_indices (dofs_per_cell);
    std::vector<types::global_dof_index> dof_indices_neighbor (dofs_per_cell);

    //MMS: update quadrature points for evaluation of manufactured solution.
    const UpdateFlags update_flags               = update_values
                                                   | update_gradients
                                                   | update_q_points
                                                   | update_JxW_values
                                                   | update_quadrature_points;
    const UpdateFlags face_update_flags          = update_values
                                                   | update_gradients
                                                   | update_q_points
                                                   | update_JxW_values
                                                   | update_normal_vectors
                                                   | update_quadrature_points;
    const UpdateFlags neighbor_face_update_flags = update_values;

    FEValues<dim>        fe_v (*mapping_ptr, fe, quadrature,
                               update_flags);
    FEFaceValues<dim>    fe_v_face (*mapping_ptr, fe, face_quadrature,
                                    face_update_flags);
    FESubfaceValues<dim> fe_v_subface (*mapping_ptr, fe, face_quadrature,
                                       face_update_flags);
    FEFaceValues<dim>    fe_v_face_neighbor (*mapping_ptr, fe, face_quadrature,
                                             neighbor_face_update_flags);
    FESubfaceValues<dim> fe_v_subface_neighbor (*mapping_ptr, fe, face_quadrature,
                                                neighbor_face_update_flags);

    // Then loop over all cells, initialize the FEValues object for the current
    // cell and call the function that assembles the problem on this cell.
    typename DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
    for (; cell!=endc; ++cell)
      if (cell->is_locally_owned())
        {
          fe_v.reinit (cell);
          cell->get_dof_indices (dof_indices);

          assemble_cell_term (fe_v, dof_indices);

          // Then loop over all the faces of this cell.  If a face is part of
          // the external boundary, then assemble boundary conditions there (the
          // fifth argument to assemble_face_terms indicates
          // whether we are working on an external or internal face; if it is an
          // external face, the fourth argument denoting the degrees of freedom
          // indices of the neighbor is ignored, so we pass an empty vector):
          for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no)
            {
              const bool face_is_at_boundary = cell->at_boundary (face_no);
              FEFaceValuesBase<dim> *ptr_fe_v_face_this = 0;
              FEFaceValuesBase<dim> *ptr_fe_v_face_neighbor = 0;
              unsigned int boundary_id = numbers::invalid_unsigned_int;
              double face_diameter = -1.0;
              bool need_to_compute_face_flux = true;

              // Loop through all sub components of current face and set proper parameters for
              // function assemble_face_term().
              // The following statement means, if the face has children, loop through all of
              // its children; if not, treat itself as its only child.
              const unsigned int n_subfaces =
                cell->face (face_no)->has_children() ?
                cell->face (face_no)->n_children() : 1;
              for (unsigned int subface_no=0; subface_no < n_subfaces; ++subface_no)
                {
                  if (face_is_at_boundary)
                    {
                      need_to_compute_face_flux = true;

                      fe_v_face.reinit (cell, face_no);
                      ptr_fe_v_face_this     = &fe_v_face;
                      ptr_fe_v_face_neighbor = ptr_fe_v_face_this;
                      std::fill (dof_indices_neighbor.begin(),
                                 dof_indices_neighbor.end(),
                                 numbers::invalid_unsigned_int);
                      boundary_id = cell->face (face_no)->boundary_id();
                      face_diameter = cell->face (face_no)->diameter();
                    }

                  // The alternative is that we are dealing with an internal face. There
                  // are two cases that we need to distinguish: that this is a normal
                  // face between two cells at the same refinement level, and that it is
                  // a face between two cells of the different refinement levels.
                  //
                  // In the first case, there is nothing we need to do: we are using a
                  // continuous finite element, and face terms do not appear in the
                  // bilinear form in this case. The second case usually does not lead
                  // to face terms either if we enforce hanging node constraints
                  // strongly (as in all previous tutorial programs so far whenever we
                  // used continuous finite elements -- this enforcement is done by the
                  // ConstraintMatrix class together with
                  // DoFTools::make_hanging_node_constraints). In the current program,
                  // however, we opt to enforce continuity weakly at faces between cells
                  // of different refinement level, for two reasons: (i) because we can,
                  // and more importantly (ii) because we would have to thread the
                  // automatic differentiation we use to compute the elements of the
                  // Newton matrix from the residual through the operations of the
                  // ConstraintMatrix class. This would be possible, but is not trivial,
                  // and so we choose this alternative approach.
                  //
                  // What needs to be decided is which side of an interface between two
                  // cells of different refinement level we are sitting on.
                  //
                  // Let's take the case where the neighbor is more refined first. We
                  // then have to loop over the children of the face of the current cell
                  // and integrate on each of them. We sprinkle a couple of assertions
                  // into the code to ensure that our reasoning trying to figure out
                  // which of the neighbor's children's faces coincides with a given
                  // subface of the current cell's faces is correct -- a bit of
                  // defensive programming never hurts.
                  //
                  // We then call the function that integrates over faces; since this is
                  // an internal face, the fifth argument is false, and the sixth one is
                  // ignored so we pass an invalid value again:
                  else
                    {
                      const typename DoFHandler<dim>::cell_iterator
                      neighbor = cell->neighbor (face_no);

                      // Make sure not subtracting two unsigned integers.
                      const int this_cell_level = cell->level();
                      const int neighbor_active_cell_level = neighbor->level() + neighbor->has_children();
                      switch (this_cell_level-neighbor_active_cell_level)
                        {
                        case -1:
                        {
                          need_to_compute_face_flux = true;
                          // This cell is one level coarser than neighbor. So we have several subfaces
                          // to deal with. The outer loop will take care of the walking.
                          const unsigned int neighbor_face_no = cell->neighbor_of_neighbor (face_no);

                          const typename DoFHandler<dim>::active_cell_iterator neighbor_child =
                            cell->neighbor_child_on_subface (face_no, subface_no);

                          // Make sure we are talking about the same subface.
                          Assert (neighbor_child->face (neighbor_face_no) ==
                                  cell->face (face_no)->child (subface_no),
                                  ExcInternalError());

                          fe_v_subface.reinit (cell, face_no, subface_no);
                          fe_v_face_neighbor.reinit (neighbor_child, neighbor_face_no);
                          ptr_fe_v_face_this     = &fe_v_subface;
                          ptr_fe_v_face_neighbor = &fe_v_face_neighbor;

                          neighbor_child->get_dof_indices (dof_indices_neighbor);

                          boundary_id = numbers::invalid_unsigned_int;
                          face_diameter = neighbor_child->face (neighbor_face_no)->diameter();
                          break;
                        }
                        case 0:
                        {
                          // This cell and neighbor cell are at same level
                          need_to_compute_face_flux = false;
                          break;
                        }
                        case 1:
                        {
                          need_to_compute_face_flux = true;
                          // This cell is one level finer than neighbor. So we are now
                          // on a subface of neighbor cell.
                          const std::pair<unsigned int, unsigned int>
                          faceno_subfaceno = cell->neighbor_of_coarser_neighbor (face_no);
                          const unsigned int &neighbor_face_no    = faceno_subfaceno.first;
                          const unsigned int &neighbor_subface_no = faceno_subfaceno.second;

                          // Make sure we are talking about the same subface.
                          Assert (neighbor->neighbor_child_on_subface (neighbor_face_no,
                                                                       neighbor_subface_no)
                                  == cell,
                                  ExcInternalError());

                          fe_v_face.reinit (cell, face_no);
                          fe_v_subface_neighbor.reinit (neighbor,
                                                        neighbor_face_no,
                                                        neighbor_subface_no);
                          ptr_fe_v_face_this     = &fe_v_face;
                          ptr_fe_v_face_neighbor = &fe_v_subface_neighbor;

                          neighbor->get_dof_indices (dof_indices_neighbor);

                          boundary_id = numbers::invalid_unsigned_int;
                          face_diameter = cell->face (face_no)->diameter();
                          break;
                        }
                        default:
                        {
                          Assert (false,
                                  ExcMessage ("Refinement level difference between face neighbor cells can't greater than 1."));
                          break;
                        }
                        } // End switch level difference
                    } // End if (face_is_at_boundary) ... else.
                  if (need_to_compute_face_flux)
                    {
                      assemble_face_term (face_no,
                                          *ptr_fe_v_face_this,
                                          *ptr_fe_v_face_neighbor,
                                          dof_indices,
                                          dof_indices_neighbor,
                                          face_is_at_boundary,
                                          boundary_id,
                                          face_diameter);
                    }
                } // End for all subfaces
            } // End for all faces
        } // End for all active cells
    apply_laplacian_continuation();
    // After all this assembling, notify the Trilinos matrix object that the
    // matrix is done:
    system_matrix.compress (VectorOperation::add);
    right_hand_side.compress (VectorOperation::add);
    physical_residual.compress (VectorOperation::add);

    return;
  }

#include "NSolver.inst"
}
<|endoftext|>


<commit_before>//
// Created by cheyulin on 12/20/16.
//

#include <boost/graph/adjacency_list.hpp>
#include <iostream>

#include "../../Utilities/pretty_print.h"

using namespace std;
using namespace boost;

enum vertex_location_t {
    vertex_location
};
enum edge_length_t {
    edge_length
};
enum graph_notes_t {
    graph_notes
};

namespace boost {
    BOOST_INSTALL_PROPERTY(vertex, location);
    BOOST_INSTALL_PROPERTY(edge, length);
    BOOST_INSTALL_PROPERTY(graph, notes);
}

using VertexProperties=property<vertex_name_t, string, property<vertex_location_t,
        array<int, 2>, property<vertex_index_t, int>>>;
using EdgeProperties=property<edge_length_t, double>;
using GraphProperties=property<graph_name_t, string, property<graph_notes_t, string>>;
using Graph=adjacency_list<setS, vecS, undirectedS, VertexProperties, EdgeProperties, GraphProperties>;
using GraphWithEdgeProperty=adjacency_list<setS, vecS, undirectedS, no_property, EdgeProperties>;

void DemoSimpleGraph() {
    cout << "Demo Simple Graph Property:" << endl;

    Graph g;
    property_map<Graph, vertex_location_t>::type vertex_location_map = boost::get(vertex_location, g);
    property_map<Graph, vertex_index_t>::type vertex_index_map = boost::get(vertex_index, g);
    property_map<Graph, edge_length_t>::type edge_length_map = boost::get(edge_length, g);

    graph_traits<Graph>::vertex_descriptor a, b, c;
    graph_traits<Graph>::edge_descriptor ed;

    a = add_vertex(g);
    b = add_vertex(g);
    c = add_vertex(g);
    vertex_location_map[b][0] = 1;
    vertex_location_map[b][1] = 1;
    vertex_location_map[c][0] = 3;
    vertex_location_map[c][1] = 3;

    bool inserted_flag;
    std::tie(ed, inserted_flag) = add_edge(a, b, g);
    edge_length_map[ed] = 1.2;
    std::tie(ed, inserted_flag) = add_edge(a, c, g);
    edge_length_map[ed] = 1.3;
    std::tie(ed, inserted_flag) = add_edge(b, c, g);
    edge_length_map[ed] = 1.4;

    cout << "degree of a:" << degree(a, g) << endl;
    for (auto vp = vertices(g); vp.first != vp.second; ++vp.first) {
        cout << "vertex index:" << vertex_index_map[*vp.first] << endl;
        cout << "vertex location :" << vertex_location_map[*vp.first] << endl;
    }

    for (auto ep = edges(g); ep.first != ep.second; ++ep.first) {
        cout << "edge length:" << edge_length_map[*ep.first] << endl;
    }
}

void DemoGraphWithEdgeProperty() {
    cout << "\nDemo Edge Property:" << endl;
    bool inserted_flag;
    graph_traits<GraphWithEdgeProperty>::vertex_descriptor aa, bb, cc;
    GraphWithEdgeProperty graph;
    aa = add_vertex(graph);
    bb = add_vertex(graph);
    add_vertex(graph);
    property_map<GraphWithEdgeProperty, edge_length_t>::type edge_length_map2 = boost::get(edge_length, graph);
    graph_traits<GraphWithEdgeProperty>::edge_descriptor ed2;

    std::tie(ed2, inserted_flag) = add_edge(aa, bb, graph);
    property_map<Graph, edge_length_t>::type edge_length_map = boost::get(edge_length, graph);
    edge_length_map[ed2] = 1.55;
    cout << edge_length_map[ed2] << endl;
}

int main() {
    DemoSimpleGraph();
    DemoGraphWithEdgeProperty();
}<commit_msg>update bgl demo codes<commit_after>//
// Created by cheyulin on 12/20/16.
//

#include <iostream>

#include <boost/graph/adjacency_list.hpp>

#include "../../Utilities/pretty_print.h"

using namespace std;
using namespace boost;

enum vertex_location_t {
    vertex_location
};
enum edge_length_t {
    edge_length
};
enum graph_note_t {
    graph_note
};

namespace boost {
    BOOST_INSTALL_PROPERTY(vertex, location);
    BOOST_INSTALL_PROPERTY(edge, length);
    BOOST_INSTALL_PROPERTY(graph, note);
}

using VertexProperties=property<vertex_name_t, string, property<vertex_location_t, array<int, 2>, property<vertex_index_t, int>>>;
using EdgeProperties=property<edge_length_t, double>;
using GraphProperties=property<graph_name_t, string, property<graph_note_t, string>>;

void DemoComplexGraph() {
    cout << "Demo Complex Graph Property:" << endl;
    using Graph=adjacency_list<setS, vecS, undirectedS, VertexProperties, EdgeProperties, GraphProperties>;
    Graph g;
    property_map<Graph, vertex_location_t>::type vertex_location_map = boost::get(vertex_location, g);
    property_map<Graph, vertex_index_t>::type vertex_index_map = boost::get(vertex_index, g);
    property_map<Graph, edge_length_t>::type edge_length_map = boost::get(edge_length, g);
    graph_traits<Graph>::vertex_descriptor a, b, c;
    graph_traits<Graph>::edge_descriptor ed;

    a = add_vertex(g);
    b = add_vertex(g);
    c = add_vertex(g);
    vertex_location_map[b][0] = 1;
    vertex_location_map[b][1] = 1;
    vertex_location_map[c][0] = 3;
    vertex_location_map[c][1] = 3;

    bool inserted_flag;
    std::tie(ed, inserted_flag) = add_edge(a, b, g);
    edge_length_map[ed] = 1.2;
    std::tie(ed, inserted_flag) = add_edge(a, c, g);
    edge_length_map[ed] = 1.3;
    std::tie(ed, inserted_flag) = add_edge(b, c, g);
    edge_length_map[ed] = 1.4;

    cout << "degree of a:" << degree(a, g) << endl;

    for (auto vp = vertices(g); vp.first != vp.second; ++vp.first) {
        cout << "vertex index:" << vertex_index_map[*vp.first] << endl;
        cout << "vertex location :" << vertex_location_map[*vp.first] << endl;
    }

    for (auto ep = edges(g); ep.first != ep.second; ++ep.first) {
        cout << "edge length:" << edge_length_map[*ep.first] << endl;
    }
}

void DemoGraphWithOnlyEdgeProperty() {
    cout << "\nDemo Edge Property:" << endl;
    using GraphWithEdgeProperty=adjacency_list<setS, vecS, undirectedS, no_property, EdgeProperties>;
    GraphWithEdgeProperty graph;
    property_map<GraphWithEdgeProperty, vertex_index_t>::type vertex_index_map = boost::get(vertex_index, graph);
    property_map<GraphWithEdgeProperty, edge_length_t>::type edge_length_map = boost::get(edge_length, graph);
    graph_traits<GraphWithEdgeProperty>::vertex_descriptor a, b;
    graph_traits<GraphWithEdgeProperty>::edge_descriptor ed2;

    a = add_vertex(graph);
    b = add_vertex(graph);
    add_vertex(graph);

    bool inserted_flag;
    std::tie(ed2, inserted_flag) = add_edge(a, b, graph);
    edge_length_map[ed2] = 1.55;

    for (auto vp = vertices(graph); vp.first != vp.second; ++vp.first) {
        cout << "vertex index:" << vertex_index_map[*vp.first] << endl;
    }

    for (auto ep = edges(graph); ep.first != ep.second; ++ep.first) {
        cout << "edge length:" << edge_length_map[*ep.first] << endl;
    }
}

int main() {
    DemoComplexGraph();
    DemoGraphWithOnlyEdgeProperty();
}<|endoftext|>