<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "greptest.h"

#include <chemkit/molecule.h>
#include <chemkit/moleculefile.h>

const QString grepApplication = "../../../../bin/chemkit-grep";
const QString testDataPath = "../../../data/";

void GrepTest::ironComposition()
{
    QProcess process;

    QStringList arguments;
    arguments.append("--composition");
    arguments.append("InChI=1/Fe/");
    arguments.append(testDataPath + "MMFF94_hypervalent.mol2");

    QTemporaryFile output;
    output.open();

    process.setStandardOutputFile(output.fileName());
    process.start(grepApplication, arguments);
    process.waitForFinished();
    process.close();

    chemkit::MoleculeFile file;
    QByteArray outputFileName = output.fileName().toAscii();
    bool ok = file.read(outputFileName.constData(), "mol2");
    if(!ok){
        qDebug() << file.errorString().c_str();
    }
    QVERIFY(ok);
    QCOMPARE(file.moleculeCount(), size_t(2));
    QCOMPARE(file.molecule(0)->name(), std::string("FE2PW3"));
    QCOMPARE(file.molecule(0)->formula(), std::string("FeH6O3"));
    QCOMPARE(file.molecule(1)->name(), std::string("FE3PW3"));
    QCOMPARE(file.molecule(1)->formula(), std::string("FeH6O3"));
}

void GrepTest::benzoicAcid()
{
    QProcess process;

    QStringList arguments;
    arguments.append("--names-only");
    arguments.append("InChI=1/C7H6O2/c8-7(9)6-4-2-1-3-5-6/h1-5H,(H,8,9)/f/h8H");
    arguments.append(testDataPath + "pubchem_416_benzenes.sdf");

    process.start(grepApplication, arguments);
    process.waitForFinished();

    QString output = process.readAllStandardOutput();
    QStringList moleculeNames = output.split("\n", QString::SkipEmptyParts);
    QCOMPARE(moleculeNames.size(), 39);
    QCOMPARE(moleculeNames[0], QString("2605"));
    QCOMPARE(moleculeNames[1], QString("2541"));
    QCOMPARE(moleculeNames[2], QString("2536"));
    QCOMPARE(moleculeNames[3], QString("2480"));
    QCOMPARE(moleculeNames[4], QString("2471"));
    QCOMPARE(moleculeNames[5], QString("2424"));
    QCOMPARE(moleculeNames[6], QString("2418"));
    QCOMPARE(moleculeNames[7], QString("2376"));
    QCOMPARE(moleculeNames[8], QString("2356"));
    QCOMPARE(moleculeNames[9], QString("2347"));
    QCOMPARE(moleculeNames[10], QString("2334"));
    QCOMPARE(moleculeNames[11], QString("2329"));
    QCOMPARE(moleculeNames[12], QString("2318"));
    QCOMPARE(moleculeNames[13], QString("2316"));
    QCOMPARE(moleculeNames[14], QString("2259"));
    QCOMPARE(moleculeNames[15], QString("2258"));
    QCOMPARE(moleculeNames[16], QString("2257"));
    QCOMPARE(moleculeNames[17], QString("2126"));
    QCOMPARE(moleculeNames[18], QString("1974"));
    QCOMPARE(moleculeNames[19], QString("1964"));
    QCOMPARE(moleculeNames[20], QString("1854"));
    QCOMPARE(moleculeNames[21], QString("1829"));
    QCOMPARE(moleculeNames[22], QString("1730"));
    QCOMPARE(moleculeNames[23], QString("1718"));
    QCOMPARE(moleculeNames[24], QString("1711"));
    QCOMPARE(moleculeNames[25], QString("1683"));
    QCOMPARE(moleculeNames[26], QString("1583"));
    QCOMPARE(moleculeNames[27], QString("1559"));
    QCOMPARE(moleculeNames[28], QString("1385"));
    QCOMPARE(moleculeNames[29], QString("1311"));
    QCOMPARE(moleculeNames[30], QString("1309"));
    QCOMPARE(moleculeNames[31], QString("1287"));
    QCOMPARE(moleculeNames[32], QString("1261"));
    QCOMPARE(moleculeNames[33], QString("1248"));
    QCOMPARE(moleculeNames[34], QString("894"));
    QCOMPARE(moleculeNames[35], QString("514"));
    QCOMPARE(moleculeNames[36], QString("287"));
    QCOMPARE(moleculeNames[37], QString("341"));
    QCOMPARE(moleculeNames[38], QString("170"));
}

QTEST_APPLESS_MAIN(GrepTest)
<commit_msg>Trim output strings in GrepTest::benzoicAcid()<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "greptest.h"

#include <chemkit/molecule.h>
#include <chemkit/moleculefile.h>

const QString grepApplication = "../../../../bin/chemkit-grep";
const QString testDataPath = "../../../data/";

void GrepTest::ironComposition()
{
    QProcess process;

    QStringList arguments;
    arguments.append("--composition");
    arguments.append("InChI=1/Fe/");
    arguments.append(testDataPath + "MMFF94_hypervalent.mol2");

    QTemporaryFile output;
    output.open();

    process.setStandardOutputFile(output.fileName());
    process.start(grepApplication, arguments);
    process.waitForFinished();
    process.close();

    chemkit::MoleculeFile file;
    QByteArray outputFileName = output.fileName().toAscii();
    bool ok = file.read(outputFileName.constData(), "mol2");
    if(!ok){
        qDebug() << file.errorString().c_str();
    }
    QVERIFY(ok);
    QCOMPARE(file.moleculeCount(), size_t(2));
    QCOMPARE(file.molecule(0)->name(), std::string("FE2PW3"));
    QCOMPARE(file.molecule(0)->formula(), std::string("FeH6O3"));
    QCOMPARE(file.molecule(1)->name(), std::string("FE3PW3"));
    QCOMPARE(file.molecule(1)->formula(), std::string("FeH6O3"));
}

void GrepTest::benzoicAcid()
{
    QProcess process;

    QStringList arguments;
    arguments.append("--names-only");
    arguments.append("InChI=1/C7H6O2/c8-7(9)6-4-2-1-3-5-6/h1-5H,(H,8,9)/f/h8H");
    arguments.append(testDataPath + "pubchem_416_benzenes.sdf");

    process.start(grepApplication, arguments);
    process.waitForFinished();

    QString output = process.readAllStandardOutput();
    QStringList moleculeNames = output.split("\n", QString::SkipEmptyParts);
    QCOMPARE(moleculeNames.size(), 39);

    // trim whitespace from names
    for(int i = 0; i < moleculeNames.size(); i++){
        moleculeNames[i] = moleculeNames[i].trimmed();
    }

    QCOMPARE(moleculeNames[0], QString("2605"));
    QCOMPARE(moleculeNames[1], QString("2541"));
    QCOMPARE(moleculeNames[2], QString("2536"));
    QCOMPARE(moleculeNames[3], QString("2480"));
    QCOMPARE(moleculeNames[4], QString("2471"));
    QCOMPARE(moleculeNames[5], QString("2424"));
    QCOMPARE(moleculeNames[6], QString("2418"));
    QCOMPARE(moleculeNames[7], QString("2376"));
    QCOMPARE(moleculeNames[8], QString("2356"));
    QCOMPARE(moleculeNames[9], QString("2347"));
    QCOMPARE(moleculeNames[10], QString("2334"));
    QCOMPARE(moleculeNames[11], QString("2329"));
    QCOMPARE(moleculeNames[12], QString("2318"));
    QCOMPARE(moleculeNames[13], QString("2316"));
    QCOMPARE(moleculeNames[14], QString("2259"));
    QCOMPARE(moleculeNames[15], QString("2258"));
    QCOMPARE(moleculeNames[16], QString("2257"));
    QCOMPARE(moleculeNames[17], QString("2126"));
    QCOMPARE(moleculeNames[18], QString("1974"));
    QCOMPARE(moleculeNames[19], QString("1964"));
    QCOMPARE(moleculeNames[20], QString("1854"));
    QCOMPARE(moleculeNames[21], QString("1829"));
    QCOMPARE(moleculeNames[22], QString("1730"));
    QCOMPARE(moleculeNames[23], QString("1718"));
    QCOMPARE(moleculeNames[24], QString("1711"));
    QCOMPARE(moleculeNames[25], QString("1683"));
    QCOMPARE(moleculeNames[26], QString("1583"));
    QCOMPARE(moleculeNames[27], QString("1559"));
    QCOMPARE(moleculeNames[28], QString("1385"));
    QCOMPARE(moleculeNames[29], QString("1311"));
    QCOMPARE(moleculeNames[30], QString("1309"));
    QCOMPARE(moleculeNames[31], QString("1287"));
    QCOMPARE(moleculeNames[32], QString("1261"));
    QCOMPARE(moleculeNames[33], QString("1248"));
    QCOMPARE(moleculeNames[34], QString("894"));
    QCOMPARE(moleculeNames[35], QString("514"));
    QCOMPARE(moleculeNames[36], QString("287"));
    QCOMPARE(moleculeNames[37], QString("341"));
    QCOMPARE(moleculeNames[38], QString("170"));
}

QTEST_APPLESS_MAIN(GrepTest)
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/examples/wordcount_test.cpp
 *
 * Part of Project Thrill - http://project-thrill.org
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/common/string.hpp>
#include <examples/word_count.hpp>

#include <gtest/gtest.h>

#include <algorithm>
#include <functional>
#include <string>
#include <utility>
#include <vector>

using namespace thrill;

TEST(WordCount, WordCountSmallFileCorrectResults) {

    using examples::WordCountPair;

    std::function<void(Context&)> start_func =
        [](Context& ctx) {

            std::vector<std::string> input_vec = {
                "test",
                "this",
                "might be",
                "a test",
                "a test",
                "a test"
            };

            auto lines = DistributeFrom(ctx, input_vec, 0);

            auto red_words = examples::WordCount(lines);

            std::vector<WordCountPair> words = red_words.AllGather();

            auto compare_function = [](WordCountPair wp1, WordCountPair wp2) {
                                        return wp1.first < wp2.first;
                                    };

            std::sort(words.begin(), words.end(), compare_function);

            ASSERT_EQ(5u, words.size());

            std::string this_str = "this";
            std::string might = "might";
            std::string be = "be";
            std::string a = "a";
            std::string test = "test";

            ASSERT_EQ(WordCountPair(a, 3), words[0]);
            ASSERT_EQ(WordCountPair(be, 1), words[1]);
            ASSERT_EQ(WordCountPair(might, 1), words[2]);
            ASSERT_EQ(WordCountPair(test, 4), words[3]);
            ASSERT_EQ(WordCountPair(this_str, 1), words[4]);
        };

    api::RunLocalTests(start_func);
}

TEST(WordCount, Generate1024DoesNotCrash) {

    using examples::WordCountPair;

    size_t size = 1024;

    std::function<void(Context&)> start_func =
        [&size](Context& ctx) {

            auto lines = GenerateFromFile(
                    ctx, "inputs/headwords",
                    [](const std::string& line) {
                        return line;
                    },
                    size);

            auto reduced_words = examples::WordCount(lines);

            reduced_words.Map(
                            [](const WordCountPair& wc) {
                                return wc.first + ": " + std::to_string(wc.second);
                            })
                    .WriteLinesMany(
                            "outputs/wordcount-");

            return 42;
        };

    api::RunLocalTests(start_func);
}

TEST(WordCount, ReadBaconDoesNotCrash) {

    using examples::WordCountPair;

    std::function<void(Context&)> start_func =
        [](Context& ctx) {

            auto lines = ReadLines(ctx, "inputs/wordcount.in");

            auto red_words = examples::WordCount(lines);

            red_words.Map(
                            [](const WordCountPair& wc) {
                                return wc.first + ": " + std::to_string(wc.second);
                            })
                    .WriteLinesMany(
                            "outputs/wordcount-");

            return 0;
        };

    api::RunLocalTests(start_func);
}

/******************************************************************************/
<commit_msg>fix 2 tests<commit_after>/*******************************************************************************
 * tests/examples/wordcount_test.cpp
 *
 * Part of Project Thrill - http://project-thrill.org
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/common/string.hpp>
#include <examples/word_count.hpp>

#include <gtest/gtest.h>

#include <algorithm>
#include <functional>
#include <string>
#include <utility>
#include <vector>

using namespace thrill;

using thrill::DIA;
using thrill::Context;

TEST(WordCount, WordCountSmallFileCorrectResults) {

    using examples::WordCountPair;

    std::function<void(Context&)> start_func =
        [](Context& ctx) {

            std::vector<std::string> input_vec = {
                "test",
                "this",
                "might be",
                "a test",
                "a test",
                "a test"
            };

            auto lines = DistributeFrom(ctx, input_vec, 0);

            auto red_words = examples::WordCount(lines);

            std::vector<WordCountPair> words = red_words.AllGather();

            auto compare_function = [](WordCountPair wp1, WordCountPair wp2) {
                                        return wp1.first < wp2.first;
                                    };

            std::sort(words.begin(), words.end(), compare_function);

            ASSERT_EQ(5u, words.size());

            std::string this_str = "this";
            std::string might = "might";
            std::string be = "be";
            std::string a = "a";
            std::string test = "test";

            ASSERT_EQ(WordCountPair(a, 3), words[0]);
            ASSERT_EQ(WordCountPair(be, 1), words[1]);
            ASSERT_EQ(WordCountPair(might, 1), words[2]);
            ASSERT_EQ(WordCountPair(test, 4), words[3]);
            ASSERT_EQ(WordCountPair(this_str, 1), words[4]);
        };

    api::RunLocalTests(start_func);
}

TEST(WordCount, Generate1024DoesNotCrash) {

    using examples::WordCountPair;

    size_t size = 1024;

    std::function<void(Context&)> start_func =
        [&size](Context& ctx) {
            ctx.set_consume(true);

            auto lines = GenerateFromFile(
                    ctx, "inputs/headwords",
                    [](const std::string& line) {
                        return line;
                    },
                    size);

            auto reduced_words = examples::WordCount(lines);

            reduced_words.Map(
                            [](const WordCountPair& wc) {
                                return wc.first + ": " + std::to_string(wc.second);
                            })
                    .WriteLinesMany(
                            "outputs/wordcount-");
        };

    api::RunLocalTests(start_func);
}

TEST(WordCount, ReadBaconDoesNotCrash) {

    using examples::WordCountPair;

    std::function<void(Context&)> start_func =
        [](Context& ctx) {
            ctx.set_consume(true);

            auto lines = ReadLines(ctx, "inputs/wordcount.in");

            auto red_words = examples::WordCount(lines);

            red_words.Map(
                            [](const WordCountPair& wc) {
                                return wc.first + ": " + std::to_string(wc.second);
                            })
                    .WriteLinesMany(
                            "outputs/wordcount-");
        };

    api::RunLocalTests(start_func);
}

/******************************************************************************/
<|endoftext|>


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

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>

#include <memory>
#include <utility>

#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/grid/alugrid.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#else
#error "This test requires alugrid!"
#endif

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/stuff/functions/combined.hh>

#include <dune/gdt/spaces/tools.hh>
#include <dune/gdt/spaces/continuouslagrange/fem.hh>
#include <dune/gdt/playground/spaces/finitevolume/default.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/darcy.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>

class errors_are_not_as_expected : public Dune::Exception
{
};

// +----------------------------------------------------------------------------+
// | 1st we define all the test structs that do something at the end of the day |
// +----------------------------------------------------------------------------+

template <class SpaceTypes>
class Darcy_Operator : public ::testing::Test
{
  typedef typename SpaceTypes::first_type SourceSpaceType;
  typedef typename SpaceTypes::second_type RangeSpaceType;

  typedef typename RangeSpaceType::GridViewType GridViewType;
  typedef typename GridViewType::Grid GridType;
  typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = SourceSpaceType::dimDomain;
  typedef double RangeFieldType;

#if HAVE_EIGEN
  typedef Dune::Stuff::LA::EigenDenseVector<RangeFieldType> VectorType;
#elif HAVE_DUNE_ISTL
  typedef Dune::Stuff::LA::IstlDenseVector<RangeFieldType> VectorType;
#else
  typedef Dune::Stuff::LA::CommonDenseVector<RangeFieldType> VectorType;
#endif

public:
  void produces_correct_results() const
  {
    using namespace Dune;
    using namespace GDT;

    GridProviderType grid_provider(0.0, 1.0, 4);
    auto grid = grid_provider.grid();
    grid->globalRefine(1);

    typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1> FunctionType;
    const FunctionType source("x", "x[0] * x[1]", 2, "source", {{"x[1]", "x[0]"}});

    const RangeSpaceType range_space(SpaceTools::GridPartView<RangeSpaceType>::create_leaf(*grid));
    VectorType range_vector(range_space.mapper().size());
    DiscreteFunction<RangeSpaceType, VectorType> range(range_space, range_vector);

    const FunctionType function("x", "-1.0", 0);
    const Operators::Darcy<GridViewType, FunctionType> darcy_operator(*(range_space.grid_view()), function);
    darcy_operator.apply(source, range);

    const Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain>
        desired_output(
            "x", std::vector<std::string>({"x[1]", "x[0]"}), 1, "desired output", {{"0.0", "1.0"}, {"1.0", "0.0"}});

    const Products::L2<GridViewType> l2_product(*(range_space.grid_view()));
    const RangeFieldType l2_error          = l2_product.induced_norm(desired_output - range);
    const RangeFieldType l2_error_expected = expected_result_("l2", desired_output, range_space.grid_view());
    if (l2_error > l2_error_expected)
      DUNE_THROW_COLORFULLY(errors_are_not_as_expected, l2_error << " vs. " << l2_error_expected);

    const Products::H1SemiGeneric<GridViewType> h1_semi_product(*(range_space.grid_view()));
    const RangeFieldType h1_error          = h1_semi_product.induced_norm(desired_output - range);
    const RangeFieldType h1_error_expected = expected_result_("h1", desired_output, range_space.grid_view());
    if (h1_error > h1_error_expected)
      DUNE_THROW_COLORFULLY(errors_are_not_as_expected, h1_error << " vs. " << h1_error_expected);
  } // ... produces_correct_results()

private:
  template <class FunctionType, class GV>
  RangeFieldType expected_result_(const std::string type, const FunctionType& desired_output,
                                  const std::shared_ptr<const GV>& grid_view_ptr) const
  {
    typedef typename Dune::GDT::SpaceTools::LeafGridPartView<GridType, RangeSpaceType::needs_grid_view>::Type GPV;
    if (std::is_base_of<Dune::GDT::Spaces::ContinuousLagrange::FemBased<GPV, 1, RangeFieldType, dimDomain>,
                        RangeSpaceType>::value) {
      if (type == "l2")
        return 2.18e-16;
      else if (type == "h1")
        return 3.12e-15;
      else
        DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
    } else if (std::is_base_of<Dune::GDT::Spaces::RaviartThomas::PdelabBased<GPV, 0, RangeFieldType, dimDomain>,
                               RangeSpaceType>::value) {
      typedef Dune::GDT::Spaces::FiniteVolume::Default<GV, RangeFieldType, dimDomain> FvSpaceType;
      const FvSpaceType fv_space(grid_view_ptr);
      VectorType fv_desired_output_vector(fv_space.mapper().size());
      Dune::GDT::DiscreteFunction<FvSpaceType, VectorType> fv_desired_output(fv_space, fv_desired_output_vector);
      const Dune::GDT::Operators::L2Projection<GV> l2_projection(*grid_view_ptr);
      l2_projection.apply(desired_output, fv_desired_output);
      const Dune::GDT::Products::L2<GV> l2_product(*grid_view_ptr);
      const Dune::GDT::Products::H1SemiGeneric<GV> h1_semi_product(*grid_view_ptr);
      if (type == "l2")
        return 2.0 * l2_product.induced_norm(desired_output - fv_desired_output);
      else if (type == "h1")
        return h1_semi_product.induced_norm(desired_output - fv_desired_output);
      else
        DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
    } else
      DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
  } // ... expected_result_(...)
}; // class Darcy_Operator

// +----------------------------------------------------------------------------+
// | 2nd we define all arguments the above test structs are to be compiled with |
// +----------------------------------------------------------------------------+

typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
typedef typename Dune::GDT::SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef
    typename Dune::GDT::SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;

typedef testing::
    Types<std::pair<Dune::GDT::Spaces::ContinuousLagrange::FemBased<AluConform2dLeafGridPartType, 1, double, 1>,
                    Dune::GDT::Spaces::ContinuousLagrange::FemBased<AluConform2dLeafGridPartType, 1, double, 2>>,
          std::pair<Dune::GDT::Spaces::ContinuousLagrange::FemBased<AluConform2dLeafGridPartType, 1, double, 1>,
                    Dune::GDT::Spaces::RaviartThomas::PdelabBased<AluConform2dLeafGridViewType, 0, double, 2>>>
        SpaceTypes;

// +--------------------------------------------------------------------------------------+
// | 3rd we combine all test structs with their appropriate arguments to create the tests |
// | (comment out the following lines if you do not want a test to run)                   |
// +--------------------------------------------------------------------------------------+

TYPED_TEST_CASE(Darcy_Operator, SpaceTypes);
TYPED_TEST(Darcy_Operator, produces_correct_results)
{
  this->produces_correct_results();
}

// +--------------------------------------------------------------------------------------+
// | 4th we run all the tests                                                             |
// | (run the resulting executable with '--gtest_catch_exceptions=0' to see an exception) |
// +--------------------------------------------------------------------------------------+

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
} // ... main(...)
<commit_msg>[tests.operator_reconstruction] disabled some, broken<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>

#include <memory>
#include <utility>

#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/grid/alugrid.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#else
#error "This test requires alugrid!"
#endif

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/stuff/functions/combined.hh>

#include <dune/gdt/spaces/tools.hh>
#include <dune/gdt/spaces/continuouslagrange/fem.hh>
#include <dune/gdt/playground/spaces/finitevolume/default.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/darcy.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>

class errors_are_not_as_expected : public Dune::Exception
{
};

// +----------------------------------------------------------------------------+
// | 1st we define all the test structs that do something at the end of the day |
// +----------------------------------------------------------------------------+

template <class SpaceTypes>
class Darcy_Operator : public ::testing::Test
{
  typedef typename SpaceTypes::first_type SourceSpaceType;
  typedef typename SpaceTypes::second_type RangeSpaceType;

  typedef typename RangeSpaceType::GridViewType GridViewType;
  typedef typename GridViewType::Grid GridType;
  typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = SourceSpaceType::dimDomain;
  typedef double RangeFieldType;

#if HAVE_EIGEN
  typedef Dune::Stuff::LA::EigenDenseVector<RangeFieldType> VectorType;
#elif HAVE_DUNE_ISTL
  typedef Dune::Stuff::LA::IstlDenseVector<RangeFieldType> VectorType;
#else
  typedef Dune::Stuff::LA::CommonDenseVector<RangeFieldType> VectorType;
#endif

public:
  void produces_correct_results() const
  {
    using namespace Dune;
    using namespace GDT;

    GridProviderType grid_provider(0.0, 1.0, 4);
    auto grid = grid_provider.grid();
    grid->globalRefine(1);

    typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1> FunctionType;
    const FunctionType source("x", "x[0] * x[1]", 2, "source", {{"x[1]", "x[0]"}});

    const RangeSpaceType range_space(SpaceTools::GridPartView<RangeSpaceType>::create_leaf(*grid));
    VectorType range_vector(range_space.mapper().size());
    DiscreteFunction<RangeSpaceType, VectorType> range(range_space, range_vector);

    const FunctionType function("x", "-1.0", 0);
    const Operators::Darcy<GridViewType, FunctionType> darcy_operator(*(range_space.grid_view()), function);
    darcy_operator.apply(source, range);

    const Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain>
        desired_output(
            "x", std::vector<std::string>({"x[1]", "x[0]"}), 1, "desired output", {{"0.0", "1.0"}, {"1.0", "0.0"}});

    const Products::L2<GridViewType> l2_product(*(range_space.grid_view()));
    const RangeFieldType l2_error          = l2_product.induced_norm(desired_output - range);
    const RangeFieldType l2_error_expected = expected_result_("l2", desired_output, range_space.grid_view());
    if (l2_error > l2_error_expected)
      DUNE_THROW_COLORFULLY(errors_are_not_as_expected, l2_error << " vs. " << l2_error_expected);

    const Products::H1SemiGeneric<GridViewType> h1_semi_product(*(range_space.grid_view()));
    const RangeFieldType h1_error          = h1_semi_product.induced_norm(desired_output - range);
    const RangeFieldType h1_error_expected = expected_result_("h1", desired_output, range_space.grid_view());
    if (h1_error > h1_error_expected)
      DUNE_THROW_COLORFULLY(errors_are_not_as_expected, h1_error << " vs. " << h1_error_expected);
  } // ... produces_correct_results()

private:
  template <class FunctionType, class GV>
  RangeFieldType expected_result_(const std::string type, const FunctionType& desired_output,
                                  const std::shared_ptr<const GV>& grid_view_ptr) const
  {
    typedef typename Dune::GDT::SpaceTools::LeafGridPartView<GridType, RangeSpaceType::needs_grid_view>::Type GPV;
    if (std::is_base_of<Dune::GDT::Spaces::ContinuousLagrange::FemBased<GPV, 1, RangeFieldType, dimDomain>,
                        RangeSpaceType>::value) {
      if (type == "l2")
        return 2.18e-16;
      else if (type == "h1")
        return 3.12e-15;
      else
        DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
    } else if (std::is_base_of<Dune::GDT::Spaces::RaviartThomas::PdelabBased<GPV, 0, RangeFieldType, dimDomain>,
                               RangeSpaceType>::value) {
      typedef Dune::GDT::Spaces::FiniteVolume::Default<GV, RangeFieldType, dimDomain> FvSpaceType;
      const FvSpaceType fv_space(grid_view_ptr);
      VectorType fv_desired_output_vector(fv_space.mapper().size());
      Dune::GDT::DiscreteFunction<FvSpaceType, VectorType> fv_desired_output(fv_space, fv_desired_output_vector);
      const Dune::GDT::Operators::L2Projection<GV> l2_projection(*grid_view_ptr);
      l2_projection.apply(desired_output, fv_desired_output);
      const Dune::GDT::Products::L2<GV> l2_product(*grid_view_ptr);
      const Dune::GDT::Products::H1SemiGeneric<GV> h1_semi_product(*grid_view_ptr);
      if (type == "l2")
        return 2.0 * l2_product.induced_norm(desired_output - fv_desired_output);
      else if (type == "h1")
        return h1_semi_product.induced_norm(desired_output - fv_desired_output);
      else
        DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
    } else
      DUNE_THROW_COLORFULLY(Dune::Stuff::Exceptions::internal_error, type);
  } // ... expected_result_(...)
}; // class Darcy_Operator

// +----------------------------------------------------------------------------+
// | 2nd we define all arguments the above test structs are to be compiled with |
// +----------------------------------------------------------------------------+

typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
typedef typename Dune::GDT::SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef
    typename Dune::GDT::SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;

typedef testing::
    Types</*std::pair< Dune::GDT::Spaces::ContinuousLagrange::FemBased< AluConform2dLeafGridPartType, 1, double, 1 >,
                                   Dune::GDT::Spaces::ContinuousLagrange::FemBased< AluConform2dLeafGridPartType, 1, double, 2 > >
                      ,*/ std::
              pair<Dune::GDT::Spaces::ContinuousLagrange::FemBased<AluConform2dLeafGridPartType, 1, double, 1>,
                   Dune::GDT::Spaces::RaviartThomas::PdelabBased<AluConform2dLeafGridViewType, 0, double, 2>>>
        SpaceTypes;

// +--------------------------------------------------------------------------------------+
// | 3rd we combine all test structs with their appropriate arguments to create the tests |
// | (comment out the following lines if you do not want a test to run)                   |
// +--------------------------------------------------------------------------------------+

TYPED_TEST_CASE(Darcy_Operator, SpaceTypes);
TYPED_TEST(Darcy_Operator, produces_correct_results)
{
  this->produces_correct_results();
}

// +--------------------------------------------------------------------------------------+
// | 4th we run all the tests                                                             |
// | (run the resulting executable with '--gtest_catch_exceptions=0' to see an exception) |
// +--------------------------------------------------------------------------------------+

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "\nDune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << "\n" << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
} // ... main(...)
<|endoftext|>


<commit_before>/**
 * @file test_uniform_int.cpp
 *
 * @brief Test uniform integer distribution
 *
 * @author Dahua Lin
 */

#include "distr_test_base.h"
#include <light_mat/random/uniform_int_distr.h>

default_rand_stream rstream;
const index_t N = 200000;

T_CASE( test_std_uniform_int )
{
	const uint32_t b = 5;
	std_uniform_int_distr<T> distr(b);

	const uint32_t s = b + 1;

	ASSERT_EQ( distr.a(), 0 );
	ASSERT_EQ( distr.b(), b );
	ASSERT_EQ( distr.span(), s );
	ASSERT_EQ( distr.mean(), double(b) / 2 );
	ASSERT_EQ( distr.var(),  double((s * s - 1)) / 12 );

	double ptol = get_p_tol(N);
	test_discrete_rng(distr, rstream, N, b+1, ptol);
}

T_CASE( test_uniform_int )
{
	const uint32_t a = 2;
	const uint32_t b = 6;
	uniform_int_distr<T> distr(a, b);

	const uint32_t s = b - a + 1;

	ASSERT_EQ( distr.a(), a );
	ASSERT_EQ( distr.b(), b );
	ASSERT_EQ( distr.span(), s );
	ASSERT_EQ( distr.mean(), double(a + b) / 2 );
	ASSERT_EQ( distr.var(),  double((s * s - 1)) / 12 );

	double ptol = get_p_tol(N);
	test_discrete_rng(distr, rstream, N, b+1, ptol);
}

AUTO_TPACK( test_uniform_int )
{
	ADD_T_CASE( test_std_uniform_int, uint32_t )
	ADD_T_CASE( test_std_uniform_int, int32_t )

	ADD_T_CASE( test_uniform_int, uint32_t )
	ADD_T_CASE( test_uniform_int, int32_t )
}

<commit_msg>minor fixes to test_uniform_int<commit_after>/**
 * @file test_uniform_int.cpp
 *
 * @brief Test uniform integer distribution
 *
 * @author Dahua Lin
 */

#include "distr_test_base.h"
#include <light_mat/random/uniform_int_distr.h>

default_rand_stream rstream;
const index_t N = 200000;

T_CASE( test_std_uniform_int )
{
	const T b = 5;
	std_uniform_int_distr<T> distr(b);

	const T s = b + 1;

	ASSERT_EQ( distr.a(), 0 );
	ASSERT_EQ( distr.b(), b );
	ASSERT_EQ( distr.span(), s );
	ASSERT_EQ( distr.mean(), double(b) / 2 );
	ASSERT_EQ( distr.var(),  double((s * s - 1)) / 12 );

	double ptol = get_p_tol(N);
	test_discrete_rng(distr, rstream, N, b+1, ptol);
}

T_CASE( test_uniform_int )
{
	const T a = 2;
	const T b = 6;
	uniform_int_distr<T> distr(a, b);

	const T s = b - a + 1;

	ASSERT_EQ( distr.a(), a );
	ASSERT_EQ( distr.b(), b );
	ASSERT_EQ( distr.span(), s );
	ASSERT_EQ( distr.mean(), double(a + b) / 2 );
	ASSERT_EQ( distr.var(),  double((s * s - 1)) / 12 );

	double ptol = get_p_tol(N);
	test_discrete_rng(distr, rstream, N, b+1, ptol);
}

AUTO_TPACK( test_uniform_int )
{
	ADD_T_CASE( test_std_uniform_int, uint32_t )
	ADD_T_CASE( test_std_uniform_int, int32_t )

	ADD_T_CASE( test_uniform_int, uint32_t )
	ADD_T_CASE( test_uniform_int, int32_t )
}

<|endoftext|>


<commit_before>#include "enrichment_tests.h"

#include <cmath>

#include <gtest/gtest.h>

#include "composition.h"
#include "context.h"
#include "cyc_limits.h"
#include "env.h"
#include "error.h"
#include "material.h"
#include "recorder.h"
#include "timer.h"

namespace cyclus {
namespace toolkit {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetUp() {
  Env::SetNucDataPath();

  feed_ = 0.0072;
  product_ = 0.05;
  tails_ = 0.002;

  assay_u_ = product_;
  mass_u_ = 10;

  Timer ti;
  Recorder rec;
  Context ctx(&ti, &rec);

  CompMap v;
  v[922350000] = assay_u_;
  v[922380000] = 1 - assay_u_;
  Composition::Ptr comp = Composition::CreateFromAtom(v);
  mat_ = Material::CreateUntracked(mass_u_, comp);

  SetEnrichmentParameters();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::TearDown() {}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetEnrichmentParameters() {
  double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1);
  double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1);
  double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1);

  feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_);
  tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_);
  swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, assays) {
  Assays a(feed_, product_, tails_);
  EXPECT_DOUBLE_EQ(feed_, a.Feed());
  EXPECT_DOUBLE_EQ(product_, a.Product());
  EXPECT_DOUBLE_EQ(tails_, a.Tails());
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, valuefunction) {
  EXPECT_THROW(ValueFunc(0 - eps()),
               ValueError);
  EXPECT_THROW(ValueFunc(1), ValueError);

  double step = 0.001;
  double test_value = 0;
  while (test_value < 1) {
    double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1);
    EXPECT_DOUBLE_EQ(expected, ValueFunc(test_value));
    test_value += step;
  }
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, material) {
  EXPECT_DOUBLE_EQ(assay_u_, UraniumAssay(mat_));
  EXPECT_DOUBLE_EQ(mass_u_, UraniumQty(mat_));
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, enrichmentcalcs) {
  Assays assays(feed_, UraniumAssay(mat_),
                                    tails_);
  double product_qty = UraniumQty(mat_);
  EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays));
  EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays));
  EXPECT_NEAR(swu_, SwuRequired(product_qty, assays), 1e-8);
}

}  // namespace toolkit
}  // namespace cyclus
<commit_msg>delete whitespace changes<commit_after>#include "enrichment_tests.h"

#include <cmath>

#include <gtest/gtest.h>

#include "composition.h"
#include "context.h"
#include "cyc_limits.h"
#include "env.h"
#include "error.h"
#include "material.h"
#include "recorder.h"
#include "timer.h"

namespace cyclus {
namespace toolkit {

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetUp() {
  Env::SetNucDataPath();

  feed_ = 0.0072;
  product_ = 0.05;
  tails_ = 0.002;

  assay_u_ = product_;
  mass_u_ = 10;

  Timer ti;
  Recorder rec;
  Context ctx(&ti, &rec);

  CompMap v;
  v[922350000] = assay_u_;
  v[922380000] = 1 - assay_u_;
  Composition::Ptr comp = Composition::CreateFromAtom(v);
  mat_ = Material::CreateUntracked(mass_u_, comp);

  SetEnrichmentParameters();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::TearDown() {}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetEnrichmentParameters() {
  double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1);
  double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1);
  double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1);

  feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_);
  tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_);
  swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, assays) {
  Assays a(feed_, product_, tails_);
  EXPECT_DOUBLE_EQ(feed_, a.Feed());
  EXPECT_DOUBLE_EQ(product_, a.Product());
  EXPECT_DOUBLE_EQ(tails_, a.Tails());
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, valuefunction) {
  EXPECT_THROW(ValueFunc(0 - eps()),
               ValueError);
  EXPECT_THROW(ValueFunc(1), ValueError);

  double step = 0.001;
  double test_value = 0;
  while (test_value < 1) {
    double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1);
    EXPECT_DOUBLE_EQ(expected, ValueFunc(test_value));
    test_value += step;
  }
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, material) {
  EXPECT_DOUBLE_EQ(assay_u_, UraniumAssay(mat_));
  EXPECT_DOUBLE_EQ(mass_u_, UraniumQty(mat_));
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, enrichmentcalcs) {
  Assays assays(feed_, UraniumAssay(mat_),
                                    tails_);
  double product_qty = UraniumQty(mat_);
  EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays));
  EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays));
  EXPECT_NEAR(swu_, SwuRequired(product_qty, assays), 1e-8);
}

}  // namespace toolkit
}  // namespace cyclus
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

#include <iostream>
#include <cmath>

using namespace mfem;

/**
 * Utility function to generate IntegerationPoints, based on param ip
 * that are outside the unit interval.  Results are placed in output
 * parameter arr.
 */
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
                                 Array<IntegrationPoint>& arr)
{
   IntegrationPoint pt = ip;
   int idx = 0;

   switch (dim)
   {
      case 1:
         arr.SetSize(3);

         pt.x =   ip.x;    arr[idx++] = pt;
         pt.x =  -ip.x;    arr[idx++] = pt;
         pt.x = 1+ip.x;    arr[idx++] = pt;
         break;
      case 2:
         arr.SetSize(7);

         pt.Set2(  ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2( -ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2(  ip.x,  -ip.y); arr[idx++] = pt;
         pt.Set2( -ip.x,  -ip.y); arr[idx++] = pt;
         pt.Set2(1+ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2(  ip.x, 1+ip.y); arr[idx++] = pt;
         pt.Set2(1+ip.x, 1+ip.y); arr[idx++] = pt;
         break;
      case 3:
         arr.SetSize(15);

         pt.Set3(  ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,  -ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,  -ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,   ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,   ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,  -ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,  -ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x, 1+ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x, 1+ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,   ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x,   ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x, 1+ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x, 1+ip.y, 1+ip.z );  arr[idx++] = pt;
         break;
   }
}

/**
 * Tests fe->CalcShape() over a grid of IntegrationPoints
 * of resolution res. Also tests at integration poins
 * that are outside the element.
 */
void TestCalcShape(FiniteElement* fe, int res)
{
   int dim = fe->GetDim();

   Vector weights( fe->GetDof() );

   // Get a uniform grid or integration points
   RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
   const IntegrationRule& intRule = ref->RefPts;

   int npoints = intRule.GetNPoints();
   for (int i=0; i < npoints; ++i)
   {
      // Get the current integration point from intRule
      IntegrationPoint pt = intRule.IntPoint(i);

      // Get several variants of this integration point
      // some of which are inside the element and some are outside
      Array<IntegrationPoint> ipArr;
      GetRelatedIntegrationPoints( pt, dim, ipArr );

      // For each such integration point check that the weights
      // from CalcShape() sum to one
      for (int j=0; j < ipArr.Size(); ++j)
      {
         IntegrationPoint& ip = ipArr[j];
         fe->CalcShape(ip, weights);
         REQUIRE( weights.Sum() == Approx(1.) );
      }
   }
}

TEST_CASE("CalcShape for several Lagrange FiniteElement instances",
          "[Lagrange1DFiniteElement]"
          "[BiLinear2DFiniteElement]"
          "[BiQuad2DFiniteElement]"
          "[LagrangeHexFiniteElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("Lagrange1DFiniteElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing Lagrange1DFiniteElement::CalcShape() "
                   << "for order " << order << std::endl;
         Lagrange1DFiniteElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("BiLinear2DFiniteElement")
   {
      std::cout << "Testing BiLinear2DFiniteElement::CalcShape()" << std::endl;
      BiLinear2DFiniteElement fe;
      TestCalcShape(&fe, resolution);
   }

   SECTION("BiQuad2DFiniteElement")
   {
      std::cout << "Testing BiQuad2DFiniteElement::CalcShape()" << std::endl;
      BiQuad2DFiniteElement fe;
      TestCalcShape(&fe, resolution);
   }

   SECTION("LagrangeHexFiniteElement")
   {
      std::cout << "Testing LagrangeHexFiniteElement::CalcShape() "
                << "for order 2" << std::endl;

      // Comments for LagrangeHexFiniteElement state
      // that only degree 2 is functional for this class
      LagrangeHexFiniteElement fe(2);
      TestCalcShape(&fe, resolution);
   }
}

TEST_CASE("CalcShape for several H1 FiniteElement instances",
          "[H1_SegmentElement]"
          "[H1_TriangleElement]"
          "[H1_QuadrilateralElement]"
          "[H1_TetrahedronElement]"
          "[H1_HexahedronElement]"
	  "[H1_WedgeElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("H1_SegmentElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_SegmentElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_SegmentElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_TriangleElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_TriangleElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_TriangleElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_QuadrilateralElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_QuadrilateralElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_QuadrilateralElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_TetrahedronElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_TetrahedronElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_TetrahedronElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_HexahedronElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_HexahedronElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_HexahedronElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_WedgeElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_WedgeElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_WedgeElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

}
<commit_msg>make style<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

#include <iostream>
#include <cmath>

using namespace mfem;

/**
 * Utility function to generate IntegerationPoints, based on param ip
 * that are outside the unit interval.  Results are placed in output
 * parameter arr.
 */
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
                                 Array<IntegrationPoint>& arr)
{
   IntegrationPoint pt = ip;
   int idx = 0;

   switch (dim)
   {
      case 1:
         arr.SetSize(3);

         pt.x =   ip.x;    arr[idx++] = pt;
         pt.x =  -ip.x;    arr[idx++] = pt;
         pt.x = 1+ip.x;    arr[idx++] = pt;
         break;
      case 2:
         arr.SetSize(7);

         pt.Set2(  ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2( -ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2(  ip.x,  -ip.y); arr[idx++] = pt;
         pt.Set2( -ip.x,  -ip.y); arr[idx++] = pt;
         pt.Set2(1+ip.x,   ip.y); arr[idx++] = pt;
         pt.Set2(  ip.x, 1+ip.y); arr[idx++] = pt;
         pt.Set2(1+ip.x, 1+ip.y); arr[idx++] = pt;
         break;
      case 3:
         arr.SetSize(15);

         pt.Set3(  ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,  -ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,  -ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,   ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,   ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,  -ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3( -ip.x,  -ip.y,  -ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x,   ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x, 1+ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x, 1+ip.y,   ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x,   ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x,   ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(  ip.x, 1+ip.y, 1+ip.z );  arr[idx++] = pt;
         pt.Set3(1+ip.x, 1+ip.y, 1+ip.z );  arr[idx++] = pt;
         break;
   }
}

/**
 * Tests fe->CalcShape() over a grid of IntegrationPoints
 * of resolution res. Also tests at integration poins
 * that are outside the element.
 */
void TestCalcShape(FiniteElement* fe, int res)
{
   int dim = fe->GetDim();

   Vector weights( fe->GetDof() );

   // Get a uniform grid or integration points
   RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
   const IntegrationRule& intRule = ref->RefPts;

   int npoints = intRule.GetNPoints();
   for (int i=0; i < npoints; ++i)
   {
      // Get the current integration point from intRule
      IntegrationPoint pt = intRule.IntPoint(i);

      // Get several variants of this integration point
      // some of which are inside the element and some are outside
      Array<IntegrationPoint> ipArr;
      GetRelatedIntegrationPoints( pt, dim, ipArr );

      // For each such integration point check that the weights
      // from CalcShape() sum to one
      for (int j=0; j < ipArr.Size(); ++j)
      {
         IntegrationPoint& ip = ipArr[j];
         fe->CalcShape(ip, weights);
         REQUIRE( weights.Sum() == Approx(1.) );
      }
   }
}

TEST_CASE("CalcShape for several Lagrange FiniteElement instances",
          "[Lagrange1DFiniteElement]"
          "[BiLinear2DFiniteElement]"
          "[BiQuad2DFiniteElement]"
          "[LagrangeHexFiniteElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("Lagrange1DFiniteElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing Lagrange1DFiniteElement::CalcShape() "
                   << "for order " << order << std::endl;
         Lagrange1DFiniteElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("BiLinear2DFiniteElement")
   {
      std::cout << "Testing BiLinear2DFiniteElement::CalcShape()" << std::endl;
      BiLinear2DFiniteElement fe;
      TestCalcShape(&fe, resolution);
   }

   SECTION("BiQuad2DFiniteElement")
   {
      std::cout << "Testing BiQuad2DFiniteElement::CalcShape()" << std::endl;
      BiQuad2DFiniteElement fe;
      TestCalcShape(&fe, resolution);
   }

   SECTION("LagrangeHexFiniteElement")
   {
      std::cout << "Testing LagrangeHexFiniteElement::CalcShape() "
                << "for order 2" << std::endl;

      // Comments for LagrangeHexFiniteElement state
      // that only degree 2 is functional for this class
      LagrangeHexFiniteElement fe(2);
      TestCalcShape(&fe, resolution);
   }
}

TEST_CASE("CalcShape for several H1 FiniteElement instances",
          "[H1_SegmentElement]"
          "[H1_TriangleElement]"
          "[H1_QuadrilateralElement]"
          "[H1_TetrahedronElement]"
          "[H1_HexahedronElement]"
          "[H1_WedgeElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("H1_SegmentElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_SegmentElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_SegmentElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_TriangleElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_TriangleElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_TriangleElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_QuadrilateralElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_QuadrilateralElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_QuadrilateralElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_TetrahedronElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_TetrahedronElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_TetrahedronElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_HexahedronElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_HexahedronElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_HexahedronElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

   SECTION("H1_WedgeElement")
   {
      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing H1_WedgeElement::CalcShape() "
                   << "for order " << order << std::endl;
         H1_WedgeElement fe(order);
         TestCalcShape(&fe, resolution);
      }
   }

}
<|endoftext|>


<commit_before>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2011 Sandro Santilli <strk@keybit.net
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: operation/union/PointGeometryUnion.java r320 (JTS-1.12)
 *
 **********************************************************************/

#include <memory> // for auto_ptr
#include <cassert> // for assert
#include <algorithm> // for copy
#include <geos/operation/union/PointGeometryUnion.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Puntal.h>
#include <geos/geom/Point.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Location.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/util/GeometryCombiner.h>
#include <geos/algorithm/PointLocator.h>

namespace geos {
namespace operation { // geos::operation
namespace geounion {  // geos::operation::geounion

/* public */
std::auto_ptr<geom::Geometry>
PointGeometryUnion::Union() const
{
  using namespace geom;
  using algorithm::PointLocator;
  using geom::util::GeometryCombiner;

  PointLocator locater;
  // use a set to eliminate duplicates, as required for union
  std::set<Coordinate> exteriorCoords;

  for (std::size_t i=0, n=pointGeom.getNumGeometries(); i<n; ++i) {
      const Point* point = dynamic_cast<const Point*>(pointGeom.getGeometryN(i));
      assert(point);
      const Coordinate* coord = point->getCoordinate();
      int loc = locater.locate(*coord, &otherGeom);
      if (loc == Location::EXTERIOR)
              exteriorCoords.insert(*coord);
  }

  // if no points are in exterior, return the other geom
  if (exteriorCoords.empty())
          return std::auto_ptr<Geometry>(otherGeom.clone());

  // make a puntal geometry of appropriate size
  std::auto_ptr<Geometry> ptComp;

  if (exteriorCoords.size() == 1) {
    ptComp.reset( geomFact->createPoint(*(exteriorCoords.begin())) );
  }
  else
  {
    std::vector<Coordinate> coords;
    std::copy(exteriorCoords.begin(), exteriorCoords.end(),
      back_inserter(coords));
    ptComp.reset( geomFact->createMultiPoint(coords) );
  }

  // add point component to the other geometry
  return std::auto_ptr<Geometry> (
    GeometryCombiner::combine(ptComp.get(), &otherGeom)
  );
}

/* public  static */
std::auto_ptr<geom::Geometry>
PointGeometryUnion::Union(const geom::Puntal& pointGeom,
      const geom::Geometry& otherGeom)
{
  PointGeometryUnion unioner(pointGeom, otherGeom);
  return unioner.Union();
}

/* public */
PointGeometryUnion::PointGeometryUnion(const geom::Puntal& pointGeom_,
                     const geom::Geometry& otherGeom_)
  :
  pointGeom ( pointGeom_ ),
  otherGeom ( otherGeom_ )
{
  geomFact = otherGeom.getFactory();
}

} // namespace geos::operation::union
} // namespace geos::operation
} // namespace geos
<commit_msg>Optimize container->container copy, on Mat's suggestion<commit_after>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2011 Sandro Santilli <strk@keybit.net
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: operation/union/PointGeometryUnion.java r320 (JTS-1.12)
 *
 **********************************************************************/

#include <memory> // for auto_ptr
#include <cassert> // for assert
#include <algorithm> // for copy
#include <geos/operation/union/PointGeometryUnion.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Puntal.h>
#include <geos/geom/Point.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Location.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/util/GeometryCombiner.h>
#include <geos/algorithm/PointLocator.h>

namespace geos {
namespace operation { // geos::operation
namespace geounion {  // geos::operation::geounion

/* public */
std::auto_ptr<geom::Geometry>
PointGeometryUnion::Union() const
{
  using namespace geom;
  using algorithm::PointLocator;
  using geom::util::GeometryCombiner;

  PointLocator locater;
  // use a set to eliminate duplicates, as required for union
  std::set<Coordinate> exteriorCoords;

  for (std::size_t i=0, n=pointGeom.getNumGeometries(); i<n; ++i) {
      const Point* point = dynamic_cast<const Point*>(pointGeom.getGeometryN(i));
      assert(point);
      const Coordinate* coord = point->getCoordinate();
      int loc = locater.locate(*coord, &otherGeom);
      if (loc == Location::EXTERIOR)
              exteriorCoords.insert(*coord);
  }

  // if no points are in exterior, return the other geom
  if (exteriorCoords.empty())
          return std::auto_ptr<Geometry>(otherGeom.clone());

  // make a puntal geometry of appropriate size
  std::auto_ptr<Geometry> ptComp;

  if (exteriorCoords.size() == 1) {
    ptComp.reset( geomFact->createPoint(*(exteriorCoords.begin())) );
  }
  else
  {
    std::vector<Coordinate> coords(exteriorCoords.size());
    std::copy(exteriorCoords.begin(), exteriorCoords.end(), coords.begin());
    ptComp.reset( geomFact->createMultiPoint(coords) );
  }

  // add point component to the other geometry
  return std::auto_ptr<Geometry> (
    GeometryCombiner::combine(ptComp.get(), &otherGeom)
  );
}

/* public  static */
std::auto_ptr<geom::Geometry>
PointGeometryUnion::Union(const geom::Puntal& pointGeom,
      const geom::Geometry& otherGeom)
{
  PointGeometryUnion unioner(pointGeom, otherGeom);
  return unioner.Union();
}

/* public */
PointGeometryUnion::PointGeometryUnion(const geom::Puntal& pointGeom_,
                     const geom::Geometry& otherGeom_)
  :
  pointGeom ( pointGeom_ ),
  otherGeom ( otherGeom_ )
{
  geomFact = otherGeom.getFactory();
}

} // namespace geos::operation::union
} // namespace geos::operation
} // namespace geos
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "classviewsymbollocation.h"
#include "classviewmanager.h"
#include "classviewnavigationwidgetfactory.h"
#include "classviewparser.h"
#include "classviewutils.h"

#include <utils/qtcassert.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <texteditor/basetexteditor.h>
#include <cplusplus/ModelManagerInterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <texteditor/itexteditor.h>

#include <QtCore/QThread>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>

namespace ClassView {
namespace Internal {

///////////////////////////////// ManagerPrivate //////////////////////////////////

/*!
   \struct ManagerPrivate
   \brief Private class data for \a Manager
   \sa Manager
 */
struct ManagerPrivate
{
    ManagerPrivate() : state(false) {}

    //! instance
    static Manager *instance;

    //! Pointer to widget factory
    QPointer<NavigationWidgetFactory> widgetFactory;

    //! State mutex
    QMutex mutexState;

    //! Internal manager state. \sa Manager::state
    bool state;

    //! code state/changes parser
    Parser parser;

    //! separate thread for the parser
    QThread parserThread;

    //! cpp code model manager
    QPointer<CPlusPlus::CppModelManagerInterface> codeModelManager;

    //! there is some massive operation ongoing so temporary we should wait
    bool disableCodeParser;
};

// static variable initialization
Manager *ManagerPrivate::instance = 0;

///////////////////////////////// Manager //////////////////////////////////

Manager::Manager(QObject *parent)
    : QObject(parent),
    d_ptr(new ManagerPrivate())
{
    d_ptr->widgetFactory = NavigationWidgetFactory::instance();

    // register - to be able send between signal/slots
    qRegisterMetaType<QSharedPointer<QStandardItem> >("QSharedPointer<QStandardItem>");

    initialize();

    // start a separate thread for the parser
    d_ptr->parser.moveToThread(&d_ptr->parserThread);
    d_ptr->parserThread.start();

    // initial setup
    onProjectListChanged();
}

Manager::~Manager()
{
    d_ptr->parserThread.quit();
    d_ptr->parserThread.wait();
}

Manager *Manager::instance(QObject *parent)
{
    if (!ManagerPrivate::instance)
        ManagerPrivate::instance = new Manager(parent);
    return ManagerPrivate::instance;
}

bool Manager::canFetchMore(QStandardItem *item) const
{
    return d_ptr->parser.canFetchMore(item);
}

void Manager::fetchMore(QStandardItem *item, bool skipRoot)
{
    d_ptr->parser.fetchMore(item, skipRoot);
}

void Manager::initialize()
{
    // use Qt::QueuedConnection everywhere

    // widget factory signals
    connect(d_ptr->widgetFactory, SIGNAL(widgetIsCreated()),
            SLOT(onWidgetIsCreated()), Qt::QueuedConnection);

    // internal manager state is changed
    connect(this, SIGNAL(stateChanged(bool)), SLOT(onStateChanged(bool)), Qt::QueuedConnection);

    // connections to enable/disable navi widget factory
    ProjectExplorer::SessionManager *sessionManager =
        ProjectExplorer::ProjectExplorerPlugin::instance()->session();
    connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
            SLOT(onProjectListChanged()), Qt::QueuedConnection);
    connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
            SLOT(onProjectListChanged()), Qt::QueuedConnection);

    Core::ICore *core = Core::ICore::instance();

    // connect to the progress manager for signals about Parsing tasks
    connect(core->progressManager(), SIGNAL(taskStarted(QString)),
            SLOT(onTaskStarted(QString)), Qt::QueuedConnection);
    connect(core->progressManager(), SIGNAL(allTasksFinished(QString)),
            SLOT(onAllTasksFinished(QString)), Qt::QueuedConnection);

    // connect to the cpp model manager for signals about document updates
    d_ptr->codeModelManager = CPlusPlus::CppModelManagerInterface::instance();

    // when code manager signals that document is updated - handle it by ourselves
    connect(d_ptr->codeModelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
            SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)), Qt::QueuedConnection);

    // when we signals that really document is updated - sent it to the parser
    connect(this, SIGNAL(requestDocumentUpdated(CPlusPlus::Document::Ptr)),
            &d_ptr->parser, SLOT(parseDocument(CPlusPlus::Document::Ptr)), Qt::QueuedConnection);

    //
    connect(d_ptr->codeModelManager, SIGNAL(aboutToRemoveFiles(QStringList)),
            &d_ptr->parser, SLOT(removeFiles(QStringList)), Qt::QueuedConnection);

    // translate data update from the parser to listeners
    connect(&d_ptr->parser, SIGNAL(treeDataUpdate(QSharedPointer<QStandardItem>)),
            this, SLOT(onTreeDataUpdate(QSharedPointer<QStandardItem>)), Qt::QueuedConnection);

    // requet current state - immediately after a notification
    connect(this, SIGNAL(requestTreeDataUpdate()),
            &d_ptr->parser, SLOT(requestCurrentState()), Qt::QueuedConnection);

    // full reset request to parser
    connect(this, SIGNAL(requestResetCurrentState()),
            &d_ptr->parser, SLOT(resetDataToCurrentState()), Qt::QueuedConnection);

    // clear cache request
    connect(this, SIGNAL(requestClearCache()),
            &d_ptr->parser, SLOT(clearCache()), Qt::QueuedConnection);

    // clear full cache request
    connect(this, SIGNAL(requestClearCacheAll()),
            &d_ptr->parser, SLOT(clearCacheAll()), Qt::QueuedConnection);

    // flat mode request
    connect(this, SIGNAL(requestSetFlatMode(bool)),
            &d_ptr->parser, SLOT(setFlatMode(bool)), Qt::QueuedConnection);
}

bool Manager::state() const
{
    return d_ptr->state;
}

void Manager::setState(bool state)
{
    QMutexLocker locker(&d_ptr->mutexState);

    // boolean comparsion - should be done correctly by any compiler
    if (state == d_ptr->state)
        return;

    d_ptr->state = state;

    emit stateChanged(d_ptr->state);
}

void Manager::onWidgetIsCreated()
{
    // do nothing - continue to sleep
}

void Manager::onWidgetVisibilityIsChanged(bool visibility)
{
    // activate data handling - when 1st time 'Class View' will be open
    if (visibility)
        setState(true);
}

void Manager::onStateChanged(bool state)
{
    if (state) {
        // enabled - request a current snapshots etc?..
        emit requestResetCurrentState();
    } else {
        // disabled - clean parsers internal cache
        emit requestClearCacheAll();
    }
}

void Manager::onProjectListChanged()
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    // update to the latest state
    requestTreeDataUpdate();
}

void Manager::onTaskStarted(const QString &type)
{
    if (type != CppTools::Constants::TASK_INDEX)
        return;

    // disable tree updates to speed up
    d_ptr->disableCodeParser = true;
}

void Manager::onAllTasksFinished(const QString &type)
{
    if (type != CppTools::Constants::TASK_INDEX)
        return;

    // parsing is finished, enable tree updates
    d_ptr->disableCodeParser = false;

    // do nothing if Manager is disabled
    if (!state())
        return;

    // any document might be changed, emit signal to clear cache
    emit requestClearCache();

    // request to update a tree to the current state
    emit requestResetCurrentState();
}

void Manager::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    // do nothing if updates are disabled
    if (d_ptr->disableCodeParser)
        return;

    emit requestDocumentUpdated(doc);
}

void Manager::gotoLocation(const QString &fileName, int line, int column)
{
    bool newEditor = false;
    TextEditor::BaseTextEditor::openEditorAt(fileName, line, column, QString(),
                                             Core::EditorManager::IgnoreNavigationHistory,
                                             &newEditor);
}

void Manager::gotoLocations(const QList<QVariant> &list)
{
    QSet<SymbolLocation> locations = Utils::roleToLocations(list);

    if (locations.count() == 0)
        return;

    QString fileName;
    int line = 0;
    int column = 0;
    bool currentPositionAvailable = false;

    // what is open now?
    Core::IEditor *editor = Core::EditorManager::instance()->currentEditor();
    if (editor) {
        // get current file name
        Core::IFile *file = editor->file();
        if (file)
            fileName = file->fileName();

        // if text file - what is current position?
        TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
        if (textEditor) {
            // there is open currently text editor
            int position = textEditor->position();
            textEditor->convertPosition(position, &line, &column);
            currentPositionAvailable = true;
        }
    }

    // if there is something open - try to check, is it currently activated symbol?
    if (currentPositionAvailable) {
        SymbolLocation current(fileName, line, column);
        QSet<SymbolLocation>::const_iterator it = locations.find(current);
        QSet<SymbolLocation>::const_iterator end = locations.constEnd();
        // is it known location?
        if (it != end) {
            // found - do one additional step
            ++it;
            if (it == end)
                it = locations.begin();
            const SymbolLocation &found = *it;
            gotoLocation(found.fileName(), found.line(), found.column());
            return;
        }
    }

    // no success - open first item in the list
    const SymbolLocation loc = *locations.constBegin();

    gotoLocation(loc.fileName(), loc.line(), loc.column());
}

void Manager::onRequestTreeDataUpdate()
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    emit requestTreeDataUpdate();
}

void Manager::setFlatMode(bool flat)
{
    emit requestSetFlatMode(flat);
}

void Manager::onTreeDataUpdate(QSharedPointer<QStandardItem> result)
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    emit treeDataUpdate(result);
}

} // namespace Internal
} // namespace ClassView
<commit_msg>classview: minor cleanup<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "classviewsymbollocation.h"
#include "classviewmanager.h"
#include "classviewnavigationwidgetfactory.h"
#include "classviewparser.h"
#include "classviewutils.h"

#include <utils/qtcassert.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <texteditor/basetexteditor.h>
#include <cplusplus/ModelManagerInterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <texteditor/itexteditor.h>

#include <QtCore/QThread>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>

namespace ClassView {
namespace Internal {

///////////////////////////////// ManagerPrivate //////////////////////////////////

/*!
   \struct ManagerPrivate
   \brief Private class data for \a Manager
   \sa Manager
 */
struct ManagerPrivate
{
    ManagerPrivate() : state(false) {}

    //! instance
    static Manager *instance;

    //! Pointer to widget factory
    QPointer<NavigationWidgetFactory> widgetFactory;

    //! State mutex
    QMutex mutexState;

    //! Internal manager state. \sa Manager::state
    bool state;

    //! code state/changes parser
    Parser parser;

    //! separate thread for the parser
    QThread parserThread;

    //! there is some massive operation ongoing so temporary we should wait
    bool disableCodeParser;
};

// static variable initialization
Manager *ManagerPrivate::instance = 0;

///////////////////////////////// Manager //////////////////////////////////

Manager::Manager(QObject *parent)
    : QObject(parent),
    d_ptr(new ManagerPrivate())
{
    d_ptr->widgetFactory = NavigationWidgetFactory::instance();

    // register - to be able send between signal/slots
    qRegisterMetaType<QSharedPointer<QStandardItem> >("QSharedPointer<QStandardItem>");

    initialize();

    // start a separate thread for the parser
    d_ptr->parser.moveToThread(&d_ptr->parserThread);
    d_ptr->parserThread.start();

    // initial setup
    onProjectListChanged();
}

Manager::~Manager()
{
    d_ptr->parserThread.quit();
    d_ptr->parserThread.wait();
}

Manager *Manager::instance(QObject *parent)
{
    if (!ManagerPrivate::instance)
        ManagerPrivate::instance = new Manager(parent);
    return ManagerPrivate::instance;
}

bool Manager::canFetchMore(QStandardItem *item) const
{
    return d_ptr->parser.canFetchMore(item);
}

void Manager::fetchMore(QStandardItem *item, bool skipRoot)
{
    d_ptr->parser.fetchMore(item, skipRoot);
}

void Manager::initialize()
{
    // use Qt::QueuedConnection everywhere

    // widget factory signals
    connect(d_ptr->widgetFactory, SIGNAL(widgetIsCreated()),
            SLOT(onWidgetIsCreated()), Qt::QueuedConnection);

    // internal manager state is changed
    connect(this, SIGNAL(stateChanged(bool)), SLOT(onStateChanged(bool)), Qt::QueuedConnection);

    // connections to enable/disable navi widget factory
    ProjectExplorer::SessionManager *sessionManager =
        ProjectExplorer::ProjectExplorerPlugin::instance()->session();
    connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
            SLOT(onProjectListChanged()), Qt::QueuedConnection);
    connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
            SLOT(onProjectListChanged()), Qt::QueuedConnection);

    Core::ICore *core = Core::ICore::instance();

    // connect to the progress manager for signals about Parsing tasks
    connect(core->progressManager(), SIGNAL(taskStarted(QString)),
            SLOT(onTaskStarted(QString)), Qt::QueuedConnection);
    connect(core->progressManager(), SIGNAL(allTasksFinished(QString)),
            SLOT(onAllTasksFinished(QString)), Qt::QueuedConnection);

    // when we signals that really document is updated - sent it to the parser
    connect(this, SIGNAL(requestDocumentUpdated(CPlusPlus::Document::Ptr)),
            &d_ptr->parser, SLOT(parseDocument(CPlusPlus::Document::Ptr)), Qt::QueuedConnection);

    // translate data update from the parser to listeners
    connect(&d_ptr->parser, SIGNAL(treeDataUpdate(QSharedPointer<QStandardItem>)),
            this, SLOT(onTreeDataUpdate(QSharedPointer<QStandardItem>)), Qt::QueuedConnection);

    // requet current state - immediately after a notification
    connect(this, SIGNAL(requestTreeDataUpdate()),
            &d_ptr->parser, SLOT(requestCurrentState()), Qt::QueuedConnection);

    // full reset request to parser
    connect(this, SIGNAL(requestResetCurrentState()),
            &d_ptr->parser, SLOT(resetDataToCurrentState()), Qt::QueuedConnection);

    // clear cache request
    connect(this, SIGNAL(requestClearCache()),
            &d_ptr->parser, SLOT(clearCache()), Qt::QueuedConnection);

    // clear full cache request
    connect(this, SIGNAL(requestClearCacheAll()),
            &d_ptr->parser, SLOT(clearCacheAll()), Qt::QueuedConnection);

    // flat mode request
    connect(this, SIGNAL(requestSetFlatMode(bool)),
            &d_ptr->parser, SLOT(setFlatMode(bool)), Qt::QueuedConnection);

    // connect to the cpp model manager for signals about document updates
    CPlusPlus::CppModelManagerInterface *codeModelManager
        = CPlusPlus::CppModelManagerInterface::instance();

    // when code manager signals that document is updated - handle it by ourselves
    connect(codeModelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
            SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)), Qt::QueuedConnection);
    //
    connect(codeModelManager, SIGNAL(aboutToRemoveFiles(QStringList)),
            &d_ptr->parser, SLOT(removeFiles(QStringList)), Qt::QueuedConnection);
}

bool Manager::state() const
{
    return d_ptr->state;
}

void Manager::setState(bool state)
{
    QMutexLocker locker(&d_ptr->mutexState);

    // boolean comparsion - should be done correctly by any compiler
    if (state == d_ptr->state)
        return;

    d_ptr->state = state;

    emit stateChanged(d_ptr->state);
}

void Manager::onWidgetIsCreated()
{
    // do nothing - continue to sleep
}

void Manager::onWidgetVisibilityIsChanged(bool visibility)
{
    // activate data handling - when 1st time 'Class View' will be open
    if (visibility)
        setState(true);
}

void Manager::onStateChanged(bool state)
{
    if (state) {
        // enabled - request a current snapshots etc?..
        emit requestResetCurrentState();
    } else {
        // disabled - clean parsers internal cache
        emit requestClearCacheAll();
    }
}

void Manager::onProjectListChanged()
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    // update to the latest state
    requestTreeDataUpdate();
}

void Manager::onTaskStarted(const QString &type)
{
    if (type != CppTools::Constants::TASK_INDEX)
        return;

    // disable tree updates to speed up
    d_ptr->disableCodeParser = true;
}

void Manager::onAllTasksFinished(const QString &type)
{
    if (type != CppTools::Constants::TASK_INDEX)
        return;

    // parsing is finished, enable tree updates
    d_ptr->disableCodeParser = false;

    // do nothing if Manager is disabled
    if (!state())
        return;

    // any document might be changed, emit signal to clear cache
    emit requestClearCache();

    // request to update a tree to the current state
    emit requestResetCurrentState();
}

void Manager::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    // do nothing if updates are disabled
    if (d_ptr->disableCodeParser)
        return;

    emit requestDocumentUpdated(doc);
}

void Manager::gotoLocation(const QString &fileName, int line, int column)
{
    bool newEditor = false;
    TextEditor::BaseTextEditor::openEditorAt(fileName, line, column, QString(),
                                             Core::EditorManager::IgnoreNavigationHistory,
                                             &newEditor);
}

void Manager::gotoLocations(const QList<QVariant> &list)
{
    QSet<SymbolLocation> locations = Utils::roleToLocations(list);

    if (locations.count() == 0)
        return;

    QString fileName;
    int line = 0;
    int column = 0;
    bool currentPositionAvailable = false;

    // what is open now?
    Core::IEditor *editor = Core::EditorManager::instance()->currentEditor();
    if (editor) {
        // get current file name
        Core::IFile *file = editor->file();
        if (file)
            fileName = file->fileName();

        // if text file - what is current position?
        TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
        if (textEditor) {
            // there is open currently text editor
            int position = textEditor->position();
            textEditor->convertPosition(position, &line, &column);
            currentPositionAvailable = true;
        }
    }

    // if there is something open - try to check, is it currently activated symbol?
    if (currentPositionAvailable) {
        SymbolLocation current(fileName, line, column);
        QSet<SymbolLocation>::const_iterator it = locations.find(current);
        QSet<SymbolLocation>::const_iterator end = locations.constEnd();
        // is it known location?
        if (it != end) {
            // found - do one additional step
            ++it;
            if (it == end)
                it = locations.begin();
            const SymbolLocation &found = *it;
            gotoLocation(found.fileName(), found.line(), found.column());
            return;
        }
    }

    // no success - open first item in the list
    const SymbolLocation loc = *locations.constBegin();

    gotoLocation(loc.fileName(), loc.line(), loc.column());
}

void Manager::onRequestTreeDataUpdate()
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    emit requestTreeDataUpdate();
}

void Manager::setFlatMode(bool flat)
{
    emit requestSetFlatMode(flat);
}

void Manager::onTreeDataUpdate(QSharedPointer<QStandardItem> result)
{
    // do nothing if Manager is disabled
    if (!state())
        return;

    emit treeDataUpdate(result);
}

} // namespace Internal
} // namespace ClassView
<|endoftext|>