Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
	reader pd("../config/config.ini");
	
	camera cam;
  cam.fx = atof(pd.get("camera.fx").c_str());
  cam.fy = atof(pd.get("camera.fy").c_str());
  cam.cx = atof(pd.get("camera.cx").c_str());
  cam.cy = atof(pd.get("camera.cy").c_str());
  cam.scale = atof(pd.get("camera.scale").c_str());
	
	frame frame1, frame2;
	
	frame1.rgb = imread("../data/rgb1.png");
	frame1.depth = imread("../data/depth1.png", -1);
  frame2.rgb = imread("../data/rgb2.png");
  frame2.depth = imread("../data/depth2.png", -1);
  
  cout << "extracting features" << endl;
  string detector = pd.get("detector");
  string descriptor = pd.get("descriptor");
  
  compute_feature(frame1, detector, descriptor);
  compute_feature(frame2, detector, descriptor);
  
  cout << "matching" << endl;
  vector<DMatch> matches;
  match(matches, frame1, frame2);
  
  cout << "solving pnp" << endl;
  pnp result = sfm(cam, matches, frame1, frame2);
  Isometry3d T = cvmat2eigen(result.r, result.t);
  cout << "r: " << result.r << endl << "t: " << result.t << endl;
  
  cout << "converting images into clouds" << endl;
  Pointcloud::Ptr cloud1 = map2point(cam, frame1.rgb, frame1.depth);
  
  cout << "combining clouds" << endl;  
  Pointcloud::Ptr output = joint(cam, cloud1, T, frame2);
  
  io::savePCDFile("../data/result.pcd", *output);
  cout << "result saved." << endl;
  
  visualization::CloudViewer viewer("viewer");
  viewer.showCloud(output);
  
  while(!viewer.wasStopped()) {}
	
	return 0;
}
Ejemplo n.º 2
0
/*!
   \reimp
*/
QSize QAppointmentDelegate::sizeHint(const QStyleOptionViewItem & option,
                                     const QModelIndex &index) const
{
    Q_UNUSED(index);

    QFontMetrics fm(mainFont(option));

#ifndef QTOPIA_PHONE
    QFontMetrics sfm(secondaryFont(option));
    return QSize(fm.width("M") * 10, fm.height() + sfm.height() + 4);
#else
    return QSize(fm.width("M") * 10, fm.height() + 4);  //  Make Qtopia phone more compact
#endif
}
Ejemplo n.º 3
0
QSize
ConfigDelegateBase::sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    int width = QStyledItemDelegate::sizeHint( option, index ).width();

    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, index );


    QFont name = opt.font;
    name.setPointSize( name.pointSize() + 2 );
    name.setBold( true );

    QFont path = opt.font;
    path.setItalic( true );
    path.setPointSize( path.pointSize() - 1 );


    QFontMetrics bfm( name );
    QFontMetrics sfm( path );
    return QSize( width, 2 * PADDING + bfm.height() + sfm.height() );
}
Ejemplo n.º 4
0
QSize CollectionListViewDelegate::trueSizeHint(const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    QFont font = QApplication::font();
    QFontMetrics fm(font);

    QString headerText = index.data(CollectionItem::NameRole).toString();

    QFont subFont(font);
    subFont.setPointSize(font.pointSize() - 2);

    QFontMetrics sfm(subFont);
    QString subText = 	index.data(CollectionItem::SizeTextRole).toString() + " | " + \
    					"subdir: " + index.data(CollectionItem::SubdirTextRole).toString();

    QSize hint;

    hint.setWidth(std::max(fm.width(headerText), sfm.width(subText)));

    hint.setHeight(5 + fm.height() + sfm.height() + 5);

    return(hint);
}
Ejemplo n.º 5
0
/*!
   \overload

   Returns the size hint for objects drawn with the delgate with style options \a option for item at \a index.
*/
QSize TwoLevelDelegate::sizeHint(const QStyleOptionViewItem & option,
        const QModelIndex &index) const
{
    QList< StringPair > subTexts = index.model()->data(index, SubLabelsRole).value<QList<StringPair> >();

    QFontMetrics fm(option.font);
    int sublinesheight = 0;

    if (subTexts.count() > 0) {
        QFont fs = differentFont(option.font, -2);
        QFont bfs = fs;
        bfs.setWeight(QFont::Bold);
        QFontMetrics sbfm(bfs);
        QFontMetrics sfm(fs);
        int sublineheight = qMax(sfm.ascent(), sbfm.ascent()) + qMax(sfm.descent(), sbfm.descent()) + 1;

        sublinesheight = subTexts.count() * (sublineheight + 1);
    }


    return QSize(qApp->style()->pixelMetric(QStyle::PM_ListViewIconSize) + fm.width("M")*10,
                 qMax(qApp->style()->pixelMetric(QStyle::PM_ListViewIconSize), fm.height() + sublinesheight));
}
Ejemplo n.º 6
0
int main(int argc, char* argv[])
{
    try
    {
        nvxio::Application &app = nvxio::Application::get();

        //
        // Parse command line arguments
        //

//        std::string sourceUri = app.findSampleFilePath("file:///dev/video0");

// "/home/ubuntu/VisionWorks-SFM-0.82-Samples/data/sfm/parking_sfm.mp4";


        std::string sourceUri = "/home/px4/test.mp4";
        std::string configFile = app.findSampleFilePath("sfm/sfm_config.ini");
        bool fullPipeline = false;
        std::string maskFile;
        bool noLoop = false;

        app.setDescription("This sample demonstrates Structure from Motion (SfM) algorithm");
        app.addOption(0, "mask", "Optional mask", nvxio::OptionHandler::string(&maskFile));
        app.addBooleanOption('f', "fullPipeline", "Run full SfM pipeline without using IMU data", &fullPipeline);
        app.addBooleanOption('n', "noLoop", "Run sample without loop", &noLoop);

        app.init(argc, argv);

        nvx_module_version_t sfmVersion;
        nvxSfmGetVersion(&sfmVersion);
        std::cout << "VisionWorks SFM version: " << sfmVersion.major << "." << sfmVersion.minor
                  << "." << sfmVersion.patch << sfmVersion.suffix << std::endl;

        std::string imuDataFile;
        std::string frameDataFile;
        if (!fullPipeline)
        {
            imuDataFile = app.findSampleFilePath("sfm/imu_data.txt");
            frameDataFile = app.findSampleFilePath("sfm/images_timestamps.txt");
        }

        if (app.getPreferredRenderName() != "default")
        {
            std::cerr << "The sample uses custom Render for GUI. --nvxio_render option is not supported!" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_RENDER;
        }

        //
        // Read SfMParams
        //

        nvx::SfM::SfMParams params;

        std::string msg;
        if (!read(configFile, params, msg))
        {
            std::cout << msg << std::endl;
            return nvxio::Application::APP_EXIT_CODE_INVALID_VALUE;
        }

        //
        // Create OpenVX context
        //

        nvxio::ContextGuard context;

        //
        // Messages generated by the OpenVX framework will be processed by nvxio::stdoutLogCallback
        //

        vxRegisterLogCallback(context, &nvxio::stdoutLogCallback, vx_false_e);

        //
        // Add SfM kernels
        //

        NVXIO_SAFE_CALL(nvxSfmRegisterKernels(context));

        //
        // Create a Frame Source
        //

        std::unique_ptr<nvxio::FrameSource> source(
             nvxio::createDefaultFrameSource(context, sourceUri));

        if (!source || !source->open())
        {
            std::cout << "Can't open source file: " << sourceUri << std::endl;
//            int haha=3;
//            fprintf(stderr, "errno = %d \n", haha);
            return nvxio::Application::APP_EXIT_CODE_NO_RESOURCE;
        }

        nvxio::FrameSource::Parameters sourceParams = source->getConfiguration();

        //
        // Create OpenVX Image to hold frames from video source
        //

        vx_image frame = vxCreateImage(context,
                                       sourceParams.frameWidth, sourceParams.frameHeight, sourceParams.format);
        NVXIO_CHECK_REFERENCE(frame);

        //
        // Load mask image if needed
        //

        vx_image mask = NULL;
        if (!maskFile.empty())
        {
            mask = nvxio::loadImageFromFile(context, maskFile, VX_DF_IMAGE_U8);

            vx_uint32 mask_width = 0, mask_height = 0;
            vxQueryImage(mask, VX_IMAGE_ATTRIBUTE_WIDTH, &mask_width, sizeof(mask_width));
            vxQueryImage(mask, VX_IMAGE_ATTRIBUTE_HEIGHT, &mask_height, sizeof(mask_height));

            if (mask_width != sourceParams.frameWidth || mask_height != sourceParams.frameHeight)
            {
                std::cerr << "The mask must have the same size as the input source." << std::endl;
                return nvxio::Application::APP_EXIT_CODE_INVALID_DIMENSIONS;
            }
        }

        //
        // Create 3D Render instance
        //
        std::unique_ptr<nvxio::Render3D> render3D(nvxio::createDefaultRender3D(context, 0, 0,
            "SfM Point Cloud", sourceParams.frameWidth, sourceParams.frameHeight));

        nvxio::Render::TextBoxStyle style = {{255, 255, 255, 255}, {0, 0, 0, 255}, {10, 10}};

        if (!render3D)
        {
            std::cerr << "Can't create a renderer" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_RENDER;
        }

        float fovYinRad = 2.f * atanf(sourceParams.frameHeight / 2.f / params.pFy);
        render3D->setDefaultFOV(180.f / nvxio::PI_F * fovYinRad);

        EventData eventData;
        render3D->setOnKeyboardEventCallback(eventCallback, &eventData);

        //
        // Create SfM class instance
        //

        std::unique_ptr<nvx::SfM> sfm(nvx::SfM::createSfM(context, params));

        //
        // Create FenceDetectorWithKF class instance
        //
        FenceDetectorWithKF fenceDetector;


        nvxio::FrameSource::FrameStatus frameStatus;
        do
        {
            frameStatus = source->fetch(frame);
        }
        while (frameStatus == nvxio::FrameSource::TIMEOUT);

        if (frameStatus == nvxio::FrameSource::CLOSED)
        {
            std::cerr << "Source has no frames" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_NO_FRAMESOURCE;
        }

        vx_status status = sfm->init(frame, mask, imuDataFile, frameDataFile);
        if (status != VX_SUCCESS)
        {
            std::cerr << "Failed to initialize the algorithm" << std::endl;
            return nvxio::Application::APP_EXIT_CODE_ERROR;
        }

        const vx_size maxNumOfPoints = 2000;
        const vx_size maxNumOfPlanesVertices = 2000;
        vx_array filteredPoints = vxCreateArray(context, NVX_TYPE_POINT3F, maxNumOfPoints);
        vx_array planesVertices = vxCreateArray(context, NVX_TYPE_POINT3F, maxNumOfPlanesVertices);

        //
        // Run processing loop
        //

        vx_matrix model = vxCreateMatrix(context, VX_TYPE_FLOAT32, 4, 4);
        float eye_data[4*4] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
        vxWriteMatrix(model, eye_data);

        nvxio::Render3D::PointCloudStyle pcStyle = {0, 12};
        nvxio::Render3D::PlaneStyle fStyle = {0, 10};

        GroundPlaneSmoother groundPlaneSmoother(7);

        nvx::Timer totalTimer;
        totalTimer.tic();
        double proc_ms = 0;
        float yGroundPlane = 0;
        while (!eventData.shouldStop)
        {
            if (!eventData.pause)
            {
                frameStatus = source->fetch(frame);

                if (frameStatus == nvxio::FrameSource::TIMEOUT)
                {
                    continue;
                }
                if (frameStatus == nvxio::FrameSource::CLOSED)
                {
                    if(noLoop) break;

                    if (!source->open())
                    {
                        std::cerr << "Failed to reopen the source" << std::endl;
                        break;
                    }

                    do
                    {
                        frameStatus = source->fetch(frame);
                    }
                    while (frameStatus == nvxio::FrameSource::TIMEOUT);

                    sfm->init(frame, mask, imuDataFile, frameDataFile);

                    fenceDetector.reset();

                    continue;
                }

                // Process
                nvx::Timer procTimer;
                procTimer.tic();
                sfm->track(frame, mask);
                proc_ms = procTimer.toc();
            }

            // Print performance results
            sfm->printPerfs();

            if (!eventData.showPointCloud)
            {
                render3D->disableDefaultKeyboardEventCallback();
                render3D->putImage(frame);
            }
            else
            {
                render3D->enableDefaultKeyboardEventCallback();
            }

            filterPoints(sfm->getPointCloud(), filteredPoints);
            render3D->putPointCloud(filteredPoints, model, pcStyle);

            if (eventData.showFences)
            {
                fenceDetector.getFencePlaneVertices(filteredPoints, planesVertices);
                render3D->putPlanes(planesVertices, model, fStyle);
            }

            if (fullPipeline && eventData.showGP)
            {
                const float x1(-1.5), x2(1.5), z1(1), z2(4);

                vx_matrix gp = sfm->getGroundPlane();
                yGroundPlane = groundPlaneSmoother.getSmoothedY(gp, x1, z1);

                nvx_point3f_t pt[4] = {{x1, yGroundPlane, z1},
                                       {x1, yGroundPlane, z2},
                                       {x2, yGroundPlane, z2},
                                       {x2, yGroundPlane, z1}};

                vx_array gpPoints = vxCreateArray(context, NVX_TYPE_POINT3F, 4);
                vxAddArrayItems(gpPoints, 4, pt, sizeof(pt[0]));

                render3D->putPlanes(gpPoints, model, fStyle);
                vxReleaseArray(&gpPoints);
            }

            double total_ms = totalTimer.toc();

            // Add a delay to limit frame rate
            app.sleepToLimitFPS(total_ms);

            total_ms = totalTimer.toc();
            totalTimer.tic();

            std::string state = createInfo(fullPipeline, proc_ms, total_ms, eventData);
            render3D->putText(state.c_str(), style);

            if (!render3D->flush())
            {
                eventData.shouldStop = true;
            }
        }

        //
        // Release all objects
        //
        vxReleaseImage(&frame);
        vxReleaseImage(&mask);
        vxReleaseMatrix(&model);
        vxReleaseArray(&filteredPoints);
        vxReleaseArray(&planesVertices);
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return nvxio::Application::APP_EXIT_CODE_ERROR;
    }

    return nvxio::Application::APP_EXIT_CODE_SUCCESS;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    TCLAP::CmdLine cmd("LINE3D++");

    TCLAP::ValueArg<std::string> inputArg("i", "input_folder", "folder containing the images", true, "", "string");
    cmd.add(inputArg);

    TCLAP::ValueArg<std::string> sfmArg("m", "sfm_folder", "full path to the colmap result files (cameras.txt, images.txt, and points3D.txt), if not specified --> input_folder", false, "", "string");
    cmd.add(sfmArg);

    TCLAP::ValueArg<std::string> outputArg("o", "output_folder", "folder where result and temporary files are stored (if not specified --> sfm_folder+'/Line3D++/')", false, "", "string");
    cmd.add(outputArg);

    TCLAP::ValueArg<int> scaleArg("w", "max_image_width", "scale image down to fixed max width for line segment detection", false, L3D_DEF_MAX_IMG_WIDTH, "int");
    cmd.add(scaleArg);

    TCLAP::ValueArg<int> neighborArg("n", "num_matching_neighbors", "number of neighbors for matching", false, L3D_DEF_MATCHING_NEIGHBORS, "int");
    cmd.add(neighborArg);

    TCLAP::ValueArg<float> sigma_A_Arg("a", "sigma_a", "angle regularizer", false, L3D_DEF_SCORING_ANG_REGULARIZER, "float");
    cmd.add(sigma_A_Arg);

    TCLAP::ValueArg<float> sigma_P_Arg("p", "sigma_p", "position regularizer (if negative: fixed sigma_p in world-coordinates)", false, L3D_DEF_SCORING_POS_REGULARIZER, "float");
    cmd.add(sigma_P_Arg);

    TCLAP::ValueArg<float> epipolarArg("e", "min_epipolar_overlap", "minimum epipolar overlap for matching", false, L3D_DEF_EPIPOLAR_OVERLAP, "float");
    cmd.add(epipolarArg);

    TCLAP::ValueArg<int> knnArg("k", "knn_matches", "number of matches to be kept (<= 0 --> use all that fulfill overlap)", false, L3D_DEF_KNN, "int");
    cmd.add(knnArg);

    TCLAP::ValueArg<int> segNumArg("y", "num_segments_per_image", "maximum number of 2D segments per image (longest)", false, L3D_DEF_MAX_NUM_SEGMENTS, "int");
    cmd.add(segNumArg);

    TCLAP::ValueArg<int> visibilityArg("v", "visibility_t", "minimum number of cameras to see a valid 3D line", false, L3D_DEF_MIN_VISIBILITY_T, "int");
    cmd.add(visibilityArg);

    TCLAP::ValueArg<bool> diffusionArg("d", "diffusion", "perform Replicator Dynamics Diffusion before clustering", false, L3D_DEF_PERFORM_RDD, "bool");
    cmd.add(diffusionArg);

    TCLAP::ValueArg<bool> loadArg("l", "load_and_store_flag", "load/store segments (recommended for big images)", false, L3D_DEF_LOAD_AND_STORE_SEGMENTS, "bool");
    cmd.add(loadArg);

    TCLAP::ValueArg<float> collinArg("r", "collinearity_t", "threshold for collinearity", false, L3D_DEF_COLLINEARITY_T, "float");
    cmd.add(collinArg);

    TCLAP::ValueArg<bool> cudaArg("g", "use_cuda", "use the GPU (CUDA)", false, true, "bool");
    cmd.add(cudaArg);

    TCLAP::ValueArg<bool> ceresArg("c", "use_ceres", "use CERES (for 3D line optimization)", false, L3D_DEF_USE_CERES, "bool");
    cmd.add(ceresArg);

    TCLAP::ValueArg<float> minBaselineArg("x", "min_image_baseline", "minimum baseline between matching images (world space)", false, L3D_DEF_MIN_BASELINE, "float");
    cmd.add(minBaselineArg);

    TCLAP::ValueArg<float> constRegDepthArg("z", "const_reg_depth", "use a constant regularization depth (only when sigma_p is metric!)", false, -1.0f, "float");
    cmd.add(constRegDepthArg);

    // read arguments
    cmd.parse(argc,argv);
    std::string inputFolder = inputArg.getValue().c_str();
    std::string sfmFolder = sfmArg.getValue().c_str();

    if(sfmFolder.length() == 0)
        sfmFolder = inputFolder;

    // check if colmap result folder
    boost::filesystem::path sfm(sfmFolder);
    if(!boost::filesystem::exists(sfm))
    {
        std::cerr << "colmap result folder " << sfm << " does not exist!" << std::endl;
        return -1;
    }

    std::string outputFolder = outputArg.getValue().c_str();
    if(outputFolder.length() == 0)
        outputFolder = sfmFolder+"/Line3D++/";

    int maxWidth = scaleArg.getValue();
    unsigned int neighbors = std::max(neighborArg.getValue(),2);
    bool diffusion = diffusionArg.getValue();
    bool loadAndStore = loadArg.getValue();
    float collinearity = collinArg.getValue();
    bool useGPU = cudaArg.getValue();
    bool useCERES = ceresArg.getValue();
    float epipolarOverlap = fmin(fabs(epipolarArg.getValue()),0.99f);
    float sigmaA = fabs(sigma_A_Arg.getValue());
    float sigmaP = sigma_P_Arg.getValue();
    float minBaseline = fabs(minBaselineArg.getValue());
    int kNN = knnArg.getValue();
    unsigned int maxNumSegments = segNumArg.getValue();
    unsigned int visibility_t = visibilityArg.getValue();
    float constRegDepth = constRegDepthArg.getValue();

    // create output directory
    boost::filesystem::path dir(outputFolder);
    boost::filesystem::create_directory(dir);

    // create Line3D++ object
    L3DPP::Line3D* Line3D = new L3DPP::Line3D(outputFolder,loadAndStore,maxWidth,
                                              maxNumSegments,true,useGPU);

    // check if result files exist
    boost::filesystem::path sfm_cameras(sfmFolder+"/cameras.txt");
    boost::filesystem::path sfm_images(sfmFolder+"/images.txt");
    boost::filesystem::path sfm_points3D(sfmFolder+"/points3D.txt");
    if(!boost::filesystem::exists(sfm_cameras) || !boost::filesystem::exists(sfm_images) ||
            !boost::filesystem::exists(sfm_points3D))
    {
        std::cerr << "at least one of the colmap result files does not exist in sfm folder: " << sfm << std::endl;
        return -2;
    }

    std::cout << std::endl << "reading colmap result..." << std::endl;

    // read cameras.txt
    std::ifstream cameras_file;
    cameras_file.open(sfm_cameras.c_str());
    std::string cameras_line;

    std::map<unsigned int,Eigen::Matrix3d> cams_K;
    std::map<unsigned int,Eigen::Vector3d> cams_radial;
    std::map<unsigned int,Eigen::Vector2d> cams_tangential;

    while(std::getline(cameras_file,cameras_line))
    {
        // check first character for a comment (#)
        if(cameras_line.substr(0,1).compare("#") != 0)
        {
            std::stringstream cameras_stream(cameras_line);

            unsigned int camID,width,height;
            std::string model;

            // parse essential data
            cameras_stream >> camID >> model >> width >> height;

            double fx,fy,cx,cy,k1,k2,k3,p1,p2;

            // check camera model
            if(model.compare("SIMPLE_PINHOLE") == 0)
            {
                // f,cx,cy
                cameras_stream >> fx >> cx >> cy;
                fy = fx;
                k1 = 0; k2 = 0; k3 = 0;
                p1 = 0; p2 = 0;
            }
            else if(model.compare("PINHOLE") == 0)
  void UncoupledAggregationFactory<LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Build(Level &currentLevel) const {
    FactoryMonitor m(*this, "Build", currentLevel);

    ParameterList pL = GetParameterList();
    bDefinitionPhase_ = false;  // definition phase is finished, now all aggregation algorithm information is fixed

    // define aggregation algorithms
    RCP<const FactoryBase> graphFact = GetFactory("Graph");

    // TODO Can we keep different aggregation algorithms over more Build calls?
    algos_.clear();
    if (pL.get<std::string>("aggregation: mode") == "old") {
      if (pL.get<bool>("UseOnePtAggregationAlgorithm")             == true)   algos_.push_back(rcp(new OnePtAggregationAlgorithm             (graphFact)));
      if (pL.get<bool>("UsePreserveDirichletAggregationAlgorithm") == true)   algos_.push_back(rcp(new PreserveDirichletAggregationAlgorithm (graphFact)));
      if (pL.get<bool>("UseUncoupledAggregationAlgorithm")         == true)   algos_.push_back(rcp(new AggregationPhase1Algorithm            (graphFact)));
      if (pL.get<bool>("UseMaxLinkAggregationAlgorithm")           == true)   algos_.push_back(rcp(new MaxLinkAggregationAlgorithm           (graphFact)));
      if (pL.get<bool>("UseEmergencyAggregationAlgorithm")         == true)   algos_.push_back(rcp(new EmergencyAggregationAlgorithm         (graphFact)));
                                                                              algos_.push_back(rcp(new IsolatedNodeAggregationAlgorithm      (graphFact)));

    } else {
      if (pL.get<bool>("aggregation: preserve Dirichlet points")   == true)   algos_.push_back(rcp(new PreserveDirichletAggregationAlgorithm (graphFact)));
      if (pL.get<bool>("aggregation: enable phase 1" )             == true)   algos_.push_back(rcp(new AggregationPhase1Algorithm            (graphFact)));
      if (pL.get<bool>("aggregation: enable phase 2a")             == true)   algos_.push_back(rcp(new AggregationPhase2aAlgorithm           (graphFact)));
      if (pL.get<bool>("aggregation: enable phase 2b")             == true)   algos_.push_back(rcp(new AggregationPhase2bAlgorithm           (graphFact)));
      if (pL.get<bool>("aggregation: enable phase 3" )             == true)   algos_.push_back(rcp(new AggregationPhase3Algorithm            (graphFact)));
                                                                              algos_.push_back(rcp(new IsolatedNodeAggregationAlgorithm      (graphFact)));
    }

    std::string mapOnePtName = pL.get<std::string>("OnePt aggregate map name");
    RCP<const Map> OnePtMap;
    if (mapOnePtName.length()) {
      RCP<const FactoryBase> mapOnePtFact = GetFactory("OnePt aggregate map factory");
      OnePtMap = currentLevel.Get<RCP<const Map> >(mapOnePtName, mapOnePtFact.get());
    }

    RCP<const GraphBase> graph = Get< RCP<GraphBase> >(currentLevel, "Graph");

    // Build
    RCP<Aggregates> aggregates = rcp(new Aggregates(*graph));
    aggregates->setObjectLabel("UC");

    const LO numRows = graph->GetNodeNumVertices();

    // construct aggStat information
    std::vector<unsigned> aggStat(numRows, READY);

    ArrayRCP<const bool> dirichletBoundaryMap = graph->GetBoundaryNodeMap();
    if (dirichletBoundaryMap != Teuchos::null)
      for (LO i = 0; i < numRows; i++)
        if (dirichletBoundaryMap[i] == true)
          aggStat[i] = BOUNDARY;

    LO nDofsPerNode = Get<LO>(currentLevel, "DofsPerNode");
    GO indexBase = graph->GetDomainMap()->getIndexBase();
    if (OnePtMap != Teuchos::null) {
      for (LO i = 0; i < numRows; i++) {
        // reconstruct global row id (FIXME only works for contiguous maps)
        GO grid = (graph->GetDomainMap()->getGlobalElement(i)-indexBase) * nDofsPerNode + indexBase;

        for (LO kr = 0; kr < nDofsPerNode; kr++)
          if (OnePtMap->isNodeGlobalElement(grid + kr))
            aggStat[i] = ONEPT;
      }
    }


    const RCP<const Teuchos::Comm<int> > comm = graph->GetComm();
    GO numGlobalRows = 0;
    if (IsPrint(Statistics1))
      sumAll(comm, as<GO>(numRows), numGlobalRows);

    LO numNonAggregatedNodes = numRows;
    GO numGlobalAggregatedPrev = 0, numGlobalAggsPrev = 0;
    for (size_t a = 0; a < algos_.size(); a++) {
      std::string phase = algos_[a]->description();
      SubFactoryMonitor sfm(*this, "Algo \"" + phase + "\"", currentLevel);

      algos_[a]->BuildAggregates(pL, *graph, *aggregates, aggStat, numNonAggregatedNodes);

      if (IsPrint(Statistics1)) {

        GO numLocalAggregated = numRows - numNonAggregatedNodes, numGlobalAggregated = 0;
        GO numLocalAggs       = aggregates->GetNumAggregates(),  numGlobalAggs = 0;
        sumAll(comm, numLocalAggregated, numGlobalAggregated);
        sumAll(comm, numLocalAggs,       numGlobalAggs);

        double aggPercent = 100*as<double>(numGlobalAggregated)/as<double>(numGlobalRows);
        if (aggPercent > 99.99 && aggPercent < 100.00) {
          // Due to round off (for instance, for 140465733/140466897), we could
          // get 100.00% display even if there are some remaining nodes. This
          // is bad from the users point of view. It is much better to change
          // it to display 99.99%.
          aggPercent = 99.99;
        }
        GetOStream(Statistics1) << "  aggregated : " << (numGlobalAggregated - numGlobalAggregatedPrev) << " (phase), " << std::fixed
                                   << std::setprecision(2) << numGlobalAggregated << "/" << numGlobalRows << " [" << aggPercent << "%] (total)\n"
                                   << "  remaining  : " << numGlobalRows - numGlobalAggregated << "\n"
                                   << "  aggregates : " << numGlobalAggs-numGlobalAggsPrev << " (phase), " << numGlobalAggs << " (total)" << std::endl;
        numGlobalAggregatedPrev = numGlobalAggregated;
        numGlobalAggsPrev       = numGlobalAggs;
      }
    }

    TEUCHOS_TEST_FOR_EXCEPTION(numNonAggregatedNodes, Exceptions::RuntimeError, "MueLu::UncoupledAggregationFactory::Build: Leftover nodes found! Error!");

    aggregates->AggregatesCrossProcessors(false);

    Set(currentLevel, "Aggregates", aggregates);

    GetOStream(Statistics0) << aggregates->description() << std::endl;
  }
  void UncoupledAggregationFactory<LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Build(Level &currentLevel) const {
    FactoryMonitor m(*this, "Build", currentLevel);

    const ParameterList& pL = GetParameterList();
    bDefinitionPhase_ = false;  // definition phase is finished, now all aggregation algorithm information is fixed

    bool bUseOnePtAggregationAlgorithm             = pL.get<bool>("UseOnePtAggregationAlgorithm");
    bool bUseSmallAggregationAlgorithm             = pL.get<bool>("UseSmallAggregatesAggregationAlgorithm");
    bool bUsePreserveDirichletAggregationAlgorithm = pL.get<bool>("UsePreserveDirichletAggregationAlgorithm");
    bool bUseUncoupledAggregationAglorithm         = pL.get<bool>("UseUncoupledAggregationAlgorithm");
    bool bUseMaxLinkAggregationAlgorithm           = pL.get<bool>("UseMaxLinkAggregationAlgorithm");
    bool bUseIsolatedNodeAggregationAglorithm      = pL.get<bool>("UseIsolatedNodeAggregationAlgorithm");
    bool bUseEmergencyAggregationAlgorithm         = pL.get<bool>("UseEmergencyAggregationAlgorithm");

    // define aggregation algorithms
    RCP<const FactoryBase> graphFact = GetFactory("Graph");

    // TODO Can we keep different aggregation algorithms over more Build calls?
    algos_.clear();
    if (bUseOnePtAggregationAlgorithm)             algos_.push_back(rcp(new OnePtAggregationAlgorithm             (graphFact)));
    if (bUseSmallAggregationAlgorithm)             algos_.push_back(rcp(new SmallAggregationAlgorithm             (graphFact)));
    if (bUseUncoupledAggregationAglorithm)         algos_.push_back(rcp(new UncoupledAggregationAlgorithm         (graphFact)));
    if (bUseMaxLinkAggregationAlgorithm)           algos_.push_back(rcp(new MaxLinkAggregationAlgorithm           (graphFact)));
    if (bUsePreserveDirichletAggregationAlgorithm) algos_.push_back(rcp(new PreserveDirichletAggregationAlgorithm (graphFact)));
    if (bUseIsolatedNodeAggregationAglorithm)      algos_.push_back(rcp(new IsolatedNodeAggregationAlgorithm      (graphFact)));
    if (bUseEmergencyAggregationAlgorithm)         algos_.push_back(rcp(new EmergencyAggregationAlgorithm         (graphFact)));


    std::string mapOnePtName = pL.get<std::string>("OnePt aggregate map name"), mapSmallAggName = pL.get<std::string>("SmallAgg aggregate map name");
    RCP<const Map> OnePtMap, SmallAggMap;
    if (mapOnePtName.length()) {
      RCP<const FactoryBase> mapOnePtFact = GetFactory("OnePt aggregate map factory");
      OnePtMap = currentLevel.Get<RCP<const Map> >(mapOnePtName, mapOnePtFact.get());
    }
    if (mapSmallAggName.length()) {
      RCP<const FactoryBase> mapSmallAggFact = GetFactory("SmallAgg aggregate map factory");
      SmallAggMap = currentLevel.Get<RCP<const Map> >(mapSmallAggName, mapSmallAggFact.get());
    }

    RCP<const GraphBase> graph = Get< RCP<GraphBase> >(currentLevel, "Graph");

    // Build
    RCP<Aggregates> aggregates = rcp(new Aggregates(*graph));
    aggregates->setObjectLabel("UC");

    const LO nRows = graph->GetNodeNumVertices();

    // construct aggStat information
    std::vector<unsigned> aggStat(nRows, NodeStats::READY);

    ArrayRCP<const bool> dirichletBoundaryMap = graph->GetBoundaryNodeMap();
    if (dirichletBoundaryMap != Teuchos::null) {
      for (LO i = 0; i < nRows; i++)
        if (dirichletBoundaryMap[i] == true)
          aggStat[i] = NodeStats::BOUNDARY;
    }

    LO nDofsPerNode = Get<LO>(currentLevel, "DofsPerNode");
    GO indexBase = graph->GetDomainMap()->getIndexBase();
    if (SmallAggMap != Teuchos::null || OnePtMap != Teuchos::null) {
      for (LO i = 0; i < nRows; i++) {
        // reconstruct global row id (FIXME only works for contiguous maps)
        GO grid = (graph->GetDomainMap()->getGlobalElement(i)-indexBase) * nDofsPerNode + indexBase;

        if (SmallAggMap != null) {
          for (LO kr = 0; kr < nDofsPerNode; kr++) {
            if (SmallAggMap->isNodeGlobalElement(grid + kr))
              aggStat[i] = MueLu::NodeStats::SMALLAGG;
          }
        }

        if (OnePtMap != null) {
          for (LO kr = 0; kr < nDofsPerNode; kr++) {
            if (OnePtMap->isNodeGlobalElement(grid + kr))
              aggStat[i] = MueLu::NodeStats::ONEPT;
          }
        }
      }
    }


    const RCP<const Teuchos::Comm<int> > comm = graph->GetComm();
    GO numGlobalRows = 0;
    if (IsPrint(Statistics1))
      sumAll(comm, as<GO>(nRows), numGlobalRows);

    LO numNonAggregatedNodes = nRows;
    GO numGlobalAggregatedPrev = 0, numGlobalAggsPrev = 0;
    for (size_t a = 0; a < algos_.size(); a++) {
      std::string phase = algos_[a]->description();
      SubFactoryMonitor sfm(*this, "Algo \"" + phase + "\"", currentLevel);

      algos_[a]->BuildAggregates(pL, *graph, *aggregates, aggStat, numNonAggregatedNodes);

      if (IsPrint(Statistics1)) {

        GO numLocalAggregated = nRows - numNonAggregatedNodes,  numGlobalAggregated = 0;
        GO numLocalAggs       = aggregates->GetNumAggregates(), numGlobalAggs = 0;
        sumAll(comm, numLocalAggregated, numGlobalAggregated);
        sumAll(comm, numLocalAggs,       numGlobalAggs);

        double aggPercent = 100*as<double>(numGlobalAggregated)/as<double>(numGlobalRows);
        GetOStream(Statistics1) << "  aggregated : " << (numGlobalAggregated - numGlobalAggregatedPrev) << " (phase), " << std::fixed
                                   << std::setprecision(2) << numGlobalAggregated << "/" << numGlobalRows << " [" << aggPercent << "%] (total)\n"
                                   << "  remaining  : " << numGlobalRows - numGlobalAggregated << "\n"
                                   << "  aggregates : " << numGlobalAggs-numGlobalAggsPrev << " (phase), " << numGlobalAggs << " (total)" << std::endl;
        numGlobalAggregatedPrev = numGlobalAggregated;
        numGlobalAggsPrev       = numGlobalAggs;
      }
    }

    TEUCHOS_TEST_FOR_EXCEPTION(numNonAggregatedNodes, Exceptions::RuntimeError, "MueLu::UncoupledAggregationFactory::Build: Leftover nodes found! Error!");

    aggregates->AggregatesCrossProcessors(false);

    Set(currentLevel, "Aggregates", aggregates);

    GetOStream(Statistics0) << aggregates->description() << std::endl;
  }
Ejemplo n.º 10
0
void CollectionListViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	painter->save();

	if (option.state & QStyle::State_Selected)
	{
		painter->fillRect(option.rect, option.palette.highlight());
		painter->setPen(option.palette.highlightedText().color());
	}


	QFont font = QApplication::font();
	QFontMetrics fm(font);

	QFont subFont(font);
	subFont.setPointSize(font.pointSize() - 2);

	QFontMetrics sfm(subFont);


	QString headerText = index.data(CollectionItem::NameRole).toString();

	QString subText = 	index.data(CollectionItem::SizeTextRole).toString() + " | " + \
						"subdir: " + index.data(CollectionItem::SubdirTextRole).toString();

	QSize trueSize(trueSizeHint(option, index));
	QSize size(sizeHint(option, index));

	if (trueSize.width() != size.width())
	{
		int n = 0;

		if (fm.width(headerText) > size.width())
		{
			for (n = headerText.size(); fm.width(QString(headerText.left(n) + "...")) > option.rect.width(); n--);
			headerText = headerText.left(n) + "...";
		}
	}

	QTextOption textOption(Qt::AlignHCenter);

	QRect basicRect = option.rect;

	if (option.rect.width() > collectionListView->width())
	{
		if (size.width() <= collectionListView->width())
		{
			basicRect.setLeft(0);
			basicRect.setRight(collectionListView->width());
		}
	}

	QRect headerRect = basicRect;

	headerRect.setTop(headerRect.top()+5);
	headerRect.setBottom(headerRect.top()+fm.height());

	QRect subRect = basicRect;

	subRect.setTop(headerRect.bottom());
	subRect.setBottom(subRect.top() + sfm.height());


	painter->setFont(font);
	painter->drawText(headerRect,headerText, textOption);


	painter->setFont(subFont);
	painter->drawText(subRect,subText, textOption);

	painter->restore();

}