<commit_before>#include <cstddef>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>

#include "nifty/python/converter.hxx"

#include "nifty/graph/rag/grid_rag.hxx"
#include "nifty/graph/rag/grid_rag_stacked_2d.hxx"

#ifdef WITH_HDF5
#include "nifty/graph/rag/grid_rag_hdf5.hxx"
#include "nifty/graph/rag/grid_rag_stacked_2d_hdf5.hxx"
#include "nifty/graph/rag/grid_rag_labels_hdf5.hxx"
#endif

namespace py = pybind11;

namespace nifty{
namespace graph{

    using namespace py;

    template<class CLS, class BASE>
    void removeFunctions(py::class_<CLS, BASE > & clsT){
        clsT
            .def("insertEdge", [](CLS * self,const uint64_t u,const uint64_t ){
                throw std::runtime_error("cannot insert edges into 'GridRag'");
            })
            .def("insertEdges",[](CLS * self, py::array_t<uint64_t> pyArray) {
                throw std::runtime_error("cannot insert edges into 'GridRag'");
            })
        ;
    }

    template<std::size_t DIM, class LABELS>
    void exportExpilictGridRagT(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        typedef UndirectedGraph<> BaseGraph;
        typedef ExplicitLabelsGridRag<DIM, LABELS> GridRagType;

        auto clsT = py::class_<GridRagType,BaseGraph>(ragModule, clsName.c_str());
        // export the rag shape
        clsT
            .def_property_readonly("shape",[](const GridRagType & self){return self.shape();})
        ;
        removeFunctions<GridRagType, BaseGraph>(clsT);

        // from labels
        ragModule.def(facName.c_str(),
            [](
               nifty::marray::PyView<LABELS, DIM> labels,
               const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;
                ExplicitLabels<DIM, LABELS> explicitLabels(labels);
                auto ptr = new GridRagType(explicitLabels, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg_t< int >("numberOfThreads", -1 )
        );

        // from labels + serialization
        ragModule.def(facName.c_str(),
            [](
               nifty::marray::PyView<LABELS, DIM>           labels,
               nifty::marray::PyView<uint64_t,   1, false>  serialization
            ){

                auto  startPtr = &serialization(0);
                auto  lastElement = &serialization(serialization.size()-1);
                auto d = lastElement - startPtr + 1;

                NIFTY_CHECK_OP(d,==,serialization.size(), "serialization must be contiguous");

                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = -1;
                ExplicitLabels<DIM, LABELS> explicitLabels(labels);
                auto ptr = new GridRagType(explicitLabels,startPtr, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("serialization")
        );

    }

    #ifdef WITH_HDF5
    template<size_t DIM, class LABELS>
    void exportHdf5GridRagT(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        typedef UndirectedGraph<> BaseGraph;
        typedef Hdf5Labels<DIM, LABELS> LabelsProxyType;
        typedef GridRag<DIM, LabelsProxyType >  GridRagType;

        const auto labelsProxyClsName = clsName + std::string("LabelsProxy");
        const auto labelsProxyFacName = facName + std::string("LabelsProxy");
        py::class_<LabelsProxyType>(ragModule, labelsProxyClsName.c_str())
            .def("hdf5Array",&LabelsProxyType::hdf5Array,py::return_value_policy::reference)
        ;

        ragModule.def(labelsProxyFacName.c_str(),
            [](
               const hdf5::Hdf5Array<LABELS> & hdf5Array,
               const int64_t numberOfLabels
            ){
                auto ptr = new LabelsProxyType(hdf5Array, numberOfLabels);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("numberOfLabels")
        );

        auto clsT = py::class_<GridRagType, BaseGraph>(ragModule, clsName.c_str());
        clsT
            .def("labelsProxy",&GridRagType::labelsProxy,py::return_value_policy::reference)
            .def_property_readonly("shape",[](const GridRagType & self){return self.shape();})
        ;

        removeFunctions<GridRagType, BaseGraph>(clsT);

        ragModule.def(facName.c_str(),
            [](
                const LabelsProxyType & labelsProxy,
                std::vector<int64_t>  blockShape,
                const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;

                if(blockShape.size() == DIM){
                    std::copy(blockShape.begin(), blockShape.end(), s.blockShape.begin());
                }
                else if(blockShape.size() == 1){
                    std::fill(s.blockShape.begin(), s.blockShape.end(), blockShape[0]);
                }
                else if(blockShape.size() != 0){
                    throw std::runtime_error("block shape has a non matching shape");
                }

                auto ptr = new GridRagType(labelsProxy, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labelsProxy"),
            py::arg_t< std::vector<int64_t>  >("blockShape", std::vector<int64_t>() ),
            py::arg_t< int >("numberOfThreads", -1 )
        );

        ragModule.def(facName.c_str(),
            [](
               const LabelsProxyType & labelsProxy,
               nifty::marray::PyView<uint64_t,   1, false>  serialization
            ){

                auto  startPtr = &serialization(0);
                auto  lastElement = &serialization(serialization.size()-1);
                auto d = lastElement - startPtr + 1;

                NIFTY_CHECK_OP(d,==,serialization.size(), "serialization must be contiguous");

                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = -1;

                auto ptr = new GridRagType(labelsProxy, startPtr, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("serialization")
        );

    }

    template<class LABELS>
    void exportHdf5GridRagStacked2D(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        py::object baseGraphPyCls = ragModule.attr("GridRagHdf5Labels3D");

        typedef Hdf5Labels<3, LABELS> LabelsProxyType;
        typedef GridRag<3, LabelsProxyType >  BaseGraph;
        typedef GridRagStacked2D<LabelsProxyType >  GridRagType;

        auto clsT = py::class_<GridRagType, BaseGraph>(ragModule, clsName.c_str());
        clsT
            .def("labelsProxy",&GridRagType::labelsProxy,py::return_value_policy::reference)
            .def("minMaxLabelPerSlice",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t, 2> out({std::size_t(shape[0]),std::size_t(2)});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    auto mima = self.minMaxNode(sliceIndex);
                    out(sliceIndex, 0) = mima.first;
                    out(sliceIndex, 1) = mima.second;
                }
                return out;
            })
            .def("numberOfNodesPerSlice",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfNodes(sliceIndex);
                }
                return out;
            })
            .def("numberOfInSliceEdges",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfInSliceEdges(sliceIndex);
                }
                return out;
            })
            .def("numberOfInBetweenSliceEdges",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfInBetweenSliceEdges(sliceIndex);
                }
                return out;
            })
            .def("inSliceEdgeOffset",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.inSliceEdgeOffset(sliceIndex);
                }
                return out;
            })
            .def("betweenSliceEdgeOffset",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.betweenSliceEdgeOffset(sliceIndex);
                }
                return out;
            })

        ;

        removeFunctions<GridRagType, BaseGraph>(clsT);

        ragModule.def(facName.c_str(),
            [](
                const LabelsProxyType & labelsProxy,
                const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;

                auto ptr = new GridRagType(labelsProxy, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labelsProxy"),
            py::arg_t< int >("numberOfThreads", -1 )
        );

    }
    #endif

    template<class LABELS>
    void exportExplicitGridRagStacked2D(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        py::object baseGraphPyCls = ragModule.attr("ExplicitLabelsGridRag3D");

        typedef ExplicitLabels<3, LABELS> LabelsProxyType;
        typedef GridRag<3, LabelsProxyType >  BaseGraph;
        typedef GridRagStacked2D<LabelsProxyType >  GridRagType;

        auto clsT = py::class_<GridRagType, BaseGraph>(ragModule, clsName.c_str());
        clsT
            //.def("labelsProxy",&GridRagType::labelsProxy,py::return_value_policy::reference)
            .def("minMaxLabelPerSlice",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t, 2> out({std::size_t(shape[0]),std::size_t(2)});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    auto mima = self.minMaxNode(sliceIndex);
                    out(sliceIndex, 0) = mima.first;
                    out(sliceIndex, 1) = mima.second;
                }
                return out;
            })
            .def("numberOfNodesPerSlice",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfNodes(sliceIndex);
                }
                return out;
            })
            .def("numberOfInSliceEdges",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfInSliceEdges(sliceIndex);
                }
                return out;
            })
            .def("numberOfInBetweenSliceEdges",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.numberOfInBetweenSliceEdges(sliceIndex);
                }
                return out;
            })
            .def("inSliceEdgeOffset",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.inSliceEdgeOffset(sliceIndex);
                }
                return out;
            })
            .def("betweenSliceEdgeOffset",[](const GridRagType & self){
                const auto & shape = self.shape();
                nifty::marray::PyView<uint64_t,  1> out({std::size_t(shape[0])});
                for(auto sliceIndex = 0; sliceIndex<shape[0]; ++sliceIndex){
                    out(sliceIndex) =  self.betweenSliceEdgeOffset(sliceIndex);
                }
                return out;
            })

        ;

        removeFunctions<GridRagType, BaseGraph>(clsT);

        ragModule.def(facName.c_str(),
            [](
               nifty::marray::PyView<LABELS, 3> labels,
               const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;
                ExplicitLabels<3, LABELS> explicitLabels(labels);
                auto ptr = new GridRagType(explicitLabels, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg_t< int >("numberOfThreads", -1 )
        );

    }

    void exportGridRag(py::module & ragModule) {

        exportExpilictGridRagT<2, uint32_t>(ragModule, "ExplicitLabelsGridRag2D", "explicitLabelsGridRag2D");
        exportExpilictGridRagT<3, uint32_t>(ragModule, "ExplicitLabelsGridRag3D", "explicitLabelsGridRag3D");

        #ifdef WITH_HDF5
        exportHdf5GridRagT<2, uint32_t>(ragModule, "GridRagHdf5Labels2D", "gridRag2DHdf5");
        exportHdf5GridRagT<3, uint32_t>(ragModule, "GridRagHdf5Labels3D", "gridRag3DHdf5");

        exportExplicitGridRagStacked2D<uint32_t>(ragModule, "GridRagStacked2DExplicit", "gridRagStacked2DExplicitImpl");
        exportHdf5GridRagStacked2D<uint32_t>(ragModule, "GridRagStacked2DHdf5", "gridRagStacked2DHdf5Impl");
        #endif
    }

} // end namespace graph
} // end namespace nifty
<commit_msg>Fix rag imports<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>

#include "nifty/python/converter.hxx"

#include "nifty/graph/rag/grid_rag.hxx"

#ifdef WITH_HDF5
#include "nifty/graph/rag/grid_rag_hdf5.hxx"
#include "nifty/graph/rag/grid_rag_labels_hdf5.hxx"
#endif

namespace py = pybind11;

namespace nifty{
namespace graph{

    using namespace py;

    template<class CLS, class BASE>
    void removeFunctions(py::class_<CLS, BASE > & clsT){
        clsT
            .def("insertEdge", [](CLS * self,const uint64_t u,const uint64_t ){
                throw std::runtime_error("cannot insert edges into 'GridRag'");
            })
            .def("insertEdges",[](CLS * self, py::array_t<uint64_t> pyArray) {
                throw std::runtime_error("cannot insert edges into 'GridRag'");
            })
        ;
    }

    template<size_t DIM, class LABELS>
    void exportExpilictGridRagT(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        typedef UndirectedGraph<> BaseGraph;
        typedef ExplicitLabelsGridRag<DIM, LABELS> GridRagType;

        auto clsT = py::class_<GridRagType,BaseGraph>(ragModule, clsName.c_str());
        // export the rag shape
        clsT
            .def_property_readonly("shape",[](const GridRagType & self){return self.shape();})
        ;
        removeFunctions<GridRagType, BaseGraph>(clsT);

        // from labels
        ragModule.def(facName.c_str(),
            [](
               nifty::marray::PyView<LABELS, DIM> labels,
               const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;
                ExplicitLabels<DIM, LABELS> explicitLabels(labels);
                auto ptr = new GridRagType(explicitLabels, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg_t< int >("numberOfThreads", -1 )
        );

        // from labels + serialization
        ragModule.def(facName.c_str(),
            [](
               nifty::marray::PyView<LABELS, DIM>           labels,
               nifty::marray::PyView<uint64_t,   1, false>  serialization
            ){

                auto  startPtr = &serialization(0);
                auto  lastElement = &serialization(serialization.size()-1);
                auto d = lastElement - startPtr + 1;

                NIFTY_CHECK_OP(d,==,serialization.size(), "serialization must be contiguous");

                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = -1;
                ExplicitLabels<DIM, LABELS> explicitLabels(labels);
                auto ptr = new GridRagType(explicitLabels,startPtr, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("serialization")
        );

    }

    #ifdef WITH_HDF5
    template<size_t DIM, class LABELS>
    void exportHdf5GridRagT(
        py::module & ragModule,
        const std::string & clsName,
        const std::string & facName
    ){
        typedef UndirectedGraph<> BaseGraph;
        typedef Hdf5Labels<DIM, LABELS> LabelsProxyType;
        typedef GridRag<DIM, LabelsProxyType >  GridRagType;

        const auto labelsProxyClsName = clsName + std::string("LabelsProxy");
        const auto labelsProxyFacName = facName + std::string("LabelsProxy");
        py::class_<LabelsProxyType>(ragModule, labelsProxyClsName.c_str())
            .def("hdf5Array",&LabelsProxyType::hdf5Array,py::return_value_policy::reference)
        ;

        ragModule.def(labelsProxyFacName.c_str(),
            [](
               const hdf5::Hdf5Array<LABELS> & hdf5Array,
               const int64_t numberOfLabels
            ){
                auto ptr = new LabelsProxyType(hdf5Array, numberOfLabels);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("numberOfLabels")
        );

        auto clsT = py::class_<GridRagType, BaseGraph>(ragModule, clsName.c_str());
        clsT
            .def("labelsProxy",&GridRagType::labelsProxy,py::return_value_policy::reference)
            .def_property_readonly("shape",[](const GridRagType & self){return self.shape();})
        ;

        removeFunctions<GridRagType, BaseGraph>(clsT);

        ragModule.def(facName.c_str(),
            [](
                const LabelsProxyType & labelsProxy,
                std::vector<int64_t>  blockShape,
                const int numberOfThreads
            ){
                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = numberOfThreads;

                if(blockShape.size() == DIM){
                    std::copy(blockShape.begin(), blockShape.end(), s.blockShape.begin());
                }
                else if(blockShape.size() == 1){
                    std::fill(s.blockShape.begin(), s.blockShape.end(), blockShape[0]);
                }
                else if(blockShape.size() != 0){
                    throw std::runtime_error("block shape has a non matching shape");
                }

                auto ptr = new GridRagType(labelsProxy, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labelsProxy"),
            py::arg_t< std::vector<int64_t>  >("blockShape", std::vector<int64_t>() ),
            py::arg_t< int >("numberOfThreads", -1 )
        );

        ragModule.def(facName.c_str(),
            [](
               const LabelsProxyType & labelsProxy,
               nifty::marray::PyView<uint64_t,   1, false>  serialization
            ){

                auto  startPtr = &serialization(0);
                auto  lastElement = &serialization(serialization.size()-1);
                auto d = lastElement - startPtr + 1;

                NIFTY_CHECK_OP(d,==,serialization.size(), "serialization must be contiguous");

                auto s = typename  GridRagType::Settings();
                s.numberOfThreads = -1;

                auto ptr = new GridRagType(labelsProxy, startPtr, s);
                return ptr;
            },
            py::return_value_policy::take_ownership,
            py::keep_alive<0, 1>(),
            py::arg("labels"),
            py::arg("serialization")
        );

    }
    #endif

    void exportGridRag(py::module & ragModule) {
        exportExpilictGridRagT<2, uint32_t>(ragModule, "ExplicitLabelsGridRag2D", "explicitLabelsGridRag2D");
        exportExpilictGridRagT<3, uint32_t>(ragModule, "ExplicitLabelsGridRag3D", "explicitLabelsGridRag3D");
        #ifdef WITH_HDF5
        exportHdf5GridRagT<2, uint32_t>(ragModule, "GridRagHdf5Labels2D", "gridRag2DHdf5");
        exportHdf5GridRagT<3, uint32_t>(ragModule, "GridRagHdf5Labels3D", "gridRag3DHdf5");
        #endif
    }

} // end namespace graph
} // end namespace nifty
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmldebugservice_p.h"
#include "qqmldebugservice_p_p.h"
#include "qqmldebugserver_p.h"
#include <private/qqmldata_p.h>
#include <private/qqmlcontext_p.h>

#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>

QT_BEGIN_NAMESPACE

QQmlDebugServicePrivate::QQmlDebugServicePrivate()
    : server(0)
{
}

QQmlDebugService::QQmlDebugService(const QString &name, float version, QObject *parent)
    : QObject(*(new QQmlDebugServicePrivate), parent)
{
    Q_D(QQmlDebugService);
    d->name = name;
    d->version = version;
    d->server = QQmlDebugServer::instance();
    d->state = QQmlDebugService::NotConnected;

}

QQmlDebugService::QQmlDebugService(QQmlDebugServicePrivate &dd,
                                                   const QString &name, float version, QObject *parent)
    : QObject(dd, parent)
{
    Q_D(QQmlDebugService);
    d->name = name;
    d->version = version;
    d->server = QQmlDebugServer::instance();
    d->state = QQmlDebugService::NotConnected;
}

/**
  Registers the service. This should be called in the constructor of the inherited class. From
  then on the service might get asynchronous calls to messageReceived().
  */
QQmlDebugService::State QQmlDebugService::registerService()
{
    Q_D(QQmlDebugService);
    if (!d->server)
        return NotConnected;

    if (d->server->serviceNames().contains(d->name)) {
        qWarning() << "QQmlDebugService: Conflicting plugin name" << d->name;
        d->server = 0;
    } else {
        d->server->addService(this);
    }
    return state();
}

QQmlDebugService::~QQmlDebugService()
{
    Q_D(const QQmlDebugService);
    if (d->server) {
        d->server->removeService(this);
    }
}

QString QQmlDebugService::name() const
{
    Q_D(const QQmlDebugService);
    return d->name;
}

float QQmlDebugService::version() const
{
    Q_D(const QQmlDebugService);
    return d->version;
}

QQmlDebugService::State QQmlDebugService::state() const
{
    Q_D(const QQmlDebugService);
    return d->state;
}

namespace {

struct ObjectReference
{
    QPointer<QObject> object;
    int id;
};

struct ObjectReferenceHash
{
    ObjectReferenceHash() : nextId(0) {}

    QHash<QObject *, ObjectReference> objects;
    QHash<int, QObject *> ids;

    int nextId;
};

}
Q_GLOBAL_STATIC(ObjectReferenceHash, objectReferenceHash)

/*!
    Returns a unique id for \a object.  Calling this method multiple times
    for the same object will return the same id.
*/
int QQmlDebugService::idForObject(QObject *object)
{
    if (!object)
        return -1;

    ObjectReferenceHash *hash = objectReferenceHash();
    QHash<QObject *, ObjectReference>::Iterator iter =
            hash->objects.find(object);

    if (iter == hash->objects.end()) {
        int id = hash->nextId++;

        hash->ids.insert(id, object);
        iter = hash->objects.insert(object, ObjectReference());
        iter->object = object;
        iter->id = id;
    } else if (iter->object != object) {
        int id = hash->nextId++;

        hash->ids.remove(iter->id);

        hash->ids.insert(id, object);
        iter->object = object;
        iter->id = id;
    }
    return iter->id;
}

/*!
    Returns the object for unique \a id.  If the object has not previously been
    assigned an id, through idForObject(), then 0 is returned.  If the object
    has been destroyed, 0 is returned.
*/
QObject *QQmlDebugService::objectForId(int id)
{
    ObjectReferenceHash *hash = objectReferenceHash();

    QHash<int, QObject *>::Iterator iter = hash->ids.find(id);
    if (iter == hash->ids.end())
        return 0;

    QHash<QObject *, ObjectReference>::Iterator objIter =
            hash->objects.find(*iter);
    Q_ASSERT(objIter != hash->objects.end());

    if (objIter->object == 0) {
        hash->ids.erase(iter);
        hash->objects.erase(objIter);
        // run a loop to remove other invalid objects
        removeInvalidObjectsFromHash();
        return 0;
    } else {
        return *iter;
    }
}

/*!
    Returns a list of objects matching the given filename, line and column.
*/
QList<QObject*> QQmlDebugService::objectForLocationInfo(const QString &filename,
                                                 int lineNumber, int columnNumber)
{
    ObjectReferenceHash *hash = objectReferenceHash();
    QList<QObject*> objects;
    QHash<int, QObject *>::Iterator iter;
    for (iter = hash->ids.begin(); iter != hash->ids.end(); ++iter) {
        QQmlData *ddata = QQmlData::get(iter.value());
        if (!ddata || !ddata->outerContext)
            continue;
        //column number may be different due to qmlrewriter
        if (QFileInfo(ddata->outerContext->urlString).fileName() == filename &&
                ddata->lineNumber == lineNumber &&
                ddata->columnNumber >= columnNumber) {
            QHash<QObject *, ObjectReference>::Iterator objIter =
                    hash->objects.find(*iter);
            Q_ASSERT(objIter != hash->objects.end());

            if (objIter->object == 0) {
                hash->ids.erase(iter);
                hash->objects.erase(objIter);
            } else {
                objects << *iter;
            }
        }
    }
    return objects;
}

void QQmlDebugService::removeInvalidObjectsFromHash()
{
    ObjectReferenceHash *hash = objectReferenceHash();
    QHash<int, QObject *>::Iterator iter = hash->ids.begin();
    while (iter != hash->ids.end()) {
        QHash<QObject *, ObjectReference>::Iterator objIter =
                hash->objects.find(*iter);
        Q_ASSERT(objIter != hash->objects.end());

        if (objIter->object == 0) {
            iter = hash->ids.erase(iter);
            hash->objects.erase(objIter);
        } else {
            ++iter;
        }
    }
}

void QQmlDebugService::clearObjectsFromHash()
{
    ObjectReferenceHash *hash = objectReferenceHash();
    hash->ids.clear();
    hash->objects.clear();
}

bool QQmlDebugService::isDebuggingEnabled()
{
    return QQmlDebugServer::instance() != 0;
}

bool QQmlDebugService::hasDebuggingClient()
{
    return QQmlDebugServer::instance() != 0
            && QQmlDebugServer::instance()->hasDebuggingClient();
}

bool QQmlDebugService::blockingMode()
{
    return QQmlDebugServer::instance() != 0
            && QQmlDebugServer::instance()->blockingMode();
}

QString QQmlDebugService::objectToString(QObject *obj)
{
    if(!obj)
        return QStringLiteral("NULL");

    QString objectName = obj->objectName();
    if(objectName.isEmpty())
        objectName = QStringLiteral("<unnamed>");

    QString rv = QString::fromUtf8(obj->metaObject()->className()) +
            QLatin1String(": ") + objectName;

    return rv;
}

void QQmlDebugService::sendMessage(const QByteArray &message)
{
    sendMessages(QList<QByteArray>() << message);
}

void QQmlDebugService::sendMessages(const QList<QByteArray> &messages)
{
    Q_D(QQmlDebugService);

    if (state() != Enabled)
        return;

    d->server->sendMessages(this, messages);
}

void QQmlDebugService::stateAboutToBeChanged(State)
{
}

void QQmlDebugService::stateChanged(State)
{
}

void QQmlDebugService::messageReceived(const QByteArray &)
{
}

QQmlDebugStream::QQmlDebugStream()
    : QDataStream()
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(QIODevice *d)
    : QDataStream(d)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(QByteArray *ba, QIODevice::OpenMode flags)
    : QDataStream(ba, flags)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(const QByteArray &ba)
    : QDataStream(ba)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QT_END_NAMESPACE
<commit_msg>Fix crash in QQmlDebugService::objectForLocationInfo()<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmldebugservice_p.h"
#include "qqmldebugservice_p_p.h"
#include "qqmldebugserver_p.h"
#include <private/qqmldata_p.h>
#include <private/qqmlcontext_p.h>

#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>

QT_BEGIN_NAMESPACE

QQmlDebugServicePrivate::QQmlDebugServicePrivate()
    : server(0)
{
}

QQmlDebugService::QQmlDebugService(const QString &name, float version, QObject *parent)
    : QObject(*(new QQmlDebugServicePrivate), parent)
{
    Q_D(QQmlDebugService);
    d->name = name;
    d->version = version;
    d->server = QQmlDebugServer::instance();
    d->state = QQmlDebugService::NotConnected;

}

QQmlDebugService::QQmlDebugService(QQmlDebugServicePrivate &dd,
                                                   const QString &name, float version, QObject *parent)
    : QObject(dd, parent)
{
    Q_D(QQmlDebugService);
    d->name = name;
    d->version = version;
    d->server = QQmlDebugServer::instance();
    d->state = QQmlDebugService::NotConnected;
}

/**
  Registers the service. This should be called in the constructor of the inherited class. From
  then on the service might get asynchronous calls to messageReceived().
  */
QQmlDebugService::State QQmlDebugService::registerService()
{
    Q_D(QQmlDebugService);
    if (!d->server)
        return NotConnected;

    if (d->server->serviceNames().contains(d->name)) {
        qWarning() << "QQmlDebugService: Conflicting plugin name" << d->name;
        d->server = 0;
    } else {
        d->server->addService(this);
    }
    return state();
}

QQmlDebugService::~QQmlDebugService()
{
    Q_D(const QQmlDebugService);
    if (d->server) {
        d->server->removeService(this);
    }
}

QString QQmlDebugService::name() const
{
    Q_D(const QQmlDebugService);
    return d->name;
}

float QQmlDebugService::version() const
{
    Q_D(const QQmlDebugService);
    return d->version;
}

QQmlDebugService::State QQmlDebugService::state() const
{
    Q_D(const QQmlDebugService);
    return d->state;
}

namespace {

struct ObjectReference
{
    QPointer<QObject> object;
    int id;
};

struct ObjectReferenceHash
{
    ObjectReferenceHash() : nextId(0) {}

    QHash<QObject *, ObjectReference> objects;
    QHash<int, QObject *> ids;

    int nextId;
};

}
Q_GLOBAL_STATIC(ObjectReferenceHash, objectReferenceHash)

/*!
    Returns a unique id for \a object.  Calling this method multiple times
    for the same object will return the same id.
*/
int QQmlDebugService::idForObject(QObject *object)
{
    if (!object)
        return -1;

    ObjectReferenceHash *hash = objectReferenceHash();
    QHash<QObject *, ObjectReference>::Iterator iter =
            hash->objects.find(object);

    if (iter == hash->objects.end()) {
        int id = hash->nextId++;

        hash->ids.insert(id, object);
        iter = hash->objects.insert(object, ObjectReference());
        iter->object = object;
        iter->id = id;
    } else if (iter->object != object) {
        int id = hash->nextId++;

        hash->ids.remove(iter->id);

        hash->ids.insert(id, object);
        iter->object = object;
        iter->id = id;
    }
    return iter->id;
}

/*!
    Returns the object for unique \a id.  If the object has not previously been
    assigned an id, through idForObject(), then 0 is returned.  If the object
    has been destroyed, 0 is returned.
*/
QObject *QQmlDebugService::objectForId(int id)
{
    ObjectReferenceHash *hash = objectReferenceHash();

    QHash<int, QObject *>::Iterator iter = hash->ids.find(id);
    if (iter == hash->ids.end())
        return 0;

    QHash<QObject *, ObjectReference>::Iterator objIter =
            hash->objects.find(*iter);
    Q_ASSERT(objIter != hash->objects.end());

    if (objIter->object == 0) {
        hash->ids.erase(iter);
        hash->objects.erase(objIter);
        // run a loop to remove other invalid objects
        removeInvalidObjectsFromHash();
        return 0;
    } else {
        return *iter;
    }
}

/*!
    Returns a list of objects matching the given filename, line and column.
*/
QList<QObject*> QQmlDebugService::objectForLocationInfo(const QString &filename,
                                                 int lineNumber, int columnNumber)
{
    ObjectReferenceHash *hash = objectReferenceHash();
    QList<QObject*> objects;
    QHash<int, QObject *>::Iterator iter = hash->ids.begin();
    while (iter != hash->ids.end()) {
        QHash<QObject *, ObjectReference>::Iterator objIter =
                hash->objects.find(*iter);
        Q_ASSERT(objIter != hash->objects.end());

        if (objIter->object == 0) {
            iter = hash->ids.erase(iter);
            hash->objects.erase(objIter);
        } else {
            QQmlData *ddata = QQmlData::get(iter.value());
            if (ddata && ddata->outerContext) {
                if (QFileInfo(ddata->outerContext->urlString).fileName() == filename &&
                    ddata->lineNumber == lineNumber &&
                    ddata->columnNumber >= columnNumber) {
                    objects << *iter;
                }
            }
            ++iter;
        }
    }
    return objects;
}

void QQmlDebugService::removeInvalidObjectsFromHash()
{
    ObjectReferenceHash *hash = objectReferenceHash();
    QHash<int, QObject *>::Iterator iter = hash->ids.begin();
    while (iter != hash->ids.end()) {
        QHash<QObject *, ObjectReference>::Iterator objIter =
                hash->objects.find(*iter);
        Q_ASSERT(objIter != hash->objects.end());

        if (objIter->object == 0) {
            iter = hash->ids.erase(iter);
            hash->objects.erase(objIter);
        } else {
            ++iter;
        }
    }
}

void QQmlDebugService::clearObjectsFromHash()
{
    ObjectReferenceHash *hash = objectReferenceHash();
    hash->ids.clear();
    hash->objects.clear();
}

bool QQmlDebugService::isDebuggingEnabled()
{
    return QQmlDebugServer::instance() != 0;
}

bool QQmlDebugService::hasDebuggingClient()
{
    return QQmlDebugServer::instance() != 0
            && QQmlDebugServer::instance()->hasDebuggingClient();
}

bool QQmlDebugService::blockingMode()
{
    return QQmlDebugServer::instance() != 0
            && QQmlDebugServer::instance()->blockingMode();
}

QString QQmlDebugService::objectToString(QObject *obj)
{
    if(!obj)
        return QStringLiteral("NULL");

    QString objectName = obj->objectName();
    if(objectName.isEmpty())
        objectName = QStringLiteral("<unnamed>");

    QString rv = QString::fromUtf8(obj->metaObject()->className()) +
            QLatin1String(": ") + objectName;

    return rv;
}

void QQmlDebugService::sendMessage(const QByteArray &message)
{
    sendMessages(QList<QByteArray>() << message);
}

void QQmlDebugService::sendMessages(const QList<QByteArray> &messages)
{
    Q_D(QQmlDebugService);

    if (state() != Enabled)
        return;

    d->server->sendMessages(this, messages);
}

void QQmlDebugService::stateAboutToBeChanged(State)
{
}

void QQmlDebugService::stateChanged(State)
{
}

void QQmlDebugService::messageReceived(const QByteArray &)
{
}

QQmlDebugStream::QQmlDebugStream()
    : QDataStream()
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(QIODevice *d)
    : QDataStream(d)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(QByteArray *ba, QIODevice::OpenMode flags)
    : QDataStream(ba, flags)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QQmlDebugStream::QQmlDebugStream(const QByteArray &ba)
    : QDataStream(ba)
{
    setVersion(QQmlDebugServer::s_dataStreamVersion);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>// El Leave One Out estima mejor el error promedio
// pero peor el desvío. Elaborar por qué.

#include "multicapa.cpp"
#include "particionar.cpp"
#include "../config.hpp"

int main()
{
    arma_rng::set_seed_random();

    mat datos;
    string rutaBaseDatos = config::sourceDir + "/guia1/icgtp1datos/";
    datos.load(rutaBaseDatos + "irisbin.csv");

    ifstream ifs{config::sourceDir + "/guia1/parametrosIris.txt"};
    ic::ParametrosMulticapa parametros;
    if (!(ifs >> parametros))
        throw runtime_error("No se pudo cargar el archivo de parámetros");

    // Leave K Out

    {
        vector<ic::Particion> particiones = ic::cargarParticiones(rutaBaseDatos + "particionesIrisKOut/", 10);
        vec errores, epocas;
        errores.resize(particiones.size());
        epocas.resize(particiones.size());

#pragma omp parallel for
        for (unsigned int i = 0; i < particiones.size(); ++i) {
            vector<mat> pesos;
            int epoca;
            tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,
                                                              datos.rows(particiones[i].first),
                                                              parametros.nEpocas,
                                                              parametros.tasaAprendizaje,
                                                              parametros.inercia,
                                                              parametros.toleranciaError);

            const double tasaError = ic::errorPrueba(pesos,
                                                     datos.rows(particiones[i].second));

            epocas(i) = epoca;
            errores(i) = tasaError;
        }

        cout << "Iris multicapa, Leave K Out" << endl
             << "Error promedio: " << mean(errores) << endl
             << "Desvío estándar del error: " << stddev(errores) << endl
             << "N° de épocas promedio que tarda en converger: " << mean(epocas) << endl
             << "Desvío estándar de lo anterior: " << stddev(epocas) << endl;
    }

    // Leave One Out

    {
        vector<ic::Particion> particiones = ic::cargarParticiones(rutaBaseDatos + "particionesIris1Out/", 150);
        vec errores, epocas;
        errores.resize(particiones.size());
        epocas.resize(particiones.size());

#pragma omp parallel for
        for (unsigned int i = 0; i < particiones.size(); ++i) {
            vector<mat> pesos;
            int epoca;
            tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,
                                                              datos.rows(particiones[i].first),
                                                              parametros.nEpocas,
                                                              parametros.tasaAprendizaje,
                                                              parametros.inercia,
                                                              parametros.toleranciaError);

            const double tasaError = ic::errorPrueba(pesos,
                                                     datos.rows(particiones[i].second));

            epocas(i) = epoca;
            errores(i) = tasaError;
        }

        cout << "\nIris multicapa, Leave One Out" << endl
             << "Error promedio: " << mean(errores) << endl
             << "Desvío estándar del error: " << stddev(errores) << endl
             << "N° de épocas promedio que tarda en converger: " << mean(epocas) << endl
             << "Desvío estándar de lo anterior: " << stddev(epocas) << endl;
    }

    return 0;
}
<commit_msg>Guia 1 - Ejercicio 4: Aclarar que el error medido es en la prueba<commit_after>// El Leave One Out estima mejor el error promedio
// pero peor el desvío. Elaborar por qué.

#include "multicapa.cpp"
#include "particionar.cpp"
#include "../config.hpp"

int main()
{
    arma_rng::set_seed_random();

    mat datos;
    string rutaBaseDatos = config::sourceDir + "/guia1/icgtp1datos/";
    datos.load(rutaBaseDatos + "irisbin.csv");

    ifstream ifs{config::sourceDir + "/guia1/parametrosIris.txt"};
    ic::ParametrosMulticapa parametros;
    if (!(ifs >> parametros))
        throw runtime_error("No se pudo cargar el archivo de parámetros");

    // Leave K Out

    {
        vector<ic::Particion> particiones = ic::cargarParticiones(rutaBaseDatos + "particionesIrisKOut/", 10);
        vec errores, epocas;
        errores.resize(particiones.size());
        epocas.resize(particiones.size());

#pragma omp parallel for
        for (unsigned int i = 0; i < particiones.size(); ++i) {
            vector<mat> pesos;
            int epoca;
            tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,
                                                              datos.rows(particiones[i].first),
                                                              parametros.nEpocas,
                                                              parametros.tasaAprendizaje,
                                                              parametros.inercia,
                                                              parametros.toleranciaError);

            const double tasaError = ic::errorPrueba(pesos,
                                                     datos.rows(particiones[i].second));

            epocas(i) = epoca;
            errores(i) = tasaError;
        }

        cout << "Iris multicapa, Leave K Out" << endl
             << "Error promedio en la prueba: " << mean(errores) << endl
             << "Desvío estándar del error: " << stddev(errores) << endl
             << "N° de épocas promedio que tarda en converger: " << mean(epocas) << endl
             << "Desvío estándar de lo anterior: " << stddev(epocas) << endl;
    }

    // Leave One Out

    {
        vector<ic::Particion> particiones = ic::cargarParticiones(rutaBaseDatos + "particionesIris1Out/", 150);
        vec errores, epocas;
        errores.resize(particiones.size());
        epocas.resize(particiones.size());

#pragma omp parallel for
        for (unsigned int i = 0; i < particiones.size(); ++i) {
            vector<mat> pesos;
            int epoca;
            tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,
                                                              datos.rows(particiones[i].first),
                                                              parametros.nEpocas,
                                                              parametros.tasaAprendizaje,
                                                              parametros.inercia,
                                                              parametros.toleranciaError);

            const double tasaError = ic::errorPrueba(pesos,
                                                     datos.rows(particiones[i].second));

            epocas(i) = epoca;
            errores(i) = tasaError;
        }

        cout << "\nIris multicapa, Leave One Out" << endl
             << "Error promedio en la prueba: " << mean(errores) << endl
             << "Desvío estándar del error: " << stddev(errores) << endl
             << "N° de épocas promedio que tarda en converger: " << mean(epocas) << endl
             << "Desvío estándar de lo anterior: " << stddev(epocas) << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/wire_func.hpp"

namespace ql {
configured_limits_t
from_optargs(const std::map<std::string, wire_func_t> &)
{
    return configured_limits_t();
}

} // namespace ql
<commit_msg>Sketch implementation.<commit_after>#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(const std::map<std::string, wire_func_t> &arguments)
{
    auto p = arguments.find("arrayLimit");
    if (p != arguments.end()) {
        return configured_limits_t((*p).second.compile_wire_func()->call(NULL)->as_int());
    } else {
        return configured_limits_t();
    }
}

} // namespace ql
<|endoftext|>


<commit_before>#include <string.h>

#include "rdb_protocol/exceptions.hpp"
#include "rdb_protocol/rdb_protocol_json.hpp"
#include "utils.hpp"

write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) {
    rassert(NULL != cjson.get() && NULL != cjson->get());
    msg << *cjson->get();
    return msg;
}

MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) {
    cJSON *data = cJSON_CreateBlank();

    archive_result_t res = deserialize(s, data);
    if (res) { return res; }

    *cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data));

    return ARCHIVE_SUCCESS;
}

namespace query_language {

// TODO: Rename this function!  It is not part of the cJSON library,
// so it should not be part of the cJSON namepace.
static const int cJSON_rank[7] = {
    [cJSON_Array]  = 0,  //5
    [cJSON_False]  = 1,  //0
    [cJSON_True]   = 2,  //1
    [cJSON_NULL]   = 3,  //2
    [cJSON_Number] = 4,  //3
    [cJSON_Object] = 5,  //6
    [cJSON_String] = 6}; //4
int cJSON_cmp(cJSON *l, cJSON *r, const backtrace_t &backtrace) {
    if (l->type != r->type) {
        rassert(0 <= l->type && l->type < int(sizeof(cJSON_rank)/sizeof(*cJSON_rank)));
        rassert(0 <= r->type && r->type < int(sizeof(cJSON_rank)/sizeof(*cJSON_rank)));
        return cJSON_rank[l->type] - cJSON_rank[r->type];
    }
    switch (l->type) {
        case cJSON_False:
            if (r->type == cJSON_True) {
                return -1;
            } else if (r->type == cJSON_False) {
                return 0;
            }
            break;
        case cJSON_True:
            if (r->type == cJSON_True) {
                return 0;
            } else if (r->type == cJSON_False) {
                return 1;
            }
            break;
        case cJSON_NULL:
            return 0;
            break;
        case cJSON_Number:
            if (l->valuedouble < r->valuedouble) {
                return -1;
            } else if (l->valuedouble > r->valuedouble) {
                return 1;
            } else {
                return 0;   // TODO: Handle NaN?
            }
            break;
        case cJSON_String:
            return strcmp(l->valuestring, r->valuestring);
            break;
        case cJSON_Array:
            {
                int lsize = cJSON_GetArraySize(l),
                    rsize = cJSON_GetArraySize(r);
                for (int i = 0; i < lsize; ++i) {
                    if (i >= rsize) {
                        return 1;  // e.g. cmp([0, 1], [0])
                    }
                    int cmp = cJSON_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i), backtrace);
                    if (cmp) {
                        return cmp;
                    }
                }
                return -1;  // e.g. cmp([0], [0, 1]);
            }
            break;
        case cJSON_Object:
            throw runtime_exc_t("Can't compare objects.", backtrace);
            break;
        default:
            unreachable();
            break;
    }
    unreachable();
}

void require_type(const cJSON *json, int type, const backtrace_t &b) {
    if (json->type != type) {
        throw runtime_exc_t(strprintf("Required type: %s but found %s.",
                                      cJSON_type_to_string(type).c_str(),
                                      cJSON_type_to_string(json->type).c_str()),
                            b);
    }
}

} // namespace query_language
<commit_msg>Fixed so compiles under gcc.<commit_after>#include <string.h>

#include "rdb_protocol/exceptions.hpp"
#include "rdb_protocol/rdb_protocol_json.hpp"
#include "utils.hpp"

write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) {
    rassert(NULL != cjson.get() && NULL != cjson->get());
    msg << *cjson->get();
    return msg;
}

MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) {
    cJSON *data = cJSON_CreateBlank();

    archive_result_t res = deserialize(s, data);
    if (res) { return res; }

    *cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data));

    return ARCHIVE_SUCCESS;
}

namespace query_language {

/* In a less ridiculous world, the C++ standard wouldn't have dropped designated
   initializers for arrays, and this namespace wouldn't be necessary. */
namespace cJSON_type_ordering {
struct rank_wrapper {
    int rank[7];
    rank_wrapper() {
        rank[cJSON_Array]  = 0;
        rank[cJSON_False]  = 1;
        rank[cJSON_True]   = 2;
        rank[cJSON_NULL]   = 3;
        rank[cJSON_Number] = 4;
        rank[cJSON_Object] = 5;
        rank[cJSON_String] = 6;
    }
};
rank_wrapper wrapper;
int cmp(int t1, int t2) { return wrapper.rank[t1] - wrapper.rank[t2]; }
}

// TODO: Rename this function!  It is not part of the cJSON library,
// so it should not be part of the cJSON namepace.
int cJSON_cmp(cJSON *l, cJSON *r, const backtrace_t &backtrace) {
    if (l->type != r->type) {
        return cJSON_type_ordering::cmp(l->type, r->type);
    }
    switch (l->type) {
        case cJSON_False:
            if (r->type == cJSON_True) {
                return -1;
            } else if (r->type == cJSON_False) {
                return 0;
            }
            break;
        case cJSON_True:
            if (r->type == cJSON_True) {
                return 0;
            } else if (r->type == cJSON_False) {
                return 1;
            }
            break;
        case cJSON_NULL:
            return 0;
            break;
        case cJSON_Number:
            if (l->valuedouble < r->valuedouble) {
                return -1;
            } else if (l->valuedouble > r->valuedouble) {
                return 1;
            } else {
                return 0;   // TODO: Handle NaN?
            }
            break;
        case cJSON_String:
            return strcmp(l->valuestring, r->valuestring);
            break;
        case cJSON_Array:
            {
                int lsize = cJSON_GetArraySize(l),
                    rsize = cJSON_GetArraySize(r);
                for (int i = 0; i < lsize; ++i) {
                    if (i >= rsize) {
                        return 1;  // e.g. cmp([0, 1], [0])
                    }
                    int cmp = cJSON_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i), backtrace);
                    if (cmp) {
                        return cmp;
                    }
                }
                return -1;  // e.g. cmp([0], [0, 1]);
            }
            break;
        case cJSON_Object:
            throw runtime_exc_t("Can't compare objects.", backtrace);
            break;
        default:
            unreachable();
            break;
    }
    unreachable();
}

void require_type(const cJSON *json, int type, const backtrace_t &b) {
    if (json->type != type) {
        throw runtime_exc_t(strprintf("Required type: %s but found %s.",
                                      cJSON_type_to_string(type).c_str(),
                                      cJSON_type_to_string(json->type).c_str()),
                            b);
    }
}

} // namespace query_language
<|endoftext|>


<commit_before>#include <iostream>

#include "dispatch.hpp"

int main()
{
  enum
  {
    NORMAL,
    INVALID
  } state(NORMAL);

  std::cout <<
    gnr::dispatch(
      state,
      []{ return "NORMAL"; },
      []{ return "INVALID"; }
    ) <<
    std::endl;

  std::cout << gnr::select(1, "NORMAL", "INVALID") << std::endl;

  return 0;
}
<commit_msg>some fixes<commit_after>#include <iostream>

#include "dispatch.hpp"

int main()
{
  enum
  {
    NORMAL,
    INVALID
  } state(NORMAL);

  std::cout <<
    gnr::dispatch(
      state,
      []{ return "NORMAL"; },
      []{ return "INVALID"; }
    ) <<
    std::endl;

  std::cout << gnr::select(1, 0, 1, 4) << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Flight Systems and Automatic Control group,
//       TU Darmstadt, nor the names of its contributors may be used to
//       endorse or promote products derived from this software without
//       specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>

namespace hector_quadrotor {

class Teleop
{
private:
  ros::NodeHandle node_handle_;
  ros::Subscriber joy_subscriber_;
  ros::Publisher velocity_publisher_;
  geometry_msgs::Twist velocity_;

  struct Axis
  {
    int axis;
    double max;
  };

  struct Button
  {
    int button;
  };

  struct {
    Axis x;
    Axis y;
    Axis z;
    Axis yaw;
  } axes_;

  struct
  {
    Button slow;
  } buttons_;

  double slow_factor_;

public:
  Teleop()
  {
    ros::NodeHandle params("~");

    axes_.x.axis = 0;
    axes_.x.max = 2.0;
    axes_.y.axis = 0;
    axes_.y.max = 2.0;
    axes_.z.axis = 0;
    axes_.z.max = 2.0;
    axes_.yaw.axis = 0;
    axes_.yaw.max = 90.0*M_PI/180.0;
    buttons_.slow.button = 0;
    slow_factor_ = 0.2;

    params.getParam("x_axis", axes_.x.axis);
    params.getParam("y_axis", axes_.y.axis);
    params.getParam("z_axis", axes_.z.axis);
    params.getParam("yaw_axis", axes_.yaw.axis);
    params.getParam("x_velocity_max", axes_.x.max);
    params.getParam("y_velocity_max", axes_.y.max);
    params.getParam("z_velocity_max", axes_.z.max);
    params.getParam("yaw_velocity_max", axes_.yaw.max);
    params.getParam("slow_button", buttons_.slow.button);
    params.getParam("slow_factor", slow_factor_);

    joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyCallback, this, _1));
    velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
  }

  ~Teleop()
  {
    stop();
  }

  void joyCallback(const sensor_msgs::JoyConstPtr& joy)
  {
    velocity_.linear.x  = getAxis(joy, axes_.x.axis)   * axes_.x.max;
    velocity_.linear.y  = getAxis(joy, axes_.y.axis)   * axes_.y.max;
    velocity_.linear.z  = getAxis(joy, axes_.z.axis)   * axes_.z.max;
    velocity_.angular.z = getAxis(joy, axes_.yaw.axis) * axes_.yaw.max;
    if (getButton(joy, buttons_.slow.button)) {
      velocity_.linear.x  *= slow_factor_;
      velocity_.linear.y  *= slow_factor_;
      velocity_.linear.z  *= slow_factor_;
      velocity_.angular.z *= slow_factor_;
    }
    velocity_publisher_.publish(velocity_);
  }

  sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr& joy, int axis)
  {
    if (axis == 0) return 0;
    sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
    if (axis < 0) { sign = -1.0; axis = -axis; }
    if ((size_t)axis > joy->axes.size()) return 0;
    return sign * joy->axes[axis - 1];
  }

  sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr& joy, int button)
  {
    if (button <= 0) return 0;
    if ((size_t)button > joy->axes.size()) return 0;
    return joy->buttons[button - 1];
  }

  void stop()
  {
    velocity_ = geometry_msgs::Twist();
    velocity_publisher_.publish(velocity_);
  }
};

} // namespace hector_quadrotor

int main(int argc, char **argv)
{
  ros::init(argc, argv, "quadrotor_teleop");

  hector_quadrotor::Teleop teleop;
  ros::spin();

  return 0;
}
<commit_msg>Add Attitude mode to teleop<commit_after>//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Flight Systems and Automatic Control group,
//       TU Darmstadt, nor the names of its contributors may be used to
//       endorse or promote products derived from this software without
//       specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include <hector_uav_msgs/YawrateCommand.h>
#include <hector_uav_msgs/ThrustCommand.h>
#include <hector_uav_msgs/AttitudeCommand.h>

namespace hector_quadrotor
{

class Teleop
{
private:
  ros::NodeHandle node_handle_;
  ros::Subscriber joy_subscriber_;

  ros::Publisher velocity_publisher_, attitude_publisher_, yawrate_publisher_, thrust_publisher_;
  geometry_msgs::Twist velocity_;
  hector_uav_msgs::AttitudeCommand attitude_;
  hector_uav_msgs::ThrustCommand thrust_;
  hector_uav_msgs::YawrateCommand yawrate_;

  struct Axis
  {
    int axis;
    double max;
  };

  struct Button
  {
    int button;
  };

  struct
  {
    Axis x;
    Axis y;
    Axis z;
    Axis yaw;
  } axes_;

  struct
  {
    Button slow;
  } buttons_;

  double slow_factor_;

public:
  Teleop()
  {
    ros::NodeHandle params("~");

    params.param<int>("x_axis", axes_.x.axis, 4);
    params.param<int>("y_axis", axes_.y.axis, 3);
    params.param<int>("z_axis", axes_.z.axis, 2);
    params.param<int>("yaw_axis", axes_.yaw.axis, 1);

    params.param<double>("yaw_velocity_max", axes_.yaw.max, 90.0 * M_PI / 180.0);
    params.param<int>("slow_button", buttons_.slow.button, 1);
    params.param<double>("slow_factor", slow_factor_, 0.2);

    std::string control_mode_str;
    params.param<std::string>("control_mode", control_mode_str, "twist");

    if (control_mode_str == "twist")
    {
      params.param<double>("x_velocity_max", axes_.x.max, 2.0);
      params.param<double>("y_velocity_max", axes_.y.max, 2.0);
      params.param<double>("z_velocity_max", axes_.z.max, 2.0);

      joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));
      velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
    }
    else if (control_mode_str == "attitude")
    {
      params.param<double>("x_roll_max", axes_.x.max, 0.35);
      params.param<double>("y_pitch_max", axes_.y.max, 0.35);
      params.param<double>("z_thrust_max", axes_.z.max, 25.0);
      joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyAttitudeCallback, this, _1));
      attitude_publisher_ = node_handle_.advertise<hector_uav_msgs::AttitudeCommand>("command/attitude", 10);
      yawrate_publisher_ = node_handle_.advertise<hector_uav_msgs::YawrateCommand>("command/yawrate", 10);
      thrust_publisher_ = node_handle_.advertise<hector_uav_msgs::ThrustCommand>("command/thrust", 10);
    }

  }

  ~Teleop()
  {
    stop();
  }

  void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)
  {
    velocity_.linear.x = getAxis(joy, axes_.x);
    velocity_.linear.y = getAxis(joy, axes_.y);
    velocity_.linear.z = getAxis(joy, axes_.z);
    velocity_.angular.z = getAxis(joy, axes_.yaw);
    if (getButton(joy, buttons_.slow.button))
    {
      velocity_.linear.x *= slow_factor_;
      velocity_.linear.y *= slow_factor_;
      velocity_.linear.z *= slow_factor_;
      velocity_.angular.z *= slow_factor_;
    }
    velocity_publisher_.publish(velocity_);
  }

  void joyAttitudeCallback(const sensor_msgs::JoyConstPtr &joy)
  {
    attitude_.roll = getAxis(joy, axes_.x);
    attitude_.pitch = getAxis(joy, axes_.y);
    attitude_publisher_.publish(attitude_);

    thrust_.thrust = getAxis(joy, axes_.z);
    thrust_publisher_.publish(thrust_);

    yawrate_.turnrate = getAxis(joy, axes_.yaw);
    if (getButton(joy, buttons_.slow.button))
    {
      yawrate_.turnrate *= slow_factor_;
    }
    yawrate_publisher_.publish(yawrate_);
  }

  sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)
  {
    if (axis.axis == 0)
    {return 0;}
    sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
    if (axis.axis < 0)
    {
      sign = -1.0;
      axis.axis = -axis.axis;
    }
    if ((size_t) axis.axis > joy->axes.size())
    {return 0;}
    return sign * joy->axes[axis.axis - 1] * axis.max;
  }

  sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)
  {
    if (button <= 0)
    {return 0;}
    if ((size_t) button > joy->axes.size())
    {return 0;}
    return joy->buttons[button - 1];
  }

  void stop()
  {
    if(velocity_publisher_.getNumSubscribers() > 0)
    {
      velocity_ = geometry_msgs::Twist();
      velocity_publisher_.publish(velocity_);
    }
    if(attitude_publisher_.getNumSubscribers() > 0)
    {
      attitude_ = hector_uav_msgs::AttitudeCommand();
      attitude_publisher_.publish(attitude_);
    }
    if(thrust_publisher_.getNumSubscribers() > 0)
    {
      thrust_ = hector_uav_msgs::ThrustCommand();
      thrust_publisher_.publish(thrust_);
    }
    if(yawrate_publisher_.getNumSubscribers() > 0)
    {
      yawrate_ = hector_uav_msgs::YawrateCommand();
      yawrate_publisher_.publish(yawrate_);
    }

  }
};

} // namespace hector_quadrotor

int main(int argc, char **argv)
{
  ros::init(argc, argv, "quadrotor_teleop");

  hector_quadrotor::Teleop teleop;
  ros::spin();

  return 0;
}
<|endoftext|>


<commit_before>//(c) 2016-2017 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)

#include "output_generator.h"
#include "../sequence/consensus_generator.h"
#include <iomanip>

//Generates FASTA from the given graph paths
std::vector<FastaRecord> OutputGenerator::
	generatePathSequences(const std::vector<UnbranchingPath>& paths) const
{
	std::vector<FastaRecord> contigSequences;

	for (auto& contig : paths)
	{
		//As each edge might correspond to multiple sequences,
		//we need to select them so as to minimize the
		//number of original contigs (that were used to build the graph)
		std::unordered_map<FastaRecord::Id, int> seqIdFreq;
		for (auto& edge : contig.path)
		{
			std::unordered_set<FastaRecord::Id> edgeSeqIds;
			for (auto& seg: edge->seqSegments)
			{
				edgeSeqIds.insert(seg.origSeqId);
			}
			for (auto& seqId : edgeSeqIds)
			{
				seqIdFreq[seqId] += 1;
			}
		}

		std::string nucSequence;
		//ContigPath contigPath;
		//contigPath.name = contig.name();
		//int32_t prevFlank = 0;
		//int32_t prevSubLength = 0;

		for (size_t i = 0; i < contig.path.size(); ++i)
		{
			if (contig.path[i]->seqSegments.empty())
			{
				throw std::runtime_error("Edge without sequence");
			}

			//get the sequence with maximum frequency
			EdgeSequence* bestSegment = nullptr;
			for (auto& seg : contig.path[i]->seqSegments)
			{
				if (!bestSegment ||
					seqIdFreq[seg.origSeqId] > seqIdFreq[bestSegment->origSeqId])
				{
					bestSegment = &seg;
				}
			}
			if (bestSegment->seqLen == 0) continue;
			nucSequence += _graph.edgeSequences()
								.getSeq(bestSegment->edgeSeqId).str();
		}
		//contigParts.push_back(contigPath);
		contigSequences.push_back({DnaSequence(nucSequence), contig.name(),
								  FastaRecord::ID_NONE});
	}

	return contigSequences;
}

void OutputGenerator::outputFasta(const std::vector<UnbranchingPath>& paths,
								  const std::string& filename)
{
	std::vector<UnbranchingPath> posStrandPaths;
	for (auto& path : paths)
	{
		if (path.id.strand()) posStrandPaths.push_back(path);
	}
	SequenceContainer::writeFasta(this->generatePathSequences(posStrandPaths),
								  filename);
}

void OutputGenerator::outputGfa(const std::vector<UnbranchingPath>& paths,
							    const std::string& filename)
{
	auto sequences = this->generatePathSequences(paths);

	Logger::get().debug() << "Writing Gfa";
	FILE* fout = fopen(filename.c_str(), "w");
	if (!fout) throw std::runtime_error("Can't open " + filename);

	fprintf(fout, "H\tVN:Z:1.0\n");
	for (size_t i = 0; i < paths.size(); ++i)
	{
		if (!paths[i].id.strand()) continue;

		//size_t kmerCount = sequences[i].sequence.length() * paths[i].meanCoverage;
		fprintf(fout, "S\t%s\t%s\tdp:i:%d\n", paths[i].name().c_str(),
				sequences[i].sequence.str().c_str(), (int)paths[i].meanCoverage);
	}

	for (auto& contigLeft : paths)
	{
		for (auto& contigRight : paths)
		{
			if (contigLeft.path.back()->nodeRight !=
				contigRight.path.front()->nodeLeft) continue;

			std::string leftSign = contigLeft.id.strand() ? "+" :"-";
			std::string leftName = contigLeft.nameUnsigned();

			std::string rightSign = contigRight.id.strand() ? "+" :"-";
			std::string rightName = contigRight.nameUnsigned();

			fprintf(fout, "L\t%s\t%s\t%s\t%s\t0M\n", leftName.c_str(),
					leftSign.c_str(), rightName.c_str(), rightSign.c_str());
		}
	}
}

void OutputGenerator::outputDot(const std::vector<UnbranchingPath>& paths,
								const std::string& filename)
{
	Logger::get().debug() << "Writing Dot";

	std::ofstream fout(filename);
	if (!fout.is_open()) throw std::runtime_error("Can't open " + filename);

	fout << "digraph {\n";
	fout << "nodesep = 0.5;\n";
	fout << "node [shape = circle, label = \"\", height = 0.3];\n";

	///re-enumerating helper functions
	std::unordered_map<GraphNode*, int> nodeIds;
	int nextNodeId = 0;
	auto nodeToId = [&nodeIds, &nextNodeId](GraphNode* node)
	{
		if (!nodeIds.count(node))
		{
			nodeIds[node] = nextNodeId++;
		}
		return nodeIds[node];
	};

	for (auto& node : _graph.iterNodes())
	{
		if (node->isTelomere())
		{
			fout << "\"" << nodeToId(node)
				<< "\" [style = \"filled\", fillcolor = \"grey\"];\n";
		}
	}

	//coloring repeat clusters
	const std::string COLORS[] = {"red", "darkgreen", "blue", "goldenrod",
								  "cadetblue1", "darkorchid", "aquamarine1",
								  "darkgoldenrod1", "deepskyblue1",
								  "darkolivegreen3"};
	std::vector<GraphEdge*> dfsStack;
	std::unordered_set<GraphEdge*> visited;
	std::unordered_map<GraphEdge*, std::string> edgeColors;
	size_t colorId = 0;
	for (auto& edge: _graph.iterEdges())
	{
		if (!edge->isRepetitive() || visited.count(edge)) continue;
		dfsStack.push_back(edge);
		while(!dfsStack.empty())
		{
			auto curEdge = dfsStack.back();
			dfsStack.pop_back();
			if (visited.count(curEdge)) continue;
			edgeColors[curEdge] = COLORS[colorId];
			edgeColors[_graph.complementEdge(curEdge)] = COLORS[colorId];
			visited.insert(curEdge);
			visited.insert(_graph.complementEdge(curEdge));
			for (auto adjEdge: curEdge->adjacentEdges())
			{
				if (adjEdge->isRepetitive() && !visited.count(adjEdge))
				{
					dfsStack.push_back(adjEdge);
				}
			}
		}
		colorId = (colorId + 1) % (sizeof(COLORS) / sizeof(COLORS[0]));
	}

	for (auto& contig : paths)
	{
		std::stringstream lengthStr;
		if (contig.length < 5000)
		{
			lengthStr << std::fixed << std::setprecision(1)
				<< (float)contig.length / 1000 << "k";
		}
		else
		{
			lengthStr << contig.length / 1000 << "k";
		}
		lengthStr << " " << contig.meanCoverage << "x";

		if (contig.repetitive)
		{
			std::string color = edgeColors[contig.path.front()];
			std::string direction = contig.path.front()->selfComplement ?
									", dir = both" : "";
			fout << "\"" << nodeToId(contig.path.front()->nodeLeft)
				 << "\" -> \"" << nodeToId(contig.path.back()->nodeRight)
				 << "\" [label = \"id " << contig.id.signedId() <<
				 "\\l" << lengthStr.str() << "\", color = \""
				 << color << "\" " << ", penwidth = 3" << direction << "] ;\n";
		}
		else
		{
			fout << "\"" << nodeToId(contig.path.front()->nodeLeft)
				 << "\" -> \"" << nodeToId(contig.path.back()->nodeRight)
				 << "\" [label = \"id " << contig.id.signedId()
				 << "\\l" << lengthStr.str() << "\", color = \"black\"] ;\n";
		}
	}

	fout << "}\n";
}
<commit_msg>don't output complementarly links in gfa<commit_after>//(c) 2016-2017 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)

#include "output_generator.h"
#include "../sequence/consensus_generator.h"
#include <iomanip>

//Generates FASTA from the given graph paths
std::vector<FastaRecord> OutputGenerator::
	generatePathSequences(const std::vector<UnbranchingPath>& paths) const
{
	std::vector<FastaRecord> contigSequences;

	for (auto& contig : paths)
	{
		//As each edge might correspond to multiple sequences,
		//we need to select them so as to minimize the
		//number of original contigs (that were used to build the graph)
		std::unordered_map<FastaRecord::Id, int> seqIdFreq;
		for (auto& edge : contig.path)
		{
			std::unordered_set<FastaRecord::Id> edgeSeqIds;
			for (auto& seg: edge->seqSegments)
			{
				edgeSeqIds.insert(seg.origSeqId);
			}
			for (auto& seqId : edgeSeqIds)
			{
				seqIdFreq[seqId] += 1;
			}
		}

		std::string nucSequence;
		//ContigPath contigPath;
		//contigPath.name = contig.name();
		//int32_t prevFlank = 0;
		//int32_t prevSubLength = 0;

		for (size_t i = 0; i < contig.path.size(); ++i)
		{
			if (contig.path[i]->seqSegments.empty())
			{
				throw std::runtime_error("Edge without sequence");
			}

			//get the sequence with maximum frequency
			EdgeSequence* bestSegment = nullptr;
			for (auto& seg : contig.path[i]->seqSegments)
			{
				if (!bestSegment ||
					seqIdFreq[seg.origSeqId] > seqIdFreq[bestSegment->origSeqId])
				{
					bestSegment = &seg;
				}
			}
			if (bestSegment->seqLen == 0) continue;
			nucSequence += _graph.edgeSequences()
								.getSeq(bestSegment->edgeSeqId).str();
		}
		//contigParts.push_back(contigPath);
		contigSequences.push_back({DnaSequence(nucSequence), contig.name(),
								  FastaRecord::ID_NONE});
	}

	return contigSequences;
}

void OutputGenerator::outputFasta(const std::vector<UnbranchingPath>& paths,
								  const std::string& filename)
{
	std::vector<UnbranchingPath> posStrandPaths;
	for (auto& path : paths)
	{
		if (path.id.strand()) posStrandPaths.push_back(path);
	}
	SequenceContainer::writeFasta(this->generatePathSequences(posStrandPaths),
								  filename);
}

void OutputGenerator::outputGfa(const std::vector<UnbranchingPath>& paths,
							    const std::string& filename)
{
	auto sequences = this->generatePathSequences(paths);

	Logger::get().debug() << "Writing Gfa";
	FILE* fout = fopen(filename.c_str(), "w");
	if (!fout) throw std::runtime_error("Can't open " + filename);

	fprintf(fout, "H\tVN:Z:1.0\n");
	for (size_t i = 0; i < paths.size(); ++i)
	{
		if (!paths[i].id.strand()) continue;

		//size_t kmerCount = sequences[i].sequence.length() * paths[i].meanCoverage;
		fprintf(fout, "S\t%s\t%s\tdp:i:%d\n", paths[i].name().c_str(),
				sequences[i].sequence.str().c_str(), (int)paths[i].meanCoverage);
	}

	std::unordered_set<std::pair<GraphEdge*, GraphEdge*>, pairhash> usedPairs;
	for (auto& contigLeft : paths)
	{
		for (auto& contigRight : paths)
		{
			GraphEdge* edgeLeft = contigLeft.path.back();
			GraphEdge* edgeRight = contigRight.path.front();
			if (edgeLeft->nodeRight != edgeRight->nodeLeft) continue;

			if (usedPairs.count(std::make_pair(edgeLeft, edgeRight))) continue;
			usedPairs.insert(std::make_pair(edgeLeft, edgeRight));
			usedPairs.insert(std::make_pair(_graph.complementEdge(edgeRight),
											_graph.complementEdge(edgeLeft)));

			std::string leftSign = contigLeft.id.strand() ? "+" :"-";
			std::string leftName = contigLeft.nameUnsigned();

			std::string rightSign = contigRight.id.strand() ? "+" :"-";
			std::string rightName = contigRight.nameUnsigned();

			fprintf(fout, "L\t%s\t%s\t%s\t%s\t0M\n", leftName.c_str(),
					leftSign.c_str(), rightName.c_str(), rightSign.c_str());
		}
	}
}

void OutputGenerator::outputDot(const std::vector<UnbranchingPath>& paths,
								const std::string& filename)
{
	Logger::get().debug() << "Writing Dot";

	std::ofstream fout(filename);
	if (!fout.is_open()) throw std::runtime_error("Can't open " + filename);

	fout << "digraph {\n";
	fout << "nodesep = 0.5;\n";
	fout << "node [shape = circle, label = \"\", height = 0.3];\n";

	///re-enumerating helper functions
	std::unordered_map<GraphNode*, int> nodeIds;
	int nextNodeId = 0;
	auto nodeToId = [&nodeIds, &nextNodeId](GraphNode* node)
	{
		if (!nodeIds.count(node))
		{
			nodeIds[node] = nextNodeId++;
		}
		return nodeIds[node];
	};

	for (auto& node : _graph.iterNodes())
	{
		if (node->isTelomere())
		{
			fout << "\"" << nodeToId(node)
				<< "\" [style = \"filled\", fillcolor = \"grey\"];\n";
		}
	}

	//coloring repeat clusters
	const std::string COLORS[] = {"red", "darkgreen", "blue", "goldenrod",
								  "cadetblue1", "darkorchid", "aquamarine1",
								  "darkgoldenrod1", "deepskyblue1",
								  "darkolivegreen3"};
	std::vector<GraphEdge*> dfsStack;
	std::unordered_set<GraphEdge*> visited;
	std::unordered_map<GraphEdge*, std::string> edgeColors;
	size_t colorId = 0;
	for (auto& edge: _graph.iterEdges())
	{
		if (!edge->isRepetitive() || visited.count(edge)) continue;
		dfsStack.push_back(edge);
		while(!dfsStack.empty())
		{
			auto curEdge = dfsStack.back();
			dfsStack.pop_back();
			if (visited.count(curEdge)) continue;
			edgeColors[curEdge] = COLORS[colorId];
			edgeColors[_graph.complementEdge(curEdge)] = COLORS[colorId];
			visited.insert(curEdge);
			visited.insert(_graph.complementEdge(curEdge));
			for (auto adjEdge: curEdge->adjacentEdges())
			{
				if (adjEdge->isRepetitive() && !visited.count(adjEdge))
				{
					dfsStack.push_back(adjEdge);
				}
			}
		}
		colorId = (colorId + 1) % (sizeof(COLORS) / sizeof(COLORS[0]));
	}

	for (auto& contig : paths)
	{
		std::stringstream lengthStr;
		if (contig.length < 5000)
		{
			lengthStr << std::fixed << std::setprecision(1)
				<< (float)contig.length / 1000 << "k";
		}
		else
		{
			lengthStr << contig.length / 1000 << "k";
		}
		lengthStr << " " << contig.meanCoverage << "x";

		if (contig.repetitive)
		{
			std::string color = edgeColors[contig.path.front()];
			std::string direction = contig.path.front()->selfComplement ?
									", dir = both" : "";
			fout << "\"" << nodeToId(contig.path.front()->nodeLeft)
				 << "\" -> \"" << nodeToId(contig.path.back()->nodeRight)
				 << "\" [label = \"id " << contig.id.signedId() <<
				 "\\l" << lengthStr.str() << "\", color = \""
				 << color << "\" " << ", penwidth = 3" << direction << "] ;\n";
		}
		else
		{
			fout << "\"" << nodeToId(contig.path.front()->nodeLeft)
				 << "\" -> \"" << nodeToId(contig.path.back()->nodeRight)
				 << "\" [label = \"id " << contig.id.signedId()
				 << "\\l" << lengthStr.str() << "\", color = \"black\"] ;\n";
		}
	}

	fout << "}\n";
}
<|endoftext|>