<commit_before>/*
 * Copyright (C) 2016 Rhys Ulerich
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <iterator>

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <descendu/hexmap.hpp>
#include <descendu/tile.hpp>

using namespace descendu;

TEST_CASE( "hexmap" ) {

    hexmap<tile> m;
    typedef hexmap<tile>::key_type key_type;

    SECTION( "conjure" ) {
        // Empty on construction
        REQUIRE( m.cbegin() == m.cend() );

        // Insertion with explicit type
        m.conjure(key_type(0, 0));
        auto a = m.cbegin();
        std::advance(a, 1);
        REQUIRE( a == m.cend() );
        REQUIRE( 1 == m.size() );

        // Idempotent re-insertion
        m.conjure(key_type(0, 0));
        auto b = m.cbegin();
        std::advance(b, 1);
        REQUIRE( b == m.cend() );
        REQUIRE( 1 == m.size() );

        // Insertion with nicety provided by hex
        m.conjure(key_type(1, 0));
        auto c = m.cbegin();
        std::advance(c, 2);
        REQUIRE( c == m.cend() );
        REQUIRE( 2 == m.size() );
    }

    SECTION( "mutable" ) {
        auto& a = m.conjure({0, 0});
        a.cannon.increase(1);
        REQUIRE( a.cannon.total() == 1 );

        auto& b = m.lookup({0, 0}).value();
        REQUIRE( b.cannon.total() == 1 );

        // No clobber of existing entry
        auto& c = m.conjure({0, 0});
        REQUIRE( c.cannon.total() == 1 );
    }

    SECTION( "not_found" ) {
        REQUIRE( !m.lookup({0, 0}).has_value() );
        REQUIRE( !m.lookup({0, 0}) );
    }

}

TEST_CASE( "breadth_first_search" ) {

    hexmap<int> m;
    typedef hexmap<tile>::key_type key_type;

    SECTION( "origin_in_map" ) {
        // Add origin
        m.conjure({0, 0});
        // Search
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        // Considered origin
        REQUIRE( retval.size() == 1 );
        // Origin considered and provides self-referencing path
        REQUIRE( retval.lookup({0, 0}) );
        REQUIRE( retval.lookup({0, 0}).value() == key_type(0, 0) );

    }

    SECTION( "origin_not_in_map" ) {
        // Origin not added
        // Search
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        // Considered origin
        REQUIRE( retval.size() == 1 );
        // Considered origin involves and empty optional
        REQUIRE( !retval.lookup({0, 0}).value() );
    }

    SECTION( "linear" ) {
        m.conjure({+0, +0});
        m.conjure({+0, -1});
        m.conjure({+0, -2});
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        REQUIRE( retval.size() == 3 );
        REQUIRE( retval.lookup({+0, -2}).value() == key_type(+0, -1) );
        REQUIRE( retval.lookup({+0, -1}).value() == key_type(+0, +0) );
        REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );
    }

    SECTION( "outward" ) {
        m.conjure({+0, +0});
        m.conjure({+0, -1});
        m.conjure({+1, -1});
        m.conjure({+1, +0});
        m.conjure({+0, +1});
        m.conjure({-1, +1});
        m.conjure({-1, +0});
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        REQUIRE( retval.size() == 7 );
        REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );
        // TODO FIXME
        // REQUIRE( retval.lookup({+0, -1}).value().value() == key_type(+0, +0) );
        // REQUIRE( retval.lookup({+1, -1}).value().value() == key_type(+0, +0) );
        // REQUIRE( retval.lookup({+1, +0}).value().value() == key_type(+0, +0) );
        // REQUIRE( retval.lookup({+0, +1}).value().value() == key_type(+0, +0) );
        // REQUIRE( retval.lookup({-1, +1}).value().value() == key_type(+0, +0) );
        // REQUIRE( retval.lookup({-1, +0}).value().value() == key_type(+0, +0) );
    }

}
<commit_msg>Beef up line search testing<commit_after>/*
 * Copyright (C) 2016 Rhys Ulerich
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <iterator>

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <descendu/hexmap.hpp>
#include <descendu/tile.hpp>

using namespace descendu;

TEST_CASE( "hexmap" ) {

    hexmap<tile> m;
    typedef hexmap<tile>::key_type key_type;

    SECTION( "conjure" ) {
        // Empty on construction
        REQUIRE( m.cbegin() == m.cend() );

        // Insertion with explicit type
        m.conjure(key_type(0, 0));
        auto a = m.cbegin();
        std::advance(a, 1);
        REQUIRE( a == m.cend() );
        REQUIRE( 1 == m.size() );

        // Idempotent re-insertion
        m.conjure(key_type(0, 0));
        auto b = m.cbegin();
        std::advance(b, 1);
        REQUIRE( b == m.cend() );
        REQUIRE( 1 == m.size() );

        // Insertion with nicety provided by hex
        m.conjure(key_type(1, 0));
        auto c = m.cbegin();
        std::advance(c, 2);
        REQUIRE( c == m.cend() );
        REQUIRE( 2 == m.size() );
    }

    SECTION( "mutable" ) {
        auto& a = m.conjure({0, 0});
        a.cannon.increase(1);
        REQUIRE( a.cannon.total() == 1 );

        auto& b = m.lookup({0, 0}).value();
        REQUIRE( b.cannon.total() == 1 );

        // No clobber of existing entry
        auto& c = m.conjure({0, 0});
        REQUIRE( c.cannon.total() == 1 );
    }

    SECTION( "not_found" ) {
        REQUIRE( !m.lookup({0, 0}).has_value() );
        REQUIRE( !m.lookup({0, 0}) );
    }

}

TEST_CASE( "breadth_first_search" ) {

    hexmap<int> m;
    typedef hexmap<tile>::key_type key_type;

    SECTION( "origin_in_map" ) {
        // Add origin
        m.conjure({0, 0});
        // Search
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        // Considered origin
        REQUIRE( retval.size() == 1 );
        // Origin considered and provides self-referencing path
        REQUIRE( retval.lookup({0, 0}) );
        REQUIRE( retval.lookup({0, 0}).value() == key_type(0, 0) );

    }

    SECTION( "origin_not_in_map" ) {
        // Origin not added
        // Search
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        // Considered origin
        REQUIRE( retval.size() == 1 );
        // Considered origin involves and empty optional
        REQUIRE( !retval.lookup({0, 0}).value() );
    }

    SECTION( "linear_one_direction" ) {
        m.conjure({+0, +0});
        m.conjure({+0, -1});
        m.conjure({+0, -2});
        const auto& retval = breadth_first_search(
            m,
            key_type(0, 0),
            [](const auto&) { return search_result::include; },
            555);
        REQUIRE( retval.size() == 3 );
        REQUIRE( retval.lookup({+0, -2}).value() == key_type(+0, -1) );
        REQUIRE( retval.lookup({+0, -1}).value() == key_type(+0, +0) );
        REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );
    }

    SECTION( "linear_all_directions" ) {
        const auto& p0 = key_type(+3, +3);
        const std::vector<int> directions = {0, 1, 2, 3, 4, 5};
        for (const auto direction : directions) {
            // Construct 4 edges in the given direction
            hexmap<int> o;
            o.conjure(p0);
            const auto& p1 = p0.neighbor(direction);
            o.conjure(p1);
            const auto& p2 = p1.neighbor(direction);
            o.conjure(p2);
            const auto& p3 = p2.neighbor(direction);
            o.conjure(p3);
            const auto& p4 = p3.neighbor(direction);
            o.conjure(p4);
            // Search three edges in the direction
            const auto& retval = breadth_first_search(
                o,
                p0,
                [](const auto&) { return search_result::include; },
                3);
            // Origin plus 3 close-enough edges
            REQUIRE( retval.size() == 4 );
            REQUIRE( retval.lookup(p3).value().value() == p2 );
            REQUIRE( retval.lookup(p2).value().value() == p1 );
            REQUIRE( retval.lookup(p1).value().value() == p0 );
            REQUIRE( retval.lookup(p0).value().value() == p0 );
            // Fourth edge was too far
            REQUIRE( !retval.lookup(p4) );
        }
    }

//  SECTION( "outward" ) {
//      m.conjure({+0, +0});
//      m.conjure({+1, +0});
//      m.conjure({+1, -1});
//      m.conjure({+0, -1});
//      m.conjure({-1, +0});
//      m.conjure({-1, +1});
//      m.conjure({+0, +1});
//      const auto& retval = breadth_first_search(
//          m,
//          key_type(0, 0),
//          [](const auto&) { return search_result::include; },
//          555);
//      REQUIRE( retval.size() == 7 );
//      REQUIRE( retval.lookup({+0, +0}).value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({+1, +0}).value().value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({+1, -1}).value().value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({+0, -1}).value().value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({-1, +0}).value().value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({-1, +1}).value().value() == key_type(+0, +0) );
//      REQUIRE( retval.lookup({+0, +1}).value().value() == key_type(+0, +0) );
//  }

}
<|endoftext|>


<commit_before>// Reminder program of C++ fundamentals.
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}
<commit_msg>Terminating newline.<commit_after>// Reminder program of C++ fundamentals.
#include <iostream>

int main()
{
  std::cout << "Hello World!" << std::endl;
}
<|endoftext|>


<commit_before>// Register adjacent HiRes images to each other,
// initialised by loaded transforms from previous registration

#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"

// my files
#include "Stack.hpp"
#include "RegistrationBuilder.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "StackTransforms.hpp"
#include "Dirs.hpp"
#include "OptimizerConfig.hpp"
#include "ScaleImages.hpp"
#include "SimpleTransformWriter.hpp"
#include "MetricValueWriter.hpp"

using namespace boost::filesystem;
namespace po = boost::program_options;
using namespace boost;

// function declarations
po::variables_map parse_arguments(int argc, char *argv[]);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

  // Process command line arguments
  Dirs::SetDataSet(argv[1]);
  Dirs::SetOutputDirName(argv[2]);
  string transform = vm["transform"].as<string>();
  string roi = vm.count("roi") ? vm["roi"].as<string>() : "ROI";

  // for globally available registrationParameters(),
  // used in e.g. OptimizerConfig
  Dirs::SetParamsFile( Dirs::ConfigDir() + "HiRes_pair_parameters.yml" );

  // construct basenames and paths
  vector< string > basenames = getBasenames(Dirs::ImageList());
  vector< string > paths = constructPaths(Dirs::SliceDir(), basenames, ".bmp");

  // initialise stack with correct spacings, sizes, basenames etc
  typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
  StackType::SliceVectorType originalImages = readImages< StackType::SliceType >(paths);
  scaleImages< StackType::SliceType >(originalImages, getSpacings<2>("HiRes"));
  shared_ptr< StackType > originalStack = make_shared< StackType >(originalImages, getSpacings<3>("LoRes"), getSize(roi));
  originalStack->SetBasenames(basenames);

  Load(*originalStack, Dirs::HiResTransformsDir() + transform + "/");

  // move stack origins to ROI
  itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation("whole_heart");
  StackTransforms::Translate(*originalStack, translation);

  // generate images
  originalStack->updateVolumes();

  // construct 2 stacks from resampled images: 1:n-1 and 2:n
  StackType::SliceVectorType resampledImages = originalStack->GetResampledSlices();
  StackType::SliceVectorType fixedImages(++resampledImages.begin(), resampledImages.end());
  StackType::SliceVectorType movingImages(resampledImages.begin(), --resampledImages.end());
  StackType::MaskVectorType2D resampledMasks = originalStack->GetResampled2DMasks();
  StackType::MaskVectorType2D fixedMasks(++resampledMasks.begin(), resampledMasks.end());
  StackType::MaskVectorType2D movingMasks(resampledMasks.begin(), --resampledMasks.end());
  shared_ptr< StackType > fixedStack  = make_shared< StackType >(fixedImages,  fixedMasks,  getSpacings<3>("LoRes"), getSize(roi));
  shared_ptr< StackType > movingStack = make_shared< StackType >(movingImages, movingMasks, getSpacings<3>("LoRes"), getSize(roi));

  // Build registration
  typedef RegistrationBuilder< StackType > RegistrationBuilderType;
  RegistrationBuilderType registrationBuilder;
  RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();

  // Initialize both stacks with CenteredRigid2DTransform
  StackTransforms::InitializeToCommonCentre(*fixedStack);
  StackTransforms::InitializeToCommonCentre(*movingStack);

  // Configure moving centre and optimiser scales
  StackTransforms::SetMovingStackCenterWithFixedStack( *fixedStack, *movingStack );

  // Convert moving CenteredRigid2DTransform to AffineTransform
  typedef itk::CenteredAffineTransform< double, 2 > AffineTransformType;
  StackTransforms::InitializeFromCurrentTransforms< StackType, AffineTransformType >(*movingStack);

  OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );

  fixedStack->updateVolumes();
  movingStack->updateVolumes();
  string outputDir = Dirs::ResultsDir() + "HiResPairs/";
  create_directory( outputDir );
  writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + "moving_before.mha");

  // Get number of slices for registration and transform basenames
  unsigned int number_of_slices = fixedStack->GetSize();

  // Build movingStack's basenames
  vector< string > transformBasenames;
  for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)
  {
    // construct basenames e.g. "0001_0002"
    transformBasenames.push_back(basenames[slice_number] + "_" + basenames[slice_number + 1]);
  }
  movingStack->SetBasenames(transformBasenames);

  // Configure intermediate transform writer
  SimpleTransformWriter::Pointer simpleTransformWriter = SimpleTransformWriter::New();
  string intermediateTransformsDir = outputDir + "IntermediateTransforms/" + transform + "/";
  remove_all( intermediateTransformsDir );
  simpleTransformWriter->setOutputRootDir(intermediateTransformsDir);
  simpleTransformWriter->setStack(movingStack.get());
  registration->GetOptimizer()->AddObserver( itk::IterationEvent(), simpleTransformWriter );

  // Configure metric value writer
  MetricValueWriter::Pointer metricValueWriter = MetricValueWriter::New();
  string metricValueDir = outputDir + "MetricValues/" + transforms + "/";
  remove_all(metricValueDir);
  metricValueWriter->setOutputRootDir(metricValueDir);
  metricValueWriter->setStack(movingStack.get());
  registration->GetOptimizer()->AddObserver( itk::IterationEvent(), metricValueWriter );

  // Perform registration
  for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)
  {
    cout << "Registering slices " << basenames[slice_number] <<
      " and " << basenames[slice_number + 1] << "..." << endl;

    simpleTransformWriter->setSliceNumber(slice_number);
    metricValueWriter->setSliceNumber(slice_number);

    registration->SetFixedImage( fixedStack->GetOriginalImage(slice_number) );
    registration->SetMovingImage( movingStack->GetOriginalImage(slice_number) );
    registration->GetMetric()->SetFixedImageMask( fixedStack->GetOriginal2DMask(slice_number) );
    registration->GetMetric()->SetMovingImageMask( movingStack->GetOriginal2DMask(slice_number) );
    registration->SetTransform( movingStack->GetTransform(slice_number) );
    registration->SetInitialTransformParameters( movingStack->GetTransform(slice_number)->GetParameters() );

    try { registration->Update(); }
    catch( itk::ExceptionObject & err )
    {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
    }
  }

  // Save transforms and inverse transforms
  string transformsDir = outputDir + "FinalTransforms/";
  create_directory(transformsDir);
  Save(*movingStack, transformsDir);

  // Write images
  fixedStack->updateVolumes();
  movingStack->updateVolumes();
  writeImage< StackType::VolumeType >( originalStack->GetVolume(), outputDir + "original.mha");
  writeImage< StackType::VolumeType >( fixedStack->GetVolume(), outputDir + "fixed.mha");
  writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + "moving_after.mha");
  writeImage< StackType::MaskVolumeType >( fixedStack->Get3DMask()->GetImage(), outputDir + "fixed_mask.mha");
  writeImage< StackType::MaskVolumeType >( movingStack->Get3DMask()->GetImage(), outputDir + "moving_mask.mha");

  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("dataSet", po::value<string>(), "which rat to use")
      ("outputDir", po::value<string>(), "directory to place results")
      ("transform", po::value<string>(), "Type of ITK transform to start from")
      ("roi", po::value<string>(), "region of interest e.g. papillary_insertion")
      ("fixedBasename", po::value<string>(), "basename of fixed slice e.g. 0196")
      ("movingBasename", po::value<string>(), "basename of moving slice e.g. 0197")
  ;

  po::positional_options_description p;
  p.add("dataSet", 1)
   .add("outputDir", 1)
   .add("transform", 1)
   .add("roi", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if(vm.count("help") ||
    !vm.count("dataSet") ||
    !vm.count("outputDir") ||
    !vm.count("transform") ||
    (vm.count("fixedBasename") != vm.count("movingBasename")) )
  {
    cerr << "Usage: "
      << argv[0]
      << " [--dataSet=]RatX [--outputDir=]my_dir"
      << " [--transform=]CenteredAffineTransform"
      << " [Options]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}
<commit_msg>Ignore identical adjacent slices<commit_after>// Register adjacent HiRes images to each other,
// initialised by loaded transforms from previous registration

#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"

// my files
#include "Stack.hpp"
#include "RegistrationBuilder.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"
#include "StackTransforms.hpp"
#include "Dirs.hpp"
#include "OptimizerConfig.hpp"
#include "ScaleImages.hpp"
#include "SimpleTransformWriter.hpp"
#include "MetricValueWriter.hpp"

using namespace boost::filesystem;
namespace po = boost::program_options;
using namespace boost;

// function declarations
po::variables_map parse_arguments(int argc, char *argv[]);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

  // Process command line arguments
  Dirs::SetDataSet(argv[1]);
  Dirs::SetOutputDirName(argv[2]);
  string transform = vm["transform"].as<string>();
  string roi = vm.count("roi") ? vm["roi"].as<string>() : "ROI";

  // for globally available registrationParameters(),
  // used in e.g. OptimizerConfig
  Dirs::SetParamsFile( Dirs::ConfigDir() + "HiRes_pair_parameters.yml" );

  // construct basenames and paths
  vector< string > basenames = getBasenames(Dirs::ImageList());
  vector< string > paths = constructPaths(Dirs::SliceDir(), basenames, ".bmp");

  // initialise stack with correct spacings, sizes, basenames etc
  typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;
  StackType::SliceVectorType originalImages = readImages< StackType::SliceType >(paths);
  scaleImages< StackType::SliceType >(originalImages, getSpacings<2>("HiRes"));
  shared_ptr< StackType > originalStack = make_shared< StackType >(originalImages, getSpacings<3>("LoRes"), getSize(roi));
  originalStack->SetBasenames(basenames);

  Load(*originalStack, Dirs::HiResTransformsDir() + transform + "/");

  // move stack origins to ROI
  itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation("whole_heart");
  StackTransforms::Translate(*originalStack, translation);

  // generate images
  originalStack->updateVolumes();

  // construct 2 stacks from resampled images: 1:n-1 and 2:n
  StackType::SliceVectorType resampledImages = originalStack->GetResampledSlices();
  StackType::SliceVectorType fixedImages(++resampledImages.begin(), resampledImages.end());
  StackType::SliceVectorType movingImages(resampledImages.begin(), --resampledImages.end());
  StackType::MaskVectorType2D resampledMasks = originalStack->GetResampled2DMasks();
  StackType::MaskVectorType2D fixedMasks(++resampledMasks.begin(), resampledMasks.end());
  StackType::MaskVectorType2D movingMasks(resampledMasks.begin(), --resampledMasks.end());
  shared_ptr< StackType > fixedStack  = make_shared< StackType >(fixedImages,  fixedMasks,  getSpacings<3>("LoRes"), getSize(roi));
  shared_ptr< StackType > movingStack = make_shared< StackType >(movingImages, movingMasks, getSpacings<3>("LoRes"), getSize(roi));

  // Build registration
  typedef RegistrationBuilder< StackType > RegistrationBuilderType;
  RegistrationBuilderType registrationBuilder;
  RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();

  // Initialize both stacks with CenteredRigid2DTransform
  StackTransforms::InitializeToCommonCentre(*fixedStack);
  StackTransforms::InitializeToCommonCentre(*movingStack);

  // Configure moving centre and optimiser scales
  StackTransforms::SetMovingStackCenterWithFixedStack( *fixedStack, *movingStack );

  // Convert moving CenteredRigid2DTransform to AffineTransform
  typedef itk::CenteredAffineTransform< double, 2 > AffineTransformType;
  StackTransforms::InitializeFromCurrentTransforms< StackType, AffineTransformType >(*movingStack);

  OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );

  fixedStack->updateVolumes();
  movingStack->updateVolumes();
  string outputDir = Dirs::ResultsDir() + "HiResPairs/";
  create_directory( outputDir );
  writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + "moving_before.mha");

  // Get number of slices for registration and transform basenames
  unsigned int number_of_slices = fixedStack->GetSize();

  // Build movingStack's basenames
  vector< string > transformBasenames;
  for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)
  {
    // construct basenames e.g. "0001_0002"
    transformBasenames.push_back(basenames[slice_number] + "_" + basenames[slice_number + 1]);
  }
  movingStack->SetBasenames(transformBasenames);

  // Configure intermediate transform writer
  SimpleTransformWriter::Pointer simpleTransformWriter = SimpleTransformWriter::New();
  string intermediateTransformsDir = outputDir + "IntermediateTransforms/" + transform + "/";
  remove_all( intermediateTransformsDir );
  simpleTransformWriter->setOutputRootDir(intermediateTransformsDir);
  simpleTransformWriter->setStack(movingStack.get());
  registration->GetOptimizer()->AddObserver( itk::IterationEvent(), simpleTransformWriter );

  // Configure metric value writer
  MetricValueWriter::Pointer metricValueWriter = MetricValueWriter::New();
  string metricValueDir = outputDir + "MetricValues/" + transform + "/";
  remove_all(metricValueDir);
  metricValueWriter->setOutputRootDir(metricValueDir);
  metricValueWriter->setStack(movingStack.get());
  registration->GetOptimizer()->AddObserver( itk::IterationEvent(), metricValueWriter );

  // Perform registration
  for(unsigned int slice_number=0; slice_number < number_of_slices; ++slice_number)
  {
    if(basenames[slice_number] != basenames[slice_number + 1])
    {
      cout << "Registering slices " << basenames[slice_number] <<
        " and " << basenames[slice_number + 1] << "..." << endl;

      simpleTransformWriter->setSliceNumber(slice_number);
      metricValueWriter->setSliceNumber(slice_number);

      registration->SetFixedImage( fixedStack->GetOriginalImage(slice_number) );
      registration->SetMovingImage( movingStack->GetOriginalImage(slice_number) );
      registration->GetMetric()->SetFixedImageMask( fixedStack->GetOriginal2DMask(slice_number) );
      registration->GetMetric()->SetMovingImageMask( movingStack->GetOriginal2DMask(slice_number) );
      registration->SetTransform( movingStack->GetTransform(slice_number) );
      registration->SetInitialTransformParameters( movingStack->GetTransform(slice_number)->GetParameters() );

      try { registration->Update(); }
      catch( itk::ExceptionObject & err )
      {
        std::cerr << "ExceptionObject caught !" << std::endl;
        std::cerr << err << std::endl;
        return EXIT_FAILURE;
      }
    }
    else
    {
      cout << "Skipping identical slice pair "
        << basenames[slice_number] << " and "
        << basenames[slice_number + 1]
        << "..." << endl;
    }
  }

  // Save transforms and inverse transforms
  string transformsDir = outputDir + "FinalTransforms/";
  create_directory(transformsDir);
  Save(*movingStack, transformsDir);

  // Write images
  fixedStack->updateVolumes();
  movingStack->updateVolumes();
  writeImage< StackType::VolumeType >( originalStack->GetVolume(), outputDir + "original.mha");
  writeImage< StackType::VolumeType >( fixedStack->GetVolume(), outputDir + "fixed.mha");
  writeImage< StackType::VolumeType >( movingStack->GetVolume(), outputDir + "moving_after.mha");
  writeImage< StackType::MaskVolumeType >( fixedStack->Get3DMask()->GetImage(), outputDir + "fixed_mask.mha");
  writeImage< StackType::MaskVolumeType >( movingStack->Get3DMask()->GetImage(), outputDir + "moving_mask.mha");

  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("dataSet", po::value<string>(), "which rat to use")
      ("outputDir", po::value<string>(), "directory to place results")
      ("transform", po::value<string>(), "Type of ITK transform to start from")
      ("roi", po::value<string>(), "region of interest e.g. papillary_insertion")
      ("fixedBasename", po::value<string>(), "basename of fixed slice e.g. 0196")
      ("movingBasename", po::value<string>(), "basename of moving slice e.g. 0197")
  ;

  po::positional_options_description p;
  p.add("dataSet", 1)
   .add("outputDir", 1)
   .add("transform", 1)
   .add("roi", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if(vm.count("help") ||
    !vm.count("dataSet") ||
    !vm.count("outputDir") ||
    !vm.count("transform") ||
    (vm.count("fixedBasename") != vm.count("movingBasename")) )
  {
    cerr << "Usage: "
      << argv[0]
      << " [--dataSet=]RatX [--outputDir=]my_dir"
      << " [--transform=]CenteredAffineTransform"
      << " [Options]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2014 Tavendo GmbH
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////

#include <map>
#include <memory>
#include <iostream>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/future.hpp>
#include <boost/asio.hpp>

using namespace std;
using namespace boost;

struct rpcsvc {

   rpcsvc (asio::io_service& io) : m_io(io), m_call_id(0) {
   }

   struct Call {
      std::shared_ptr<asio::deadline_timer> m_timer;
      promise<float> m_promise;
   };

   future<float> slowsquare(float x, int delay) {

      m_call_id += 1;
      m_calls[m_call_id] = Call();

      std::shared_ptr<asio::deadline_timer>
         timer(new asio::deadline_timer(m_io, posix_time::seconds(delay)));

      m_calls[m_call_id].m_timer = timer;

      int call_id = m_call_id;

      timer->async_wait(
         [=](system::error_code ec) {
            if (!ec) {

               // Question 1:
               //
               // m_call_id seems to be captured by value, though we
               // said [=] in the lambda .. why? We workaround by
               // using a local var in the enclosing method body.
               //
               cout << m_call_id << " - " << call_id << endl;

               this->m_calls[call_id].m_promise.set_value(x * x);
               this->m_calls.erase(call_id);
            } else {
               cout << "Error in timer: " << ec << endl;
            }
         }
      );

      cout << "call " << m_call_id << " issued" << endl;

      return m_calls[m_call_id].m_promise.get_future();
   }

   asio::io_service& m_io;
   int m_call_id;
   map<int, Call> m_calls;
};

int main () {

   try {
      asio::io_service io;

      rpcsvc rpc(io);

      auto f1 = rpc.slowsquare(2, 2).then([](future<float> f) {
         cout << "call 1 returned" << endl;
         cout << "result 1: " << f.get() << endl;
      });

      auto f2 = rpc.slowsquare(3, 1).then([](future<float> f) {
         cout << "call 2 returned" << endl;
         cout << "result 2: " << f.get() << endl;
      });

      auto f3 = when_all(std::move(f1), std::move(f2));
      auto f4 = f3.then([](decltype(f3)) {
         cout << "done." << endl;
      });

      io.run();

      // Question 2:
      //
      // Neither f3 nor f4 "induce" any work on ASIO reactor ..
      // so ASIO will end it's loop though the continuation
      // hasn't been executed yet. we workaround by "manually"
      // waiting .. but that seems suboptimal ..
      //
      f4.get();

   }
   catch (std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
<commit_msg>extend test case<commit_after>///////////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2014 Tavendo GmbH
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////

#include <map>
#include <memory>
#include <iostream>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/future.hpp>
#include <boost/asio.hpp>

using namespace std;
using namespace boost;

struct rpcsvc {

   rpcsvc (asio::io_service& io) : m_io(io), m_call_id(0) {
   }

   struct Call {
      std::shared_ptr<asio::deadline_timer> m_timer;
      promise<float> m_promise;
   };

   future<float> slowsquare(float x, float delay) {

      m_call_id += 1;
      m_calls[m_call_id] = Call();

      std::shared_ptr<asio::deadline_timer>
         timer(new asio::deadline_timer(m_io, posix_time::seconds(delay)));

      m_calls[m_call_id].m_timer = timer;

      int call_id = m_call_id;

      timer->async_wait(
         [=](system::error_code ec) {
            if (!ec) {

               // Question 1:
               //
               // m_call_id seems to be captured by value, though we
               // said [=] in the lambda .. why? We workaround by
               // using a local var in the enclosing method body.
               //
               cout << m_call_id << " - " << call_id << endl;

               this->m_calls[call_id].m_promise.set_value(x * x);
               this->m_calls.erase(call_id);
            } else {
               cout << "Error in timer: " << ec << endl;
            }
         }
      );

      cout << "call " << m_call_id << " issued" << endl;

      return m_calls[m_call_id].m_promise.get_future();
   }

   asio::io_service& m_io;
   int m_call_id;
   map<int, Call> m_calls;
};

int main () {

   try {
      asio::io_service io;

      rpcsvc rpc(io);

      auto f1 = rpc.slowsquare(2, 2).then([](future<float> f) {
         cout << "call 1 returned" << endl;
         cout << "result 1: " << f.get() << endl;
      });

      auto f2 = rpc.slowsquare(3, 1.1).then([](future<float> f) {
         cout << "call 2 returned" << endl;
         cout << "result 2: " << f.get() << endl;
      });

      auto f3 = rpc.slowsquare(4, 1).then([](future<float> f) {
         cout << "call 3 returned" << endl;
         cout << "result 3: " << f.get() << endl;
      });

      auto f12 = when_all(std::move(f1), std::move(f2));
      auto f12d = f12.then([](decltype(f12)) {
         cout << "call 1/2 done" << endl;
      });

/*
      auto f23 = when_all(std::move(f2), std::move(f3));
      auto f23d = f23.then([](decltype(f23)) {
         cout << "call 2/3 done" << endl;
      });

      auto f123 = when_all(std::move(f12d), std::move(f23d));
      auto f123d = f123.then([](decltype(f123)) {
         cout << "all calls done" << endl;
      });
*/
      io.run();

      // Question 2:
      //
      // Neither f12 nor f12d (and etc) "induce" any work on
      // ASIO reactor .. so ASIO will end it's loop though the
      // continuation hasn't been executed yet. we workaround
      // by "manually" waiting .. but that seems suboptimal ..
      //
      f12d.get();

      // Question 3:
      //
      // When above f23,f23d,f123,f123d and the line below
      // is commented in, the program will deadlock somehow.
      // Why? And is there a safe ("fool proof") way to avoid
      // this kind of issues?
      //f123d.get();
   }
   catch (std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tls-cert-verifier-op.h"

#include <TelepathyQt/PendingVariantMap>

#include <KDebug>

TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,
        const Tp::ConnectionPtr &connection,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_connection(connection),
      m_channel(channel)
{
    QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ServerCertificate")));
    m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".Hostname")));
    m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ReferenceIdentities")));

    m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(
            channel->dbusConnection(), channel->busName(), certificatePath.path());
    connect(m_authTLSCertificateIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

TlsCertVerifierOp::~TlsCertVerifierOp()
{
}

void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" <<
            m_authTLSCertificateIface->path();
        m_channel->requestClose();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    // everything ok, we can return from handleChannels now
    Q_EMIT ready(this);

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    m_certType = qdbus_cast<QString>(props.value(QLatin1String("CertificateType")));
    m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String("CertificateChainData")));

    // FIXME: verify cert
    setFinished();
}

#include "tls-cert-verifier-op.moc"
<commit_msg>Very minimal prompt accept/reject certificate<commit_after>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tls-cert-verifier-op.h"

#include <TelepathyQt/PendingVariantMap>

#include <KMessageBox>
#include <KLocalizedString>
#include <KDebug>

#include <QSslCertificate>

TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,
        const Tp::ConnectionPtr &connection,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_connection(connection),
      m_channel(channel)
{
    QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ServerCertificate")));
    m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".Hostname")));
    m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(
                TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ReferenceIdentities")));

    m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(
            channel->dbusConnection(), channel->busName(), certificatePath.path());
    connect(m_authTLSCertificateIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

TlsCertVerifierOp::~TlsCertVerifierOp()
{
}

void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" <<
            m_authTLSCertificateIface->path();
        m_channel->requestClose();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    // everything ok, we can return from handleChannels now
    Q_EMIT ready(this);

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    m_certType = qdbus_cast<QString>(props.value(QLatin1String("CertificateType")));
    m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String("CertificateChainData")));

    if(m_certType.compare(QLatin1String("x509"), Qt::CaseInsensitive)) {
        kWarning() << "This is not an x509 certificate";
    }

    Q_FOREACH (const QByteArray &data, m_certData) {
        // FIXME How to chech if it is QSsl::Pem or QSsl::Der? QSsl::Der works for kdetalk
        QList<QSslCertificate> certs = QSslCertificate::fromData(data, QSsl::Der);
        Q_FOREACH (const QSslCertificate &cert, certs) {
            kDebug() << cert;
        }
    }

    //TODO Show a nice dialog
    if (KMessageBox::questionYesNo(0,
                                   i18n("Accept this certificate?
%1").arg(QString::fromLatin1(m_certData.first().toHex())),
                                   i18n("Untrusted certificate")) == KMessageBox::Yes) {
        // TODO Remember value
        m_authTLSCertificateIface->Accept().waitForFinished();
        setFinished();
    } else {
        Tp::TLSCertificateRejectionList rejections;
        // TODO Add reason
        m_authTLSCertificateIface->Reject(rejections);
        m_channel->requestClose();
        setFinishedWithError(QLatin1String("Cert.Untrusted"),
                             QLatin1String("Certificate rejected by the user"));
    }
}

#include "tls-cert-verifier-op.moc"
<|endoftext|>


<commit_before>/******************************************************************************
  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "ModuleOutline.h"

#include "DataSource.h"
#include "Utilities.h"
#include "pqProxiesWidget.h"
#include "vtkNew.h"
#include "vtkSMParaViewPipelineControllerWithRendering.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include <pqColorChooserButton.h>
#include <vtkGridAxes3DActor.h>
#include <vtkPVRenderView.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkTextProperty.h>

#include <QCheckBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>

namespace tomviz {

using pugi::xml_attribute;
using pugi::xml_node;

ModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)
{
}

ModuleOutline::~ModuleOutline()
{
  this->finalize();
}

QIcon ModuleOutline::icon() const
{
  return QIcon(":/icons/pqProbeLocation.png");
}

bool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
  if (!this->Superclass::initialize(data, vtkView)) {
    return false;
  }

  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;

  vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();

  // Create the outline filter.
  vtkSmartPointer<vtkSMProxy> proxy;
  proxy.TakeReference(pxm->NewProxy("filters", "OutlineFilter"));

  this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);
  Q_ASSERT(this->OutlineFilter);
  controller->PreInitializeProxy(this->OutlineFilter);
  vtkSMPropertyHelper(this->OutlineFilter, "Input").Set(data->producer());
  controller->PostInitializeProxy(this->OutlineFilter);
  controller->RegisterPipelineProxy(this->OutlineFilter);

  // Create the representation for it.
  this->OutlineRepresentation =
    controller->Show(this->OutlineFilter, 0, vtkView);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position")
    .Set(data->displayPosition(), 3);
  Q_ASSERT(this->OutlineRepresentation);
  // vtkSMPropertyHelper(this->OutlineRepresentation,
  //                    "Representation").Set("Outline");
  this->OutlineRepresentation->UpdateVTKObjects();

  // Give the proxy a friendly name for the GUI/Python world.
  if (auto p = convert<pqProxy*>(proxy)) {
    p->rename(label());
  }

  // Init the grid axes
  initializeGridAxes(data, vtkView);
  updateGridAxesColor(offWhite);

  return true;
}

bool ModuleOutline::finalize()
{
  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
  controller->UnRegisterProxy(this->OutlineRepresentation);
  controller->UnRegisterProxy(this->OutlineFilter);

  if (m_view) {
    m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());
  }

  this->OutlineFilter = nullptr;
  this->OutlineRepresentation = nullptr;
  return true;
}

bool ModuleOutline::serialize(pugi::xml_node& ns) const
{
  xml_node rootNode = ns.append_child("properties");

  xml_node visibilityNode = rootNode.append_child("visibility");
  visibilityNode.append_attribute("enabled") = visibility();

  xml_node gridAxesNode = rootNode.append_child("grid_axes");
  gridAxesNode.append_attribute("enabled") = m_gridAxes->GetVisibility() > 0;
  gridAxesNode.append_attribute("grid") = m_gridAxes->GetGenerateGrid();

  xml_node color = gridAxesNode.append_child("color");
  double rgb[3];
  m_gridAxes->GetProperty()->GetDiffuseColor(rgb);
  color.append_attribute("r") = rgb[0];
  color.append_attribute("g") = rgb[1];
  color.append_attribute("b") = rgb[2];

  return true;
}

bool ModuleOutline::deserialize(const pugi::xml_node& ns)
{
  xml_node rootNode = ns.child("properties");
  if (!rootNode) {
    return false;
  }

  xml_node node = rootNode.child("visibility");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      setVisibility(att.as_bool());
    }
  }

  node = rootNode.child("grid_axes");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);
    }
    att = node.attribute("grid");
    if (att) {
      m_gridAxes->SetGenerateGrid(att.as_bool());
    }
    xml_node color = node.child("color");
    if (color) {
      double rgb[3];
      att = color.attribute("r");
      if (att) {
        rgb[0] = att.as_double();
      }
      att = color.attribute("g");
      if (att) {
        rgb[1] = att.as_double();
      }
      att = color.attribute("b");
      if (att) {
        rgb[2] = att.as_double();
      }
      updateGridAxesColor(rgb);
    }
  }

  return Module::deserialize(ns);
}

bool ModuleOutline::setVisibility(bool val)
{
  Q_ASSERT(this->OutlineRepresentation);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
    .Set(val ? 1 : 0);
  this->OutlineRepresentation->UpdateVTKObjects();
  m_gridAxes->SetVisibility(val ? 1 : 0);
  return true;
}

bool ModuleOutline::visibility() const
{
  if (this->OutlineRepresentation) {
    return vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
             .GetAsInt() != 0;
  } else {
    return false;
  }
}

void ModuleOutline::addToPanel(QWidget* panel)
{
  Q_ASSERT(panel && this->OutlineRepresentation);

  if (panel->layout()) {
    delete panel->layout();
  }

  QHBoxLayout* layout = new QHBoxLayout;
  QLabel* label = new QLabel("Color");
  layout->addWidget(label);
  layout->addStretch();
  pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);
  colorSelector->setShowAlphaChannel(false);
  layout->addWidget(colorSelector);

  // Show Grid?
  QHBoxLayout* showGridLayout = new QHBoxLayout;
  QCheckBox* showGrid = new QCheckBox(QString("Show Grid"));
  showGrid->setChecked(m_gridAxes->GetGenerateGrid());

  connect(showGrid, &QCheckBox::stateChanged, this, [this](int state) {
    this->m_gridAxes->SetGenerateGrid(state == Qt::Checked);
    emit this->renderNeeded();
  });

  showGridLayout->addWidget(showGrid);

  // Show Axes?
  QHBoxLayout* showAxesLayout = new QHBoxLayout;
  QCheckBox* showAxes = new QCheckBox(QString("Show Axes"));
  showAxes->setChecked(m_gridAxes->GetVisibility());
  // Disable "Show Grid" if axes not enabled
  if (!showAxes->isChecked()) {
    showGrid->setEnabled(false);
  }
  connect(showAxes, &QCheckBox::stateChanged, this,
          [this, showGrid](int state) {
            this->m_gridAxes->SetVisibility(state == Qt::Checked);
            // Uncheck "Show Grid" and disable it
            if (state == Qt::Unchecked) {
              showGrid->setChecked(false);
              showGrid->setEnabled(false);
            } else {
              showGrid->setEnabled(true);
            }

            emit this->renderNeeded();
          });
  showAxesLayout->addWidget(showAxes);

  QVBoxLayout* panelLayout = new QVBoxLayout;
  panelLayout->addItem(layout);
  panelLayout->addItem(showAxesLayout);
  panelLayout->addItem(showGridLayout);
  panelLayout->addStretch();
  panel->setLayout(panelLayout);

  m_links.addPropertyLink(
    colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)),
    this->OutlineRepresentation,
    this->OutlineRepresentation->GetProperty("DiffuseColor"));

  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged,
                [this](const QColor& color) {
                  double rgb[3];
                  rgb[0] = color.redF();
                  rgb[1] = color.greenF();
                  rgb[2] = color.blueF();
                  updateGridAxesColor(rgb);

                });
  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,
                &ModuleOutline::dataUpdated);
}

void ModuleOutline::dataUpdated()
{
  m_links.accept();
  emit this->renderNeeded();
}

void ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)
{
  double pos[3] = { newX, newY, newZ };
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position").Set(pos, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
  this->m_gridAxes->SetPosition(newX, newY, newZ);
}

//-----------------------------------------------------------------------------
bool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)
{
  return (proxy == this->OutlineFilter.Get()) ||
         (proxy == this->OutlineRepresentation.Get());
}

std::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)
{
  if (proxy == this->OutlineFilter.Get()) {
    return "Outline";
  } else if (proxy == this->OutlineRepresentation.Get()) {
    return "Representation";
  } else {
    qWarning("Unknown proxy passed to module outline in save animation");
    return "";
  }
}

vtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)
{
  if (str == "Outline") {
    return this->OutlineFilter.Get();
  } else if (str == "Representation") {
    return this->OutlineRepresentation.Get();
  } else {
    return nullptr;
  }
}

void ModuleOutline::updateGridAxesBounds(DataSource* dataSource)
{
  Q_ASSERT(dataSource);
  double bounds[6];
  dataSource->getBounds(bounds);
  m_gridAxes->SetGridBounds(bounds);
}
void ModuleOutline::initializeGridAxes(DataSource* data,
                                       vtkSMViewProxy* vtkView)
{

  updateGridAxesBounds(data);
  m_gridAxes->SetVisibility(0);
  m_gridAxes->SetGenerateGrid(false);

  // Work around a bug in vtkGridAxes3DActor. GetProperty() returns the
  // vtkProperty associated with a single face, so to get a property associated
  // with all the faces, we need to create a new one and set it.
  vtkNew<vtkProperty> prop;
  prop->DeepCopy(m_gridAxes->GetProperty());
  this->m_gridAxes->SetProperty(prop.Get());

  // Set the titles
  updateGridAxesUnit(data);

  m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());
  m_view->GetRenderer()->AddActor(m_gridAxes.Get());

  connect(data, &DataSource::dataPropertiesChanged, this, [this]() {
    auto dataSource = qobject_cast<DataSource*>(sender());
    this->updateGridAxesBounds(dataSource);
    this->updateGridAxesUnit(dataSource);
    dataSource->producer()->MarkModified(nullptr);
    dataSource->producer()->UpdatePipeline();
    emit this->renderNeeded();

  });
}

void ModuleOutline::updateGridAxesColor(double* color)
{
  for (int i = 0; i < 6; i++) {
    vtkNew<vtkTextProperty> prop;
    prop->SetColor(color);
    m_gridAxes->SetTitleTextProperty(i, prop.Get());
    m_gridAxes->SetLabelTextProperty(i, prop.Get());
  }
  m_gridAxes->GetProperty()->SetDiffuseColor(color);
  vtkSMPropertyHelper(this->OutlineRepresentation, "DiffuseColor")
    .Set(color, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
}

void ModuleOutline::updateGridAxesUnit(DataSource* dataSource)
{
  QString xTitle = QString("X (%1)").arg(dataSource->getUnits(0));
  QString yTitle = QString("Y (%1)").arg(dataSource->getUnits(1));
  QString zTitle = QString("Z (%1)").arg(dataSource->getUnits(2));
  m_gridAxes->SetXTitle(xTitle.toUtf8().data());
  m_gridAxes->SetYTitle(yTitle.toUtf8().data());
  m_gridAxes->SetZTitle(zTitle.toUtf8().data());
}

} // end of namespace tomviz
<commit_msg>Enable front face culling<commit_after>/******************************************************************************
  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "ModuleOutline.h"

#include "DataSource.h"
#include "Utilities.h"
#include "pqProxiesWidget.h"
#include "vtkNew.h"
#include "vtkSMParaViewPipelineControllerWithRendering.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include <pqColorChooserButton.h>
#include <vtkGridAxes3DActor.h>
#include <vtkPVRenderView.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkTextProperty.h>

#include <QCheckBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>

namespace tomviz {

using pugi::xml_attribute;
using pugi::xml_node;

ModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)
{
}

ModuleOutline::~ModuleOutline()
{
  this->finalize();
}

QIcon ModuleOutline::icon() const
{
  return QIcon(":/icons/pqProbeLocation.png");
}

bool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
  if (!this->Superclass::initialize(data, vtkView)) {
    return false;
  }

  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;

  vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();

  // Create the outline filter.
  vtkSmartPointer<vtkSMProxy> proxy;
  proxy.TakeReference(pxm->NewProxy("filters", "OutlineFilter"));

  this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);
  Q_ASSERT(this->OutlineFilter);
  controller->PreInitializeProxy(this->OutlineFilter);
  vtkSMPropertyHelper(this->OutlineFilter, "Input").Set(data->producer());
  controller->PostInitializeProxy(this->OutlineFilter);
  controller->RegisterPipelineProxy(this->OutlineFilter);

  // Create the representation for it.
  this->OutlineRepresentation =
    controller->Show(this->OutlineFilter, 0, vtkView);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position")
    .Set(data->displayPosition(), 3);
  Q_ASSERT(this->OutlineRepresentation);
  // vtkSMPropertyHelper(this->OutlineRepresentation,
  //                    "Representation").Set("Outline");
  this->OutlineRepresentation->UpdateVTKObjects();

  // Give the proxy a friendly name for the GUI/Python world.
  if (auto p = convert<pqProxy*>(proxy)) {
    p->rename(label());
  }

  // Init the grid axes
  initializeGridAxes(data, vtkView);
  updateGridAxesColor(offWhite);

  return true;
}

bool ModuleOutline::finalize()
{
  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
  controller->UnRegisterProxy(this->OutlineRepresentation);
  controller->UnRegisterProxy(this->OutlineFilter);

  if (m_view) {
    m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());
  }

  this->OutlineFilter = nullptr;
  this->OutlineRepresentation = nullptr;
  return true;
}

bool ModuleOutline::serialize(pugi::xml_node& ns) const
{
  xml_node rootNode = ns.append_child("properties");

  xml_node visibilityNode = rootNode.append_child("visibility");
  visibilityNode.append_attribute("enabled") = visibility();

  xml_node gridAxesNode = rootNode.append_child("grid_axes");
  gridAxesNode.append_attribute("enabled") = m_gridAxes->GetVisibility() > 0;
  gridAxesNode.append_attribute("grid") = m_gridAxes->GetGenerateGrid();

  xml_node color = gridAxesNode.append_child("color");
  double rgb[3];
  m_gridAxes->GetProperty()->GetDiffuseColor(rgb);
  color.append_attribute("r") = rgb[0];
  color.append_attribute("g") = rgb[1];
  color.append_attribute("b") = rgb[2];

  return true;
}

bool ModuleOutline::deserialize(const pugi::xml_node& ns)
{
  xml_node rootNode = ns.child("properties");
  if (!rootNode) {
    return false;
  }

  xml_node node = rootNode.child("visibility");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      setVisibility(att.as_bool());
    }
  }

  node = rootNode.child("grid_axes");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);
    }
    att = node.attribute("grid");
    if (att) {
      m_gridAxes->SetGenerateGrid(att.as_bool());
    }
    xml_node color = node.child("color");
    if (color) {
      double rgb[3];
      att = color.attribute("r");
      if (att) {
        rgb[0] = att.as_double();
      }
      att = color.attribute("g");
      if (att) {
        rgb[1] = att.as_double();
      }
      att = color.attribute("b");
      if (att) {
        rgb[2] = att.as_double();
      }
      updateGridAxesColor(rgb);
    }
  }

  return Module::deserialize(ns);
}

bool ModuleOutline::setVisibility(bool val)
{
  Q_ASSERT(this->OutlineRepresentation);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
    .Set(val ? 1 : 0);
  this->OutlineRepresentation->UpdateVTKObjects();
  m_gridAxes->SetVisibility(val ? 1 : 0);
  return true;
}

bool ModuleOutline::visibility() const
{
  if (this->OutlineRepresentation) {
    return vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
             .GetAsInt() != 0;
  } else {
    return false;
  }
}

void ModuleOutline::addToPanel(QWidget* panel)
{
  Q_ASSERT(panel && this->OutlineRepresentation);

  if (panel->layout()) {
    delete panel->layout();
  }

  QHBoxLayout* layout = new QHBoxLayout;
  QLabel* label = new QLabel("Color");
  layout->addWidget(label);
  layout->addStretch();
  pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);
  colorSelector->setShowAlphaChannel(false);
  layout->addWidget(colorSelector);

  // Show Grid?
  QHBoxLayout* showGridLayout = new QHBoxLayout;
  QCheckBox* showGrid = new QCheckBox(QString("Show Grid"));
  showGrid->setChecked(m_gridAxes->GetGenerateGrid());

  connect(showGrid, &QCheckBox::stateChanged, this, [this](int state) {
    this->m_gridAxes->SetGenerateGrid(state == Qt::Checked);
    emit this->renderNeeded();
  });

  showGridLayout->addWidget(showGrid);

  // Show Axes?
  QHBoxLayout* showAxesLayout = new QHBoxLayout;
  QCheckBox* showAxes = new QCheckBox(QString("Show Axes"));
  showAxes->setChecked(m_gridAxes->GetVisibility());
  // Disable "Show Grid" if axes not enabled
  if (!showAxes->isChecked()) {
    showGrid->setEnabled(false);
  }
  connect(showAxes, &QCheckBox::stateChanged, this,
          [this, showGrid](int state) {
            this->m_gridAxes->SetVisibility(state == Qt::Checked);
            // Uncheck "Show Grid" and disable it
            if (state == Qt::Unchecked) {
              showGrid->setChecked(false);
              showGrid->setEnabled(false);
            } else {
              showGrid->setEnabled(true);
            }

            emit this->renderNeeded();
          });
  showAxesLayout->addWidget(showAxes);

  QVBoxLayout* panelLayout = new QVBoxLayout;
  panelLayout->addItem(layout);
  panelLayout->addItem(showAxesLayout);
  panelLayout->addItem(showGridLayout);
  panelLayout->addStretch();
  panel->setLayout(panelLayout);

  m_links.addPropertyLink(
    colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)),
    this->OutlineRepresentation,
    this->OutlineRepresentation->GetProperty("DiffuseColor"));

  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged,
                [this](const QColor& color) {
                  double rgb[3];
                  rgb[0] = color.redF();
                  rgb[1] = color.greenF();
                  rgb[2] = color.blueF();
                  updateGridAxesColor(rgb);

                });
  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,
                &ModuleOutline::dataUpdated);
}

void ModuleOutline::dataUpdated()
{
  m_links.accept();
  emit this->renderNeeded();
}

void ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)
{
  double pos[3] = { newX, newY, newZ };
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position").Set(pos, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
  this->m_gridAxes->SetPosition(newX, newY, newZ);
}

//-----------------------------------------------------------------------------
bool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)
{
  return (proxy == this->OutlineFilter.Get()) ||
         (proxy == this->OutlineRepresentation.Get());
}

std::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)
{
  if (proxy == this->OutlineFilter.Get()) {
    return "Outline";
  } else if (proxy == this->OutlineRepresentation.Get()) {
    return "Representation";
  } else {
    qWarning("Unknown proxy passed to module outline in save animation");
    return "";
  }
}

vtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)
{
  if (str == "Outline") {
    return this->OutlineFilter.Get();
  } else if (str == "Representation") {
    return this->OutlineRepresentation.Get();
  } else {
    return nullptr;
  }
}

void ModuleOutline::updateGridAxesBounds(DataSource* dataSource)
{
  Q_ASSERT(dataSource);
  double bounds[6];
  dataSource->getBounds(bounds);
  m_gridAxes->SetGridBounds(bounds);
}
void ModuleOutline::initializeGridAxes(DataSource* data,
                                       vtkSMViewProxy* vtkView)
{

  updateGridAxesBounds(data);
  m_gridAxes->SetVisibility(0);
  m_gridAxes->SetGenerateGrid(false);

  // Work around a bug in vtkGridAxes3DActor. GetProperty() returns the
  // vtkProperty associated with a single face, so to get a property associated
  // with all the faces, we need to create a new one and set it.
  vtkNew<vtkProperty> prop;
  prop->DeepCopy(m_gridAxes->GetProperty());
  this->m_gridAxes->SetProperty(prop.Get());

  // Enable front face culling
  prop->SetFrontfaceCulling(1);

  // Set the titles
  updateGridAxesUnit(data);

  m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());
  m_view->GetRenderer()->AddActor(m_gridAxes.Get());

  connect(data, &DataSource::dataPropertiesChanged, this, [this]() {
    auto dataSource = qobject_cast<DataSource*>(sender());
    this->updateGridAxesBounds(dataSource);
    this->updateGridAxesUnit(dataSource);
    dataSource->producer()->MarkModified(nullptr);
    dataSource->producer()->UpdatePipeline();
    emit this->renderNeeded();

  });
}

void ModuleOutline::updateGridAxesColor(double* color)
{
  for (int i = 0; i < 6; i++) {
    vtkNew<vtkTextProperty> prop;
    prop->SetColor(color);
    m_gridAxes->SetTitleTextProperty(i, prop.Get());
    m_gridAxes->SetLabelTextProperty(i, prop.Get());
  }
  m_gridAxes->GetProperty()->SetDiffuseColor(color);
  vtkSMPropertyHelper(this->OutlineRepresentation, "DiffuseColor")
    .Set(color, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
}

void ModuleOutline::updateGridAxesUnit(DataSource* dataSource)
{
  QString xTitle = QString("X (%1)").arg(dataSource->getUnits(0));
  QString yTitle = QString("Y (%1)").arg(dataSource->getUnits(1));
  QString zTitle = QString("Z (%1)").arg(dataSource->getUnits(2));
  m_gridAxes->SetXTitle(xTitle.toUtf8().data());
  m_gridAxes->SetYTitle(yTitle.toUtf8().data());
  m_gridAxes->SetZTitle(zTitle.toUtf8().data());
}

} // end of namespace tomviz
<|endoftext|>


<commit_before>/*
  Copyright (C) 2014 Marcus Soll
  All rights reserved.

  You may use this file under the terms of BSD license as follows:

  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 Jolla Ltd 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "cornercore.h"
#include "assemblyaihelper.h"

using AssemblyAI::opponent;

CornerCore::CornerCore()
{
}

bool CornerCore::retirement(Gameboard board, int player)
{
    // The core should retrire when neither the player nor the opponent can get a corner
    return !(board.play(0,0,opponent(player),true) || board.play(7,0,opponent(player),true) || board.play(0,7,opponent(player),true) || board.play(7,7,opponent(player),true))
            && !(board.play(0,0,player,true) || board.play(7,0,player,true) || board.play(0,7,player,true) || board.play(7,7,player,true));
}

bool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)
{
    // Mistrust if you can get a corner but the proposal doesn't consider it

    if(!(vote[0][0] <= 0) && board.play(0,0,player,true))
    {
        return true;
    }
    else if(!(vote[0][7] <= 0) && board.play(0,7,player,true))
    {
        return true;
    }
    else if(!(vote[7][0] <= 0) && board.play(7,0,player,true))
    {
        return true;
    }
    else if(!(vote[7][7] <= 0) && board.play(7,7,player,true))
    {
        return true;
    }

    // Mistrust if a play is proposed where the opponent could get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && !((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,player,false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    return true;
                }
            }
        }
    }
    return false;
}

void CornerCore::propose(float ** const vote, Gameboard board, int player)
{
    // Try to get corners
    if(board.play(0,0,player,true))
    {
        vote[0][0] = 1;
    }
    if(board.play(0,7,player,true))
    {
        vote[0][7] = 1;
    }
    if(board.play(7,0,player,true))
    {
        vote[7][0] = 1;
    }
    if(board.play(7,7,player,true))
    {
        vote[7][7] = 1;
    }

    // Propose plays where the opponent can't get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))
                {
                    vote[x][y] = 0.1;
                }
            }
        }
    }
    AssemblyAI::ensureOnePossibleMove(vote,board,player);
}

void CornerCore::correct(float ** const vote, Gameboard board, int player)
{
    // Give Corners a high priority
    vote[0][0] *= Core::_factorLarge;
    vote[0][7] *= Core::_factorLarge;
    vote[7][0] *= Core::_factorLarge;
    vote[7][7] *= Core::_factorLarge;

    // Give plays where an opponent can get a corner a low priority
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    vote[x][y] /= Core::_factorLarge;
                }
            }
        }
    }
}

QString CornerCore::name() const
{
    return "Corner Core";
}
<commit_msg>Hopefully fixed "Corner Core"<commit_after>/*
  Copyright (C) 2014 Marcus Soll
  All rights reserved.

  You may use this file under the terms of BSD license as follows:

  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 Jolla Ltd 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "cornercore.h"
#include "assemblyaihelper.h"

using AssemblyAI::opponent;

CornerCore::CornerCore()
{
}

bool CornerCore::retirement(Gameboard board, int player)
{
        // Do not retrire if you can get a corner

        if(board.play(0,0,player,true))
        {
            return false;
        }
        else if(board.play(0,7,player,true))
        {
            return false;
        }
        else if(board.play(7,0,player,true))
        {
            return false;
        }
        else if(board.play(7,7,player,true))
        {
            return false;
        }

        // Do not retrire if there is a play where the opponent could get a corner
        for(int x = 0; x < 8; ++x)
        {
            for(int y = 0; y < 8; ++y)
            {
                if(!((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
                {
                    Gameboard testboard = board;
                    testboard.play(x,y,player,false);
                    if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                    {
                        return false;
                    }
                }
            }
        }
        // Else retrire
        return true;
}

bool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)
{
    // Mistrust if you can get a corner but the proposal doesn't consider it

    if(!(vote[0][0] <= 0) && board.play(0,0,player,true))
    {
        return true;
    }
    else if(!(vote[0][7] <= 0) && board.play(0,7,player,true))
    {
        return true;
    }
    else if(!(vote[7][0] <= 0) && board.play(7,0,player,true))
    {
        return true;
    }
    else if(!(vote[7][7] <= 0) && board.play(7,7,player,true))
    {
        return true;
    }

    // Mistrust if a play is proposed where the opponent could get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && !((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,player,false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    return true;
                }
            }
        }
    }
    return false;
}

void CornerCore::propose(float ** const vote, Gameboard board, int player)
{
    // Try to get corners
    if(board.play(0,0,player,true))
    {
        vote[0][0] = 1;
    }
    if(board.play(0,7,player,true))
    {
        vote[0][7] = 1;
    }
    if(board.play(7,0,player,true))
    {
        vote[7][0] = 1;
    }
    if(board.play(7,7,player,true))
    {
        vote[7][7] = 1;
    }

    // Propose plays where the opponent can't get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))
                {
                    vote[x][y] = 0.1;
                }
            }
        }
    }
    AssemblyAI::ensureOnePossibleMove(vote,board,player);
}

void CornerCore::correct(float ** const vote, Gameboard board, int player)
{
    // Give Corners a high priority
    vote[0][0] *= Core::_factorLarge;
    vote[0][7] *= Core::_factorLarge;
    vote[7][0] *= Core::_factorLarge;
    vote[7][7] *= Core::_factorLarge;

    // Give plays where an opponent can get a corner a low priority
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    vote[x][y] /= Core::_factorLarge;
                }
            }
        }
    }
}

QString CornerCore::name() const
{
    return "Corner Core";
}
<|endoftext|>


<commit_before>//===- Error.cpp - system_error extensions for obj2yaml ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Error.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

namespace {
class _obj2yaml_error_category : public std::error_category {
public:
  const char *name() const LLVM_NOEXCEPT override;
  std::string message(int ev) const override;
};
} // namespace

const char *_obj2yaml_error_category::name() const { return "obj2yaml"; }

std::string _obj2yaml_error_category::message(int ev) const {
  switch (static_cast<obj2yaml_error>(ev)) {
  case obj2yaml_error::success:
    return "Success";
  case obj2yaml_error::file_not_found:
    return "No such file.";
  case obj2yaml_error::unrecognized_file_format:
    return "Unrecognized file type.";
  case obj2yaml_error::unsupported_obj_file_format:
    return "Unsupported object file format.";
  }
  llvm_unreachable("An enumerator of obj2yaml_error does not have a message "
                   "defined.");
}

namespace llvm {
  const std::error_category &obj2yaml_category() {
  static _obj2yaml_error_category o;
  return o;
}
} // namespace llvm
<commit_msg>Added missing LLVM_NOEXCEPT to the definition of _obj2yaml_error_category::name<commit_after>//===- Error.cpp - system_error extensions for obj2yaml ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Error.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

namespace {
class _obj2yaml_error_category : public std::error_category {
public:
  const char *name() const LLVM_NOEXCEPT override;
  std::string message(int ev) const override;
};
} // namespace

const char *_obj2yaml_error_category::name() const LLVM_NOEXCEPT {
  return "obj2yaml";
}

std::string _obj2yaml_error_category::message(int ev) const {
  switch (static_cast<obj2yaml_error>(ev)) {
  case obj2yaml_error::success:
    return "Success";
  case obj2yaml_error::file_not_found:
    return "No such file.";
  case obj2yaml_error::unrecognized_file_format:
    return "Unrecognized file type.";
  case obj2yaml_error::unsupported_obj_file_format:
    return "Unsupported object file format.";
  }
  llvm_unreachable("An enumerator of obj2yaml_error does not have a message "
                   "defined.");
}

namespace llvm {
  const std::error_category &obj2yaml_category() {
  static _obj2yaml_error_category o;
  return o;
}
} // namespace llvm
<|endoftext|>


<commit_before>
/*
 * Copyright (c) 2015 LinBox
 * This file is part of the library LinBox. See COPYING for license info.
 * Written by bds.
 */
/** @file tests/checker.C
@brief script to run LinBox tests

Checker is compiled and run by the check macro invoked by "make fullcheck" in the top source dir or in tests/.

Run without args,
each test is build and run, with a one line report of success or failure.
A summary at the end reports number of test failing to compile, failing at runtime, and skipped.
There should be a 1-1 correspondence between files tests/test-*.C and report lines

A LinBox unit/regresssion test has a default behaviour -- when there are no command line file names -- in which nothing is written to any output stream and the return value is 0 for a passing test, nonzero for any failure.

The current convention is that (1) linbox' checker.C, runs the tests with no command line parameters at all, and (2) if there is a command line file name, verbose diagnostic output is written to that file and more terse output may be written to standard output streams.  The second feature is intended to assist debugging with individual tests.

*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <vector>
//#include <iomanip>
using namespace std;
#include "linbox-config.h"
//#include "linbox/linbox-config.h"
//#include "fflas-ffpack/fflas-ffpack.h"

// globals
//map< string, string> skip_note;
map< string, string> warn_note;
set< string> skips;
set< string> hides;
void warn(const string& t, const string& w) { warn_note[t] = w; }
void skip(const string& t, const string& w) { warn_note[t] = w; skips.insert(t); }
void hide(const string& t, const string& w) { warn_note[t] = w; hides.insert(t); }

int main(int argc, char* argv[]) {
	int arg;
	bool force_build = false, reporting = true, honor_skips = true;
	for (arg = 1; arg < argc; ++arg)
		for (char * i = argv[arg]; *i != 0; ++i){
			if (*i == 'r') force_build = true;
			if (*i == 's') reporting = false;
			if (*i == 'a') honor_skips = false;
		}
    if (argc > 1 and not force_build and reporting and honor_skips){ // bogus arg
		cout << "usage: " << argv[0] << " [-][r][s][a]" << endl;
		cout << "  -r Force recompilation of each test."<< endl;
		cout << "  -s Summary only: 3 lines printed. (Default is one line per test.)" << endl;
		cout << "  -a Build and run all. (Ignore skip and hide commands.)" << endl;
		return 0;
	}

// fullcheck customization: warnings, skips, hides, optional package dependencies

//// notes section (customize fullcheck here) ////

if (honor_skips) {
hide("test-block-ring", "non commutative rings not supported");
//hide("test-ffpack", "testTURBO fails, move to ffpack tests?");
hide("test-ftrmm", "should move to attic");
skip("test-givaro-fields", "may fail on small fields because of supposed non-randomness or failure to find a non trivial element");
hide("test-image-field", "deprecated");
//skip("test-isposdef", "intermittent inf loop");
//skip("test-ispossemidef", "intermittent inf loop");
hide("test-la-block-lanczos", "not maintained. operator >> missing");
hide("test-mg-block-lanczos", "not maintained");
hide("test-modular", "deprecated");
hide("test-modular-byte",  "deprecated");
hide("test-modular-short",  "deprecated");
//skip("test-modular-balanced-int",  "test and modular-balanced disagree on init/convert");
//skip("test-modular-balanced-double",  "test and modular-balanced disagree on init/convert");
//skip("test-moore-penrose", "inf loop");
skip("test-optimization", "not in test form");
skip("test-quad-matrix", "depends on out-of-date blackbox/zo.h");
//skip("test-rational-reconstruction-base", "inf loop");
skip("test-rat-charpoly", "inf loop");
skip("test-rat-minpoly", "stale test. solns over QQ need fresh tests"); // "intermittent failures")
skip("test-rat-solve", "stale test. solns over QQ need fresh tests"); // "infinite loop")
skip("test-poly-det", "incomplete test (if still relevant)");
skip("test-sparse-map-map", "const issue in givranditer, curious use of nonexistant next() in Extension");
//Tests requiring further development
skip("test-tutorial", "incomplete test");
skip("test-dense-zero-one", "half baked, bds responsible");
}

//warn("test-echelon-form", "new");
warn("test-fibb",  "incomplete");
//warn("test-matrix-domain", "intermittent row permutation failure");
warn("test-param-fuzzy", "Noncompliant field");
//		template <class F2Field> BitVector (const F2Field&) {}
//warn("test-qlup", "GF2 fails to compile");
//warn("test-rank-u32", "intermittent failure"/*, "vector (bb) responsible"*/);
warn("test-rat-charpoly", "stale test. solns over QQ need fresh tests");//, "infinite loop, cp responsible?")
warn("test-rat-solve", "infinite loop");
//warn("test-smith-form-local", "bds, intermittent failures");
warn("test-solve", "most of the tests are commented out");
warn("test-toom-cook", "one method does not work");
//warn("test-transpose", "sometimes fails on Sparsematrix/getEntry");
warn("test-quad-matrix", "half baked, bds responsible");

//// optional package dependency section ////
	set< string> ntl_tests;
	ntl_tests.insert("test-ntl-hankel");
	ntl_tests.insert("test-ntl-lzz_p");
	ntl_tests.insert("test-ntl-lzz_pe");
	ntl_tests.insert("test-ntl-lzz_px");
	ntl_tests.insert("test-ntl-lzz_pex");
	warn("test-toeplitz-det", "we should have a non NTL version.");
	ntl_tests.insert("test-toeplitz-det");
	warn("test-ntl-rr", "floating point equality");
	ntl_tests.insert("test-ntl-rr");
	ntl_tests.insert("test-ntl-sylvester");
	ntl_tests.insert("test-ntl-toeplitz");
	ntl_tests.insert("test-ntl-zz_p");

	// are these really ntl dependent?
	ntl_tests.insert("test-smith-form");
	ntl_tests.insert("test-smith-form-adaptive");
	ntl_tests.insert("test-smith-form-iliopoulos");
	set< string> ocl_tests;
	ocl_tests.insert("test-opencl-domain");

//// Things are automatic from here onward. ////

	// process optional dependencies
	#ifndef LINBOX_HAVE_OCL
    for (set< string>::iterator i = ocl_tests.begin(); i != ocl_tests.end(); ++i)
		skip(*i, "OpenCL not present");
	#endif
	#ifndef __LINBOX_HAVE_NTL
    for (set< string>::iterator i = ntl_tests.begin(); i != ntl_tests.end(); ++i)
		skip(*i, "NTL not present");
	#endif
// build and run the tests section
	string t, cmd;
	system("ls test-*C >.tmp-tests");
	ifstream tests(".tmp-tests");
	int buildfail = 0, runfail = 0, skipped = 0, pass = 0; // counts
	vector<string> all_tests;
	while (tests >> t) {t.resize(t.size()-2); all_tests.push_back(t);}
//#ifdef LINBOX_HAVE_OPENMP
//#pragma omp parallel for
//PARFOR1D(i, 0, all_tests.size(), SPLITTER(),
//#endif
	for (size_t i = 0; i < all_tests.size(); ++i)
	{
		t = all_tests[i];
		if (hides.count(t) > 0) continue; // ignore entirely
		stringstream report;
		report.width(35);
		report << left << t;
		if (skips.count(t) > 0) { // print skip message
			report << "skipped, " + warn_note[t];
			skipped++;
		} else { // do build
			if (force_build) {
				cmd = "touch " + t + ".C";
				system(cmd.c_str());
			}
			// build
			cmd = "make " + t + " 2> /dev/null > /dev/null";
			report << "build ";
			int status = system(cmd.c_str());
//			#ifndef LINBOX_HAVE_OPENMP
//			if (status == 2) break;
//			#endif
			if (status != 0) { // build failure
				buildfail++;
				report << "FAIL ";
			} else {// do run
				report << "OK, run ";
				std::ostringstream prog ;
				prog << "./" << t ;
				status = system(prog.str().c_str());
//				#ifndef LINBOX_HAVE_OPENMP
//				if (status == 2) break;
//				#endif
				if (status == 0) {
					report << "OK.  " + warn_note[t];
					pass++;
				} else {
					runfail++;
					report << "FAIL" + warn_note[t];
				}
			}
		}
		if (reporting) cout << report.str() << endl;
	} // for i
	//); // parfor

	//// summary ////
	cout << "--------------------------------------------------------------------" << endl;
	int total = pass + buildfail + runfail + skipped;
	if (buildfail || runfail)
		cout << "Of " << total << " tests, "
		    << pass << " passed, "
			<< buildfail << " failed to compile, "
			<< runfail << " failed at runtime, "
			<< " and " << skipped << " were skipped." << endl;
	else
		cout << endl << "All " << total - skipped << " tests pass."
			<< "  (There were " << skipped << " skipped tests.)" << endl;
	cout << "--------------------------------------------------------------------" << endl;

	return buildfail || runfail ? -1 : 0;
} // main
<commit_msg>linbox/linbox-config.h<commit_after>
/*
 * Copyright (c) 2015 LinBox
 * This file is part of the library LinBox. See COPYING for license info.
 * Written by bds.
 */
/** @file tests/checker.C
@brief script to run LinBox tests

Checker is compiled and run by the check macro invoked by "make fullcheck" in the top source dir or in tests/.

Run without args,
each test is build and run, with a one line report of success or failure.
A summary at the end reports number of test failing to compile, failing at runtime, and skipped.
There should be a 1-1 correspondence between files tests/test-*.C and report lines

A LinBox unit/regresssion test has a default behaviour -- when there are no command line file names -- in which nothing is written to any output stream and the return value is 0 for a passing test, nonzero for any failure.

The current convention is that (1) linbox' checker.C, runs the tests with no command line parameters at all, and (2) if there is a command line file name, verbose diagnostic output is written to that file and more terse output may be written to standard output streams.  The second feature is intended to assist debugging with individual tests.

*/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <vector>
//#include <iomanip>
using namespace std;
//#include "linbox-config.h"
#include "linbox/linbox-config.h"
//#include "fflas-ffpack/fflas-ffpack.h"

// globals
//map< string, string> skip_note;
map< string, string> warn_note;
set< string> skips;
set< string> hides;
void warn(const string& t, const string& w) { warn_note[t] = w; }
void skip(const string& t, const string& w) { warn_note[t] = w; skips.insert(t); }
void hide(const string& t, const string& w) { warn_note[t] = w; hides.insert(t); }

int main(int argc, char* argv[]) {
	int arg;
	bool force_build = false, reporting = true, honor_skips = true;
	for (arg = 1; arg < argc; ++arg)
		for (char * i = argv[arg]; *i != 0; ++i){
			if (*i == 'r') force_build = true;
			if (*i == 's') reporting = false;
			if (*i == 'a') honor_skips = false;
		}
    if (argc > 1 and not force_build and reporting and honor_skips){ // bogus arg
		cout << "usage: " << argv[0] << " [-][r][s][a]" << endl;
		cout << "  -r Force recompilation of each test."<< endl;
		cout << "  -s Summary only: 3 lines printed. (Default is one line per test.)" << endl;
		cout << "  -a Build and run all. (Ignore skip and hide commands.)" << endl;
		return 0;
	}

// fullcheck customization: warnings, skips, hides, optional package dependencies

//// notes section (customize fullcheck here) ////

if (honor_skips) {
hide("test-block-ring", "non commutative rings not supported");
//hide("test-ffpack", "testTURBO fails, move to ffpack tests?");
hide("test-ftrmm", "should move to attic");
skip("test-givaro-fields", "may fail on small fields because of supposed non-randomness or failure to find a non trivial element");
hide("test-image-field", "deprecated");
//skip("test-isposdef", "intermittent inf loop");
//skip("test-ispossemidef", "intermittent inf loop");
hide("test-la-block-lanczos", "not maintained. operator >> missing");
hide("test-mg-block-lanczos", "not maintained");
hide("test-modular", "deprecated");
hide("test-modular-byte",  "deprecated");
hide("test-modular-short",  "deprecated");
//skip("test-modular-balanced-int",  "test and modular-balanced disagree on init/convert");
//skip("test-modular-balanced-double",  "test and modular-balanced disagree on init/convert");
//skip("test-moore-penrose", "inf loop");
skip("test-optimization", "not in test form");
skip("test-quad-matrix", "depends on out-of-date blackbox/zo.h");
//skip("test-rational-reconstruction-base", "inf loop");
skip("test-rat-charpoly", "inf loop");
skip("test-rat-minpoly", "stale test. solns over QQ need fresh tests"); // "intermittent failures")
skip("test-rat-solve", "stale test. solns over QQ need fresh tests"); // "infinite loop")
skip("test-poly-det", "incomplete test (if still relevant)");
skip("test-sparse-map-map", "const issue in givranditer, curious use of nonexistant next() in Extension");
//Tests requiring further development
skip("test-tutorial", "incomplete test");
skip("test-dense-zero-one", "half baked, bds responsible");
}

//warn("test-echelon-form", "new");
warn("test-fibb",  "incomplete");
//warn("test-matrix-domain", "intermittent row permutation failure");
warn("test-param-fuzzy", "Noncompliant field");
//		template <class F2Field> BitVector (const F2Field&) {}
//warn("test-qlup", "GF2 fails to compile");
//warn("test-rank-u32", "intermittent failure"/*, "vector (bb) responsible"*/);
warn("test-rat-charpoly", "stale test. solns over QQ need fresh tests");//, "infinite loop, cp responsible?")
warn("test-rat-solve", "infinite loop");
//warn("test-smith-form-local", "bds, intermittent failures");
warn("test-solve", "most of the tests are commented out");
warn("test-toom-cook", "one method does not work");
//warn("test-transpose", "sometimes fails on Sparsematrix/getEntry");
warn("test-quad-matrix", "half baked, bds responsible");

//// optional package dependency section ////
	set< string> ntl_tests;
	ntl_tests.insert("test-ntl-hankel");
	ntl_tests.insert("test-ntl-lzz_p");
	ntl_tests.insert("test-ntl-lzz_pe");
	ntl_tests.insert("test-ntl-lzz_px");
	ntl_tests.insert("test-ntl-lzz_pex");
	warn("test-toeplitz-det", "we should have a non NTL version.");
	ntl_tests.insert("test-toeplitz-det");
	warn("test-ntl-rr", "floating point equality");
	ntl_tests.insert("test-ntl-rr");
	ntl_tests.insert("test-ntl-sylvester");
	ntl_tests.insert("test-ntl-toeplitz");
	ntl_tests.insert("test-ntl-zz_p");

	// are these really ntl dependent?
	ntl_tests.insert("test-smith-form");
	ntl_tests.insert("test-smith-form-adaptive");
	ntl_tests.insert("test-smith-form-iliopoulos");
	set< string> ocl_tests;
	ocl_tests.insert("test-opencl-domain");

//// Things are automatic from here onward. ////

	// process optional dependencies
	#ifndef LINBOX_HAVE_OCL
    for (set< string>::iterator i = ocl_tests.begin(); i != ocl_tests.end(); ++i)
		skip(*i, "OpenCL not present");
	#endif
	#ifndef __LINBOX_HAVE_NTL
    for (set< string>::iterator i = ntl_tests.begin(); i != ntl_tests.end(); ++i)
		skip(*i, "NTL not present");
	#endif
// build and run the tests section
	string t, cmd;
	system("ls test-*C >.tmp-tests");
	ifstream tests(".tmp-tests");
	int buildfail = 0, runfail = 0, skipped = 0, pass = 0; // counts
	vector<string> all_tests;
	while (tests >> t) {t.resize(t.size()-2); all_tests.push_back(t);}
//#ifdef LINBOX_HAVE_OPENMP
//#pragma omp parallel for
//PARFOR1D(i, 0, all_tests.size(), SPLITTER(),
//#endif
	for (size_t i = 0; i < all_tests.size(); ++i)
	{
		t = all_tests[i];
		if (hides.count(t) > 0) continue; // ignore entirely
		stringstream report;
		report.width(35);
		report << left << t;
		if (skips.count(t) > 0) { // print skip message
			report << "skipped, " + warn_note[t];
			skipped++;
		} else { // do build
			if (force_build) {
				cmd = "touch " + t + ".C";
				system(cmd.c_str());
			}
			// build
			cmd = "make " + t + " 2> /dev/null > /dev/null";
			report << "build ";
			int status = system(cmd.c_str());
//			#ifndef LINBOX_HAVE_OPENMP
//			if (status == 2) break;
//			#endif
			if (status != 0) { // build failure
				buildfail++;
				report << "FAIL ";
			} else {// do run
				report << "OK, run ";
				std::ostringstream prog ;
				prog << "./" << t ;
				status = system(prog.str().c_str());
//				#ifndef LINBOX_HAVE_OPENMP
//				if (status == 2) break;
//				#endif
				if (status == 0) {
					report << "OK.  " + warn_note[t];
					pass++;
				} else {
					runfail++;
					report << "FAIL" + warn_note[t];
				}
			}
		}
		if (reporting) cout << report.str() << endl;
	} // for i
	//); // parfor

	//// summary ////
	cout << "--------------------------------------------------------------------" << endl;
	int total = pass + buildfail + runfail + skipped;
	if (buildfail || runfail)
		cout << "Of " << total << " tests, "
		    << pass << " passed, "
			<< buildfail << " failed to compile, "
			<< runfail << " failed at runtime, "
			<< " and " << skipped << " were skipped." << endl;
	else
		cout << endl << "All " << total - skipped << " tests pass."
			<< "  (There were " << skipped << " skipped tests.)" << endl;
	cout << "--------------------------------------------------------------------" << endl;

	return buildfail || runfail ? -1 : 0;
} // main
<|endoftext|>