text:
/**
 * @file hpt_test.cpp
 *
 * Tests for the hyper-parameter tuning module.
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */

#include <mlpack/core/cv/metrics/mse.hpp>
#include <mlpack/core/cv/metrics/accuracy.hpp>
#include <mlpack/core/cv/simple_cv.hpp>
#include <mlpack/core/hpt/cv_function.hpp>
#include <mlpack/core/hpt/fixed.hpp>
#include <mlpack/core/hpt/hpt.hpp>
#include <mlpack/core/optimizers/grid_search/grid_search.hpp>
#include <mlpack/core/optimizers/gradient_descent/gradient_descent.cpp>
#include <mlpack/methods/lars/lars.hpp>
#include <mlpack/methods/logistic_regression/logistic_regression.hpp>

#include <boost/test/unit_test.hpp>

using namespace mlpack::cv;
using namespace mlpack::data;
using namespace mlpack::hpt;
using namespace mlpack::optimization;
using namespace mlpack::regression;

BOOST_AUTO_TEST_SUITE(HPTTest);

/**
 * Test CVFunction runs cross-validation in according with specified fixed
 * arguments and passed parameters.
 */
BOOST_AUTO_TEST_CASE(CVFunctionTest)
{
  arma::mat xs = arma::randn(5, 100);
  arma::vec beta = arma::randn(5, 1);
  arma::rowvec ys = beta.t() * xs + 0.1 * arma::randn(1, 100);

  SimpleCV<LARS, MSE> cv(0.2, xs, ys);

  bool transposeData = true;
  bool useCholesky = false;
  double lambda1 = 1.0;
  double lambda2 = 2.0;

  FixedArg<bool, 1> fixedUseCholesky{useCholesky};
  FixedArg<double, 3> fixedLambda1{lambda2};
  CVFunction<decltype(cv), LARS, 4, FixedArg<bool, 1>, FixedArg<double, 3>>
      cvFun(cv, 0.0, 0.0, fixedUseCholesky, fixedLambda1);

  double expected = cv.Evaluate(transposeData, useCholesky, lambda1, lambda2);
  arma::vec parameters(2);
  parameters(0) = transposeData;
  parameters(1) = lambda1;
  double actual = cvFun.Evaluate(parameters);

  BOOST_REQUIRE_CLOSE(expected, actual, 1e-5);
}

/**
 * This class provides the interface of CV classes, but really implements a
 * simple quadratic function of three variables.
 */
template<typename MLAlgorithm,
         typename Metric = void,
         typename MatType = void,
         typename PredictionsType = void,
         typename WeightsType = void>
class QuadraticFunction
{
 public:
  QuadraticFunction(double a,
                    double b,
                    double c,
                    double d,
                    double xMin = 0.0,
                    double yMin = 0.0,
                    double zMin = 0.0) :
      a(a), b(b), c(c), d(d), xMin(xMin), yMin(yMin), zMin(zMin) {}

  double Evaluate(double x, double y, double z)
  {
    return a * pow(x - xMin, 2)  + b * pow(y - yMin, 2) + c * pow(z - zMin, 2)
        + d;
  }

  // Declaring and defining it just in order to provide the same interface as
  // other CV classes.
  MLAlgorithm Model()
  {
    return MLAlgorithm();
  }

 private:
  double a, b, c, d, xMin, yMin, zMin;
};

/**
 * Test CVFunction approximates gradient in the expected way.
 */
BOOST_AUTO_TEST_CASE(CVFunctionGradientTest)
{
  double a = 1.0;
  double b = -1.5;
  double c = 2.5;
  double d = 3.0;
  QuadraticFunction<LARS> lf(a, b, c, d);

  double relativeDelta = 0.01;
  double minDelta = 0.001;
  CVFunction<decltype(lf), LARS, 3> cvFun(lf, relativeDelta, minDelta);

  double x = 0.0;
  double y = -1.0;
  double z = 2.0;
  arma::mat gradient;
  cvFun.Gradient(arma::vec("0.0 -1.0 2.0"), gradient);

  double xDelta = minDelta;
  double yDelta = relativeDelta * abs(y);
  double zDelta = relativeDelta * abs(z);

  double aproximateXPartialDerivative = a * (2 * x + xDelta);
  double aproximateYPartialDerivative = b * (2 * y + yDelta);
  double aproximateZPartialDerivative = c * (2 * z + zDelta);

  BOOST_REQUIRE_EQUAL(gradient.n_elem, 3);
  BOOST_REQUIRE_CLOSE(gradient(0), aproximateXPartialDerivative, 1e-5);
  BOOST_REQUIRE_CLOSE(gradient(1), aproximateYPartialDerivative, 1e-5);
  BOOST_REQUIRE_CLOSE(gradient(2), aproximateZPartialDerivative, 1e-5);
}

void InitProneToOverfittingData(arma::mat& xs,
                                arma::rowvec& ys,
                                double& validationSize)
{
  // Total number of data points.
  size_t N = 10;
  // Total number of features (all except the first one are redundant).
  size_t M = 5;

  arma::rowvec data = arma::linspace<arma::rowvec>(0.0, 10.0, N);
  xs = data;
  for (size_t i = 2; i <= M; ++i)
    xs = arma::join_cols(xs, arma::pow(data, i));

  // Responses that approximately follow the function y = 2 * x. Adding noise to
  // avoid having a polynomial of degree 1 that exactly fits the points.
  ys = 2 * data + 0.05 * arma::randn(1, N);

  validationSize = 0.3;
}

template<typename T1, typename T2>
void FindLARSBestLambdas(arma::mat& xs,
                         arma::rowvec& ys,
                         double& validationSize,
                         bool transposeData,
                         bool useCholesky,
                         const T1& lambda1Set,
                         const T2& lambda2Set,
                         double& bestLambda1,
                         double& bestLambda2,
                         double& bestObjective)
{
  SimpleCV<LARS, MSE> cv(validationSize, xs, ys);

  bestObjective = std::numeric_limits<double>::max();

  for (double lambda1 : lambda1Set)
    for (double lambda2 : lambda2Set)
    {
      double objective =
          cv.Evaluate(transposeData, useCholesky, lambda1, lambda2);
      if (objective < bestObjective)
      {
        bestObjective = objective;
        bestLambda1 = lambda1;
        bestLambda2 = lambda2;
      }
    }
}

 /**
 * Test grid-search optimization leads to the best parameters from the specified
 * ones.
 */
BOOST_AUTO_TEST_CASE(GridSearchTest)
{
  arma::mat xs;
  arma::rowvec ys;
  double validationSize;
  InitProneToOverfittingData(xs, ys, validationSize);

  bool transposeData = true;
  bool useCholesky = false;
  arma::vec lambda1Set("0 0.001 0.01 0.1 1.0 10.0 100.0");
  std::array<double, 4> lambda2Set{{0.0, 0.05, 0.5, 5.0}};

  double expectedLambda1, expectedLambda2, expectedObjective;
  FindLARSBestLambdas(xs, ys, validationSize, transposeData, useCholesky,
      lambda1Set, lambda2Set, expectedLambda1, expectedLambda2,
      expectedObjective);

  SimpleCV<LARS, MSE> cv(validationSize, xs, ys);
  CVFunction<decltype(cv), LARS, 4, FixedArg<bool, 0>, FixedArg<bool, 1>>
      cvFun(cv, 0.0, 0.0, {transposeData}, {useCholesky});

  IncrementPolicy policy(true);
  DatasetMapper<IncrementPolicy, double> datasetInfo(policy, 2);
  for (double lambda1 : lambda1Set)
    datasetInfo.MapString<size_t>(lambda1, 0);
  for (double lambda2 : lambda2Set)
    datasetInfo.MapString<size_t>(lambda2, 1);

  GridSearch optimizer;
  arma::mat actualParameters;
  double actualObjective =
      optimizer.Optimize(cvFun, actualParameters, datasetInfo);

  BOOST_REQUIRE_CLOSE(expectedObjective, actualObjective, 1e-5);
  BOOST_REQUIRE_CLOSE(expectedLambda1, actualParameters(0, 0), 1e-5);
  BOOST_REQUIRE_CLOSE(expectedLambda2, actualParameters(1, 0), 1e-5);
}

/**
 * Test HyperParameterTuner.
 */
BOOST_AUTO_TEST_CASE(HPTTest)
{
  arma::mat xs;
  arma::rowvec ys;
  double validationSize;
  InitProneToOverfittingData(xs, ys, validationSize);

  bool transposeData = true;
  bool useCholesky = false;
  arma::vec lambda1Set("0 0.001 0.01 0.1 1.0 10.0 100.0");
  arma::vec lambda2Set("0.0 0.05 0.5 5.0");

  double expectedLambda1, expectedLambda2, expectedObjective;
  FindLARSBestLambdas(xs, ys, validationSize, transposeData, useCholesky,
      lambda1Set, lambda2Set, expectedLambda1, expectedLambda2,
      expectedObjective);

  double actualLambda1, actualLambda2;
  HyperParameterTuner<LARS, MSE, SimpleCV, GridSearch>
      hpt(validationSize, xs, ys);
  std::tie(actualLambda1, actualLambda2) = hpt.Optimize(Fixed(transposeData),
      Fixed(useCholesky), lambda1Set, lambda2Set);

  BOOST_REQUIRE_CLOSE(expectedObjective, hpt.BestObjective(), 1e-5);
  BOOST_REQUIRE_CLOSE(expectedLambda1, actualLambda1, 1e-5);
  BOOST_REQUIRE_CLOSE(expectedLambda2, actualLambda2, 1e-5);

  /* Checking that the model provided by the hyper-parameter tuner shows the
   * same performance. */
  size_t validationFirstColumn = round(xs.n_cols * (1.0 - validationSize));
  arma::mat validationXs = xs.cols(validationFirstColumn, xs.n_cols - 1);
  arma::rowvec validationYs = ys.cols(validationFirstColumn, ys.n_cols - 1);
  double objective = MSE::Evaluate(hpt.BestModel(), validationXs, validationYs);
  BOOST_REQUIRE_CLOSE(expectedObjective, objective, 1e-5);
}

/**
 * Test HyperParamterTuner maximizes Accuracy rather than minimizes it.
 */
BOOST_AUTO_TEST_CASE(HPTMaximizationTest)
{
  // Initializing a linearly separable dataset.
  arma::mat xs = arma::linspace<arma::rowvec>(0.0, 10.0, 50);
  arma::Row<size_t> ys = arma::join_rows(arma::zeros<arma::Row<size_t>>(25),
      arma::ones<arma::Row<size_t>>(25));

  // We will train and validate on the same dataset.
  double validationSize = 0.5;
  arma::mat doubledXs = arma::join_rows(xs, xs);
  arma::Row<size_t> doubledYs = arma::join_rows(ys, ys);

  // Defining lambdas to choose from. Zero should be preferred since big lambdas
  // are likely to restrict capabilities of logistic regression.
  arma::vec lambdas("0 1e12");

  // Making sure that the assumption above is true.
  SimpleCV<LogisticRegression<>, Accuracy>
      cv(validationSize, doubledXs, doubledYs);
  BOOST_REQUIRE_GT(cv.Evaluate(0.0), cv.Evaluate(1e12));

  HyperParameterTuner<LogisticRegression<>, Accuracy, SimpleCV>
      hpt(validationSize, doubledXs, doubledYs);

  double actualLambda;
  std::tie(actualLambda) = hpt.Optimize(lambdas);

  BOOST_REQUIRE_CLOSE(hpt.BestObjective(), 1.0, 1e-5);
  BOOST_REQUIRE_CLOSE(actualLambda, 0.0, 1e-5);
}

/**
 * Test HyperParameterTuner works with GradientDescent.
 */
BOOST_AUTO_TEST_CASE(HPTGradientDescentTest)
{
  // Constructor arguments for the fake CV function (QuadraticFunction).
  double a = 1.0;
  double b = -1.5;
  double c = 2.5;
  double d = 3.0;

  // Optimal values for three "hyper-parameters".
  double xMin = 1.5;
  double yMin = 0.0;
  double zMin = -2.0;

  // We pass LARS just because some ML algorithm should be passed. We pass MSE
  // to tell HyperParameterTuner that the objective function (QuadraticFunction)
  // should be minimized.
  HyperParameterTuner<LARS, MSE, QuadraticFunction, GradientDescent>
      hpt(a, b, c, d, xMin, yMin, zMin);

  // Setting GradientDescent to find more close solution to the optimal one.
  hpt.Optimizer().StepSize() = 0.1;
  hpt.Optimizer().Tolerance() = 1e-15;

  // Always using the same small increase of arguments in calculation of partial
  // derivatives.
  hpt.RelativeDelta() = 0.0;
  hpt.MinDelta() = 1e-10;

  // We will try to find optimal values only for two "hyper-parameters".
  double x0 = 3.0;
  double y = yMin;
  double z0 = -3.0;

  double xOptimized, zOptimized;
  std::tie(xOptimized, zOptimized) = hpt.Optimize(x0, Fixed(y), z0);
  BOOST_REQUIRE_CLOSE(xOptimized, xMin, 1e-4);
  BOOST_REQUIRE_CLOSE(zOptimized, zMin, 1e-4);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: chigur/mlpack

max_issues_repo_name: chigur/mlpack

max_forks_repo_name: chigur/mlpack


text:
#include <iostream>
#include <cassert>
#include <random>
#include <tuple>
#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <thread>

#include <boost/timer.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <apr_mmap.h>
#include <apr_general.h>

#include "akumuli.h"

using namespace std;

const int DB_SIZE = 3;
const int NUM_ITERATIONS = 100*1000*1000;

const char* DB_NAME = "test";
const char* DB_PATH = "./test";
const char* DB_META_FILE = "./test/test.akumuli";

uint64_t reader_n_busy = 0ul;

void delete_storage() {
    boost::filesystem::remove_all(DB_PATH);
}

void print_storage_stats(aku_StorageStats& ss) {
    std::cout << ss.n_entries << " elements in" << std::endl
              << ss.n_volumes << " volumes with" << std::endl
              << ss.used_space << " bytes used and" << std::endl
              << ss.free_space << " bytes free" << std::endl;
}

void print_search_stats(aku_SearchStats& ss) {
    std::cout << "Interpolation search" << std::endl;
    std::cout << ss.istats.n_matches << " matches" << std::endl
              << ss.istats.n_times << " times" << std::endl
              << ss.istats.n_steps << " steps" << std::endl
              << ss.istats.n_overshoots << " overshoots" << std::endl
              << ss.istats.n_undershoots << " undershoots" << std::endl
              << ss.istats.n_reduced_to_one_page << "  reduced to page" << std::endl

              << ss.istats.n_page_in_core_checks << "  page_in_core checks" << std::endl
              << ss.istats.n_page_in_core_errors << "  page_in_core errors" << std::endl
              << ss.istats.n_pages_in_core_found  << "  page_in_core success" << std::endl
              << ss.istats.n_pages_in_core_miss  << "  page_in_core miss" << std::endl;

    std::cout << "Binary search" << std::endl;
    std::cout << ss.bstats.n_steps << " steps" << std::endl
              << ss.bstats.n_times << " times" << std::endl;

    std::cout << "Scan" << std::endl;
    std::cout << ss.scan.bwd_bytes << " bytes read in backward direction" << std::endl
              << ss.scan.fwd_bytes << " bytes read in forward direction" << std::endl;
}

int format_timestamp(uint64_t ts, char* buffer) {
    auto fractional = static_cast<int>(ts %  1000000000);  // up to 9 decimal digits
    auto seconds = static_cast<int>(ts / 1000000000);      // two seconds digits
    return sprintf(buffer, "20150102T0304%02d.%09d", seconds, fractional);
}

std::string ts2str(uint64_t ts) {
    char buffer[0x100];
    auto len = format_timestamp(ts, buffer);
    return std::string(buffer, buffer+len);
}

std::string build_query(uint64_t begin, uint64_t end) {
    std::stringstream str;
    str << R"({ "sample": "all", )";
    str << R"("range": { "from": ")" << ts2str(begin)
        << R"(", "to": ")" << ts2str(end)
        << R"("}})";
    return str.str();
}

aku_Timestamp query_database_backward(aku_Database* db, aku_Timestamp begin, aku_Timestamp end, uint64_t& counter, boost::timer& timer, uint64_t mod) {
    const int NUM_ELEMENTS = 1000;
    std::string query = build_query(begin, end);
    aku_Cursor* cursor = aku_query(db, query.c_str());
    aku_Timestamp current_time = end;
    aku_Timestamp last = begin;
    bool last_initialized = false;
    while(!aku_cursor_is_done(cursor)) {
        aku_Status err = AKU_SUCCESS;
        if (aku_cursor_is_error(cursor, &err)) {
            aku_cursor_close(cursor);
            if (err == AKU_EBUSY) { // OK
                reader_n_busy++;
                return last;
            } else {                           // Critical
                std::cout << aku_error_message(err) << std::endl;
                throw std::runtime_error(aku_error_message(err));
            }
        }
        aku_Sample samples[NUM_ELEMENTS];
        int n_entries = aku_cursor_read(cursor, samples, NUM_ELEMENTS);
        for (int i = 0; i < n_entries; i++) {
            if (last_initialized) {
                if (samples[i].timestamp != current_time) {
                    std::cout << "(BW) Bad ts at " << current_time << " expected " << current_time
                              << " acutal " << samples[i].timestamp << std::endl;
                    aku_cursor_close(cursor);
                    return last;
                }
                if (samples[i].paramid != 42) {
                    std::cout << "(BW) Bad id at " << current_time << " expected " << 42
                              << " acutal " << samples[i].paramid << std::endl;
                    aku_cursor_close(cursor);
                    return last;

                }
            }
            if (!last_initialized) {
                last = samples[i].timestamp;
                current_time = last;
                last_initialized = true;
            }
            current_time--;
            counter++;
            if (counter % mod == 0) {
                std::cout << counter << "..." << timer.elapsed() << "s (bw)" << std::endl;
                timer.restart();
            }
        }
    }
    aku_cursor_close(cursor);
    return last;
}

aku_Timestamp query_database_forward(aku_Database* db, aku_Timestamp begin, aku_Timestamp end, uint64_t& counter, boost::timer& timer, uint64_t mod) {
    const int NUM_ELEMENTS = 1000;
    std::string query = build_query(end, begin);
    aku_Cursor* cursor = aku_query(db, query.c_str());
    aku_Timestamp current_time = begin;
    aku_Timestamp last = begin;
    while(!aku_cursor_is_done(cursor)) {
        aku_Status err = AKU_SUCCESS;
        if (aku_cursor_is_error(cursor, &err)) {
            aku_cursor_close(cursor);
            if (err == AKU_EBUSY) { // OK
                reader_n_busy++;
                return last;
            } else {                           // Critical
                std::cout << aku_error_message(err) << std::endl;
                throw std::runtime_error(aku_error_message(err));
            }
        }
        aku_Sample samples[NUM_ELEMENTS];
        int n_entries = aku_cursor_read(cursor, samples, NUM_ELEMENTS);
        for (int i = 0; i < n_entries; i++) {
            if (samples[i].timestamp != current_time) {
                std::cout << "(FW) Bad ts at " << current_time << " expected " << current_time
                          << " acutal " << samples[i].timestamp << std::endl;
                aku_cursor_close(cursor);
                return last;
            }
            if (samples[i].paramid != 42) {
                std::cout << "(FW) Bad id at " << current_time << " expected " << 42
                          << " acutal " << samples[i].paramid << std::endl;
                aku_cursor_close(cursor);
                return last;

            }
            current_time++;
            last = samples[i].timestamp;
            counter++;
            if (counter % mod == 0) {
                std::cout << counter << "..." << timer.elapsed() << "s (fw)" << std::endl;
                timer.restart();
            }
        }
    }
    aku_cursor_close(cursor);
    return last;
}

int main(int cnt, const char** args)
{
    aku_initialize(nullptr);

    // Cleanup
    delete_storage();

    // Create database
    apr_status_t result = aku_create_database(DB_NAME, DB_PATH, DB_PATH, DB_SIZE, nullptr);
    if (result != APR_SUCCESS) {
        std::cout << "Error in new_storage" << std::endl;
        return (int)result;
    }

    aku_FineTuneParams params = {};
    params.debug_mode = 0;
    auto db = aku_open_database(DB_META_FILE, params);
    boost::timer timer;

    auto reader_fn_bw = [&db]() {
        boost::timer timer;
        aku_Timestamp top = 0u;
        uint64_t counter = 0;
        uint64_t query_counter = 0;
        // query last elements from database
        while (true) {
            top = query_database_backward(db, top, AKU_MAX_TIMESTAMP, counter, timer, 1000000);
            query_counter++;
            if (top == NUM_ITERATIONS - 1) {
                std::cout << "query_counter=" << query_counter << std::endl;
                break;
            }
        }
    };

    auto reader_fn_fw = [&db]() {
        boost::timer timer;
        aku_Timestamp top = 0u;
        uint64_t counter = 0;
        uint64_t query_counter = 0;
        // query last elements from database
        while (true) {
            top = query_database_forward(db, top, AKU_MAX_TIMESTAMP, counter, timer, 1000000);
            query_counter++;
            if (top >= (NUM_ITERATIONS - 20001)) {
                std::cout << "query_counter=" << query_counter << std::endl;
                break;
            }
        }
    };

    std::thread fw_reader_thread(reader_fn_fw);
    std::thread bw_reader_thread(reader_fn_bw);

    int writer_n_busy = 0;
    for(uint64_t ts = 0; ts < NUM_ITERATIONS; ts++) {
        uint64_t k = ts + 2;
        double value = 0.0001*k;
        aku_ParamId id = ts & 0xF;
        aku_Status status = aku_write_double_raw(db, id, ts, value);
        if (status == AKU_SUCCESS) {
            if (ts % 1000000 == 0) {
                std::cout << ts << "---" << timer.elapsed() << "s" << std::endl;
                timer.restart();
            }
        } else if (status == AKU_EBUSY) {
            writer_n_busy++;
            status = aku_write_double_raw(db, id, ts, value);
        }
        if (status != AKU_SUCCESS) {
            std::cout << "aku_add_sample error " << aku_error_message(status) << std::endl;
            break;
        }
    }
    std::cout << "Writer busy count = " << writer_n_busy << std::endl;

    fw_reader_thread.join();
    bw_reader_thread.join();

    std::cout << "Reader busy count = " << reader_n_busy << std::endl;

    aku_SearchStats search_stats;

    aku_global_search_stats(&search_stats, true);
    print_search_stats(search_stats);

    aku_close_database(db);

    delete_storage();

    return 0;
}

ext: cpp

max_stars_repo_name: vladon/Akumuli

max_issues_repo_name: vladon/Akumuli

max_forks_repo_name: vladon/Akumuli


text:
#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include "stock.h"
#include "perf.h"
#include "seispp.h"
#include "LatLong-UTMconversion.h"
#include "StreamObjectWriter.h"
/* This could be in an include, but will insert this prototype here
   rather than make an include file with one line.*/
TimeSeries ReadSegyTrace(FILE *,bool load_coordinates);

void usage()
{
    cerr << "SU3CEnsembleConverter outfile [--help -pf pffile] < SUfile "<<endl
        << "Translates one ensemble of 3C data in SU format"<<endl
        << "to a SEISPP ThreeComponentEnsemble saved as a binary StreamObject file "
        <<endl
        << " SU data comes through stdin - normally pipeline with an suwind filer"
        <<endl
        << " Input assumed to be 3c channel triplets (1,2,3=sensor 1, 4,5,6=sensor 2, etc.)"
        <<endl;
    exit(-1);
}
/* This is defined in SU's par.h and seems necessary for this to link.
      Not used in this code, but an annoying extern.   This is
      an incredibly obscure trick to make this work.  Found by
     pure hacking
*/
extern "C"{
int xargc;
char **xargv;
}
/* DEBUG routine */
/*
void print_tmatrix(ThreeComponentSeismogram d)
{
    int i,j;
    for(i=0;i<3;++i)
    {
        for(j=0;j<3;++j)
            cout << d.tmatrix[i][j]<<" ";
        cout <<endl;
    }
    if(d.components_are_orthogonal)
        cout << "components_are_orthogonal is set true"<<endl;
    else
        cout << "components_are_orthogonal is set false"<<endl;
    if(d.components_are_cardinal)
        cout << "components_are_cardinal is set true"<<endl;
    else
        cout << "components_are_cardinal is set false"<<endl;
}
*/
bool SEISPP::SEISPP_verbose(true);
int main(int argc, char **argv)
{
    if(argc<2)usage();
    xargc=argc;
    xargv=argv;
    string outfile(argv[1]);
    if(outfile=="--help") usage();
    string pffile("SU3CEnsembleConverter");
    int i,j;
    for(i=2;i<argc;++i)
    {
        string sarg(argv[i]);
        if(sarg=="-pf")
        {
            ++i;
            if(i>=argc) usage();
            pffile=string(argv[i]);
        }
        else
            usage();
    }
    Pf *pf;
    if(pfread(const_cast<char*>(pffile.c_str()),&pf))
    {
        cerr << "pfread failed on pffile="<<pffile<<endl;
        usage();
    }
    try{
        /* seispp stream file creation */
        StreamObjectWriter<ThreeComponentEnsemble> oa(outfile,'b');
        /* Now build all the list of metadata to be loaded */
        MetadataList tmdl=pfget_mdlist(pf,"trace_metadata_list");
        Metadata control(pf);
        bool apply_spreading_correction=control.get_bool("correct_for_geometric_spreading");
        double spow(0.0);
        if(apply_spreading_correction)
        {
            spow=control.get_double("spreading_power_factor");
            cout << "Applying geometric spreading correction using "
                << "offset^"<<spow<<endl;
        }
        bool apply_rotation=control.get_bool("apply_rotation");
        double rotation_angle(0.0);
        if(apply_rotation)
        {
            rotation_angle=control.get_double("rotation_angle");
            /* All angles in my library are radians but input is degrees*/
            cout << "Horizontal components will be rotated by phi="<<rotation_angle<<endl;
            rotation_angle=rad(rotation_angle);
        }
        bool convert_utm=control.get_bool("convert_utm_to_dd");
        string zone;  //utm zone when needed
        int RefEl(23);   //frozen as WGS-84
        if(convert_utm)
        {
            zone=control.get_string("UTM_zone");
            cout << "UTM conversion will be done with zone="<<zone<<endl;
        }
        else
            cout << "Warning:  utm conversion is off."<<endl
                << "Using the result in ParticleMotionVTKconverter will fail"<<endl;
        /* This is a crude way to define the hang,vang orientation data. Works
        only for homestake data where all sensors had a common orientation */
        Tbl *t;
        t=pfget_tbl(pf,const_cast<char *>("channel_orientation"));
        if(t==NULL)
        {
            cerr << "Missing required Tbl parameter channel_orientation"<<endl;
            usage();
        }
        if(maxtbl(t)!=3)
        {
            cerr << "channel_orientation Tbl parameter in pf file is incorrectly defined"
                <<endl << "Size must be 3.   Size found="<<maxtbl(t)<<endl;
            exit(-1);
        }
        double hang[3],vang[3];   // parallel arrays
        long int ii;
        for(ii=0;ii<3;++ii)
        {
            char *line;
            line=(char *)gettbl(t,ii);
            sscanf(line,"%d%lf%lf",&i,hang+ii,vang+ii);
            if(i!=ii)
            {
                cerr << "Format error for channel_orientation data"<<endl
                    << "Must be listed in ascending channel order (0,1,2)"<<endl
                    << "Read index "<<i<<" when expecting "<<ii<<endl;
                exit(-1);
            }
            cout << "Component "<<ii<<" Setting hang="<<hang[ii]<< " and vang="
                <<vang[ii]<<endl;
        }

        /* This will hold our results */
        ThreeComponentEnsemble ens;
        cout << "SU3CEnsembleConverter processing begins - reading from stdin"<<endl;
        /* Now load the data file until EOF.  This is not general
           but assumes this program will always follow a suwind
           command to build the ensemble.  The logic of this
           read loop is a bit perverted because of the read procedure
           interface to SU was designed to return a TimeSeries object.
           */
        bool readok;
        bool load_coordinates=control.get_bool("load_coordinates");
        TimeSeries dread=ReadSegyTrace(stdin,load_coordinates);
        if(dread.ns<=0)
        {
            cerr << "No data to process.   ReadSegyTrace hit EOF immediately"
                <<endl;
            exit(-1);
        }
        else
            readok=true;
        int n;   // counter for number of traces read - sanity check
        int k;   // mod 3 to get channel code
        /* This holds channels to build 3c objects.  STL container
        has to be initialized like this to allow use of indexing
        operator */
        vector<TimeSeries> channels;
        for(n=0;n<3;++n) channels.push_back(TimeSeries());
        n=0;  k=0;
        while(readok)
        {
            double dcoord;
            int icoord;
            dread.put("hang",hang[k]);
            dread.put("vang",vang[k]);
            channels[k]=dread;
            if(k==2)
            {
                ThreeComponentSeismogram d3c(channels,0);
                //cout << "Transformation matrix from constructor"<<endl;
                //print_tmatrix(d3c);
                d3c.rotate_to_standard();
                //cout << "Transformation matrix after rotate_to_standard"<<endl;
                //print_tmatrix(d3c);
                if(apply_rotation)
                    d3c.rotate(rotation_angle);
                if(convert_utm)
                {
                    double easting,northing;
                    easting=d3c.get_double("rx");
                    northing=d3c.get_double("ry");
                    double lat,lon;
                    /* This library routine returns lat,lon in degrees.
                       We post that to header as css names to mate
                       with ParticleMotionVTKconverter.  */
                    UTMtoLL(RefEl,northing,easting,zone.c_str(),lat,lon);
                    d3c.put("site.lat",lat);
                    d3c.put("site.lon",lon);
                }
                if(apply_spreading_correction)
                {
                    double offset=d3c.get_double("offset");
                    offset=fabs(offset);
                    /* Test for small offset - unit dependent assumes
                       offset in m */
                    if(offset>0.01)
                    {
                        double scale=pow(offset,spow);
                        dscal(3*d3c.ns,scale,d3c.u.get_address(0,0),1);
                    }
                }
                ens.member.push_back(d3c);
            }
            dread=ReadSegyTrace(stdin,load_coordinates);
            if(dread.ns<=0) readok=false;
            ++n;
            k=n%3;
        }
        cout << "Finished bundling 3C ensemble with "<<ens.member.size()
            << " 3C objects"<<endl
        << "Writing to seispp file "<<outfile<<endl;
        /* Now we save the result to outfile */
        oa.write(ens);
    }catch(SeisppError& serr)
    {
        serr.log_error();
    }
}

ext: cc


text:
#include "Lib/spin_system.h"
#include "Lib/log_trace.h"
#include "Lib/simulate.h"
#include "Lib/grid.h"
#include "Lib/constants.h"
#include "Lib/load_parameters.h"

#include <omp.h>

#include <iostream>
#include <filesystem>
#include <unsupported/Eigen/MatrixFunctions>
#include <Eigen/Eigenvalues>
#include <vector>
#include <fstream>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/ref.hpp>

namespace fs = std::experimental::filesystem;

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

	try {
		if (argc < 4)
		{
			throw std::runtime_error("Not enough arguments given");
		}
	}
	catch (std::runtime_error &er) {
		std::cout << er.what() << "\n";
	}

	std::vector<double> phi;
	std::vector<double> theta;
	std::vector<double> weights;

	std::vector<double> B;
	double t_step;

	Spin_System_Doublet spin_time;
	Spin_System_Doublet spin_pulse;
	std::vector<double> t;
	auto temp = boost::make_tuple(boost::ref(spin_time), boost::ref(spin_pulse), boost::ref(t_step), boost::ref(B), boost::ref(t));
	temp=load_parameters_doublet(argv[1]);

	auto temp2 = boost::make_tuple(boost::ref(phi), boost::ref(theta), boost::ref(weights));
	temp2 = grid(argv[3],spin_time.symmetrie, spin_time.knots);

	double const t0 = t[0];
	double const t1 = t[1];
	double const t2 = t[2];
	double const t3 = t[3];
	double const t4 = t[4];
	double const t5 = t[5];

	Log_stream log_stream (argv[2], "integral", t_step);

	for (auto B_temp : B) {

		spin_time.change_B(B_temp);
		spin_pulse.change_B(B_temp);

		Spin_System_Doublet::operator_type rho_eq = spin_time.get_rho_equ();
		Spin_System_Doublet::operator_type rho;

		log_stream.save_x(B_temp);

		for (int i = 0; i < phi.size(); ++i) {

			std::vector<double> angles = { 0,theta[i],phi[i],weights[i] };
			rho = simulate(spin_pulse, t0, t1, angles, rho_eq, Log_trace_none{});
			rho = simulate(spin_time, t1, t2, angles, rho, Log_trace_none{});
			rho = simulate(spin_pulse, t2, t3, angles, rho, Log_trace_none{});
			rho = simulate(spin_time, t3, t4, angles, rho, Log_trace_none{});
			rho = simulate(spin_time, t4, t5, angles, rho, log_stream);
		}

		log_stream.next();

	}

	log_stream.save_data();

}


text:
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "WorkspacePanel.h"

#include <boost/bind.hpp>

#include <wx/bitmap.h>
#include <wx/button.h>
#include <wx/imaglist.h>
#include <wx/menu.h>
#include <wx/sizer.h>
#include <wx/aui/auibook.h>

#include "OgreMaterial.h"
#include "OgreMaterialManager.h"
#include "OgreMaterialSerializer.h"
#include "OgrePass.h"
#include "OgreTechnique.h"

#include "EditorManager.h"
#include "EventArgs.h"
#include "IconManager.h"
#include "MaterialController.h"
#include "MaterialEventArgs.h"
#include "MaterialScriptEditor.h"
#include "MaterialWizard.h"
#include "PassController.h"
#include "PassWizard.h"
#include "Project.h"
#include "ProjectEventArgs.h"
#include "ProjectWizard.h"
#include "SelectionService.h"
#include "TechniqueController.h"
#include "TechniqueEventArgs.h"
#include "TechniqueWizard.h"
#include "Workspace.h"
#include "WorkspaceEventArgs.h"

#define WORKSPACE_IMAGE 0
#define PROJECT_IMAGE 1
#define MATERIAL_SCRIPT_IMAGE 2
#define MATERIAL_IMAGE 3
#define TECHNIQUE_IMAGE 4
#define PASS_IMAGE 5

namespace
{
	class Ogre::MaterialSerializer;
}

const long ID_TREE_CTRL = wxNewId();
const long ID_MENU_NEW = wxNewId();
const long ID_MENU_NEW_PROJECT = wxNewId();
const long ID_MENU_NEW_MATERIAL_SCRIPT = wxNewId();
const long ID_MENU_NEW_MATERIAL = wxNewId();
const long ID_MENU_NEW_TECHNIQUE = wxNewId();
const long ID_MENU_NEW_PASS = wxNewId();
const long ID_MENU_ADD_MATERIAL = wxNewId();
const long ID_MENU_EDIT = wxNewId();
const long ID_MENU_PASS_ENABLED = wxNewId();
const long ID_MENU_DELETE = wxNewId();

BEGIN_EVENT_TABLE(WorkspacePanel, wxPanel)
	EVT_TREE_ITEM_RIGHT_CLICK(ID_TREE_CTRL, WorkspacePanel::OnRightClick)
	EVT_TREE_ITEM_ACTIVATED(ID_TREE_CTRL, WorkspacePanel::OnActivate)
	EVT_TREE_SEL_CHANGED(ID_TREE_CTRL, WorkspacePanel::OnSelectionChanged)
	EVT_MENU(ID_MENU_NEW_PROJECT, WorkspacePanel::OnNewProject)
	EVT_MENU(ID_MENU_NEW_MATERIAL_SCRIPT, WorkspacePanel::OnNewMaterialScript)
	EVT_MENU(ID_MENU_NEW_MATERIAL, WorkspacePanel::OnNewMaterial)
	EVT_MENU(ID_MENU_NEW_TECHNIQUE, WorkspacePanel::OnNewTechnique)
	EVT_MENU(ID_MENU_NEW_PASS, WorkspacePanel::OnNewPass)
	EVT_MENU(ID_MENU_ADD_MATERIAL, WorkspacePanel::OnAddMaterial)
	EVT_MENU(ID_MENU_EDIT, WorkspacePanel::OnEdit)
	EVT_UPDATE_UI(ID_MENU_NEW_MATERIAL, WorkspacePanel::OnUpdateMaterialMenuItem)
	EVT_UPDATE_UI(ID_MENU_NEW_TECHNIQUE, WorkspacePanel::OnUpdateTechniqueMenuItem)
	EVT_UPDATE_UI(ID_MENU_NEW_PASS, WorkspacePanel::OnUpdatePassMenuItem)
END_EVENT_TABLE()

WorkspacePanel::WorkspacePanel(wxWindow* parent,
			   wxWindowID id /* = wxID_ANY */,
			   const wxPoint& pos /* = wxDefaultPosition */,
			   const wxSize& size /* = wxDefaultSize */,
			   long style /* = wxTAB_TRAVERSAL | wxNO_BORDER */,
			   const wxString& name /* = wxT("Workspace Panel")) */)
			   : mImageList(NULL), wxPanel(parent, id, pos, size, style, name)
{
	createPanel();

	Workspace::getSingletonPtr()->subscribe(Workspace::ProjectAdded, boost::bind(&WorkspacePanel::projectAdded, this, _1));
	Workspace::getSingletonPtr()->subscribe(Workspace::ProjectRemoved, boost::bind(&WorkspacePanel::projectRemoved, this, _1));
}

WorkspacePanel::~WorkspacePanel()
{
}

void WorkspacePanel::createPanel()
{
	mSizer = new wxFlexGridSizer(1, 1, 0, 0);
	mSizer->AddGrowableCol(0);
	mSizer->AddGrowableRow(0);
	mSizer->SetFlexibleDirection(wxVERTICAL);
	mSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);

	//mToolBarPanel = new wxPanel(this);
	//mSizer->Add(mToolBarPanel, 1, wxALL | wxEXPAND, 0);

	mTreeCtrl = new wxTreeCtrl(this, ID_TREE_CTRL, wxDefaultPosition, wxDefaultSize, wxNO_BORDER | wxTR_FULL_ROW_HIGHLIGHT | wxTR_HAS_BUTTONS | wxTR_SINGLE);
	mTreeCtrl->AssignImageList(getImageList());
	mRootId = mTreeCtrl->AddRoot(wxT("Workspace"), WORKSPACE_IMAGE);

	mSizer->Add(mTreeCtrl, 0, wxALL | wxEXPAND, 0);

	SetSizer(mSizer);
	Layout();
}

wxImageList* WorkspacePanel::getImageList()
{
	if(mImageList == NULL)
	{
		mImageList = new wxImageList(16, 16, true, 6);
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::WORKSPACE));
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::PROJECT));
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::MATERIAL_SCRIPT));
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::MATERIAL));
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::TECHNIQUE));
		mImageList->Add(IconManager::getSingleton().getIcon(IconManager::PASS));
	}

	return mImageList;
}

void WorkspacePanel::showContextMenu(wxPoint point, wxTreeItemId id)
{
	wxMenu contextMenu;
	appendNewMenu(&contextMenu);
	contextMenu.AppendSeparator();
	if(isProject(id)) appendProjectMenuItems(&contextMenu);
	else if(isMaterial(id)) appendMaterialMenuItems(&contextMenu);
	else if(isTechnique(id)) appendTechniqueMenuItems(&contextMenu);
	//else appendPassMenuItems(&contextMenu);
	contextMenu.Append(ID_MENU_EDIT, wxT("Edit"));
	PopupMenu(&contextMenu, point);
}

void WorkspacePanel::appendNewMenu(wxMenu* menu)
{
	wxMenu* newMenu = new wxMenu();
	newMenu->Append(ID_MENU_NEW_PROJECT, wxT("Project"));
	newMenu->Append(ID_MENU_NEW_MATERIAL_SCRIPT, wxT("Material Script"));
	newMenu->Append(ID_MENU_NEW_MATERIAL, wxT("Material"));
	newMenu->Append(ID_MENU_NEW_TECHNIQUE, wxT("Technique"));
	newMenu->Append(ID_MENU_NEW_PASS, wxT("Pass"));

	menu->AppendSubMenu(newMenu, wxT("New"));
}

void WorkspacePanel::appendProjectMenuItems(wxMenu* menu)
{
	menu->Append(ID_MENU_ADD_MATERIAL, wxT("Add Material"));
}

void WorkspacePanel::appendMaterialMenuItems(wxMenu* menu)
{
}

void WorkspacePanel::appendTechniqueMenuItems(wxMenu* menu)
{
}

void WorkspacePanel::appendPassMenuItems(wxMenu* menu)
{
	menu->AppendCheckItem(ID_MENU_PASS_ENABLED, wxT("Enabled"));
}

Project* WorkspacePanel::getProject(wxTreeItemId id)
{
	for(ProjectIdMap::iterator it = mProjectIdMap.begin(); it != mProjectIdMap.end(); ++it)
	{
		if(it->second == id) return it->first;
	}

	return NULL;
}

MaterialController* WorkspacePanel::getMaterial(wxTreeItemId id)
{
	for(MaterialIdMap::iterator it = mMaterialIdMap.begin(); it != mMaterialIdMap.end(); ++it)
	{
		if(it->second == id) return it->first;
	}

	return NULL;
}

TechniqueController* WorkspacePanel::getTechnique(wxTreeItemId id)
{
	for(TechniqueIdMap::iterator it = mTechniqueIdMap.begin(); it != mTechniqueIdMap.end(); ++it)
	{
		if(it->second == id) return it->first;
	}

	return NULL;
}

PassController* WorkspacePanel::getPass(wxTreeItemId id)
{
	for(PassIdMap::iterator it = mPassIdMap.begin(); it != mPassIdMap.end(); ++it)
	{
		if(it->second == id) return it->first;
	}

	return NULL;
}

bool WorkspacePanel::isWorkspace(wxTreeItemId id)
{
	return mRootId == id;
}

bool WorkspacePanel::isProject(wxTreeItemId id)
{
	return getProject(id) != NULL;
}

bool WorkspacePanel::isMaterial(wxTreeItemId id)
{
	return getMaterial(id) != NULL;
}

bool WorkspacePanel::isTechnique(wxTreeItemId id)
{
	return getTechnique(id) != NULL;
}

bool WorkspacePanel::isPass(wxTreeItemId id)
{
	return getPass(id) != NULL;
}

void WorkspacePanel::subscribe(Project* project)
{
	project->subscribe(Project::NameChanged, boost::bind(&WorkspacePanel::projectNameChanged, this, _1));
	project->subscribe(Project::MaterialAdded, boost::bind(&WorkspacePanel::projectMaterialAdded, this, _1));
	project->subscribe(Project::MaterialRemoved, boost::bind(&WorkspacePanel::projectMaterialRemoved, this, _1));
}

void WorkspacePanel::subscribe(MaterialController* material)
{
	material->subscribe(MaterialController::NameChanged, boost::bind(&WorkspacePanel::materialNameChanged, this, _1));
	material->subscribe(MaterialController::TechniqueAdded, boost::bind(&WorkspacePanel::materialTechniqueAdded, this, _1));
	material->subscribe(MaterialController::TechniqueRemoved, boost::bind(&WorkspacePanel::materialTechniqueRemoved, this, _1));
}

void WorkspacePanel::subscribe(TechniqueController* technique)
{
	technique->subscribe(TechniqueController::NameChanged, boost::bind(&WorkspacePanel::techniqueNameChanged, this, _1));
	technique->subscribe(TechniqueController::PassAdded, boost::bind(&WorkspacePanel::techniquePassAdded, this, _1));
	technique->subscribe(TechniqueController::PassRemoved, boost::bind(&WorkspacePanel::techniquePassRemoved, this, _1));
}

void WorkspacePanel::OnRightClick(wxTreeEvent& event)
{
	showContextMenu(event.GetPoint(), event.GetItem());
}

void WorkspacePanel::OnActivate(wxTreeEvent& event)
{
	OnEdit(event);
}

void WorkspacePanel::OnSelectionChanged(wxTreeEvent& event)
{
	SelectionList list;
	wxTreeItemId id = event.GetItem();
	if(isProject(id)) list.push_back(getProject(id));
	else if(isMaterial(id)) list.push_back(getMaterial(id));
	else if(isTechnique(id)) list.push_back(getTechnique(id));
	else if(isPass(id)) list.push_back(getPass(id));
	// else its the workspace so just leave the list empty as if nothing were selected

	SelectionService::getSingletonPtr()->setSelection(list);
}

void WorkspacePanel::OnNewProject(wxCommandEvent& event)
{
	ProjectWizard* wizard = new ProjectWizard();
	wizard->Create(this, wxID_ANY, wxT("New Project"), wxNullBitmap, wxDefaultPosition, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
	wizard->RunWizard(wizard->getProjectPage()); // This seems unnatural, seems there must be a better way to deal with wizards

	wizard->Destroy();

	delete wizard;
}

void WorkspacePanel::OnNewMaterialScript(wxCommandEvent& event)
{
	wxTreeItemId id = mTreeCtrl->GetSelection();
	mTreeCtrl->AppendItem(id, "Material Script", MATERIAL_SCRIPT_IMAGE);
}

void WorkspacePanel::OnNewMaterial(wxCommandEvent& event)
{
	wxTreeItemId id = mTreeCtrl->GetSelection();

	MaterialWizard* wizard = new MaterialWizard();
	wizard->Create(this, wxID_ANY, wxT("New Project"), wxNullBitmap, wxDefaultPosition, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
	wizard->getMaterialPage()->setProject(getProject(id));
	wizard->RunWizard(wizard->getMaterialPage()); // This seems unnatural, seems there must be a better way to deal with wizards

	wizard->Destroy();

	delete wizard;
}

void WorkspacePanel::OnNewTechnique(wxCommandEvent& event)
{
	Project* project = NULL;
	MaterialController* material = NULL;

	wxTreeItemId selId = mTreeCtrl->GetSelection();
	if(isProject(selId))
	{
		project = getProject(selId);
	}
	else if(isMaterial(selId))
	{
		wxTreeItemId projectId = mTreeCtrl->GetItemParent(selId);
		project = getProject(projectId);

		material = getMaterial(selId);
	}

	TechniqueWizard* wizard = new TechniqueWizard();
	wizard->Create(this, wxID_ANY, wxT("New Technique"), wxNullBitmap, wxDefaultPosition, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
	wizard->getTechniquePage()->setProject(project);
	wizard->getTechniquePage()->setMaterial(material);
	wizard->RunWizard(wizard->getTechniquePage()); // This seems unnatural, seems there must be a better way to deal with wizards

	wizard->Destroy();

	delete wizard;
}

void WorkspacePanel::OnNewPass(wxCommandEvent& event)
{
	Project* project = NULL;
	MaterialController* material = NULL;
	TechniqueController* technique = NULL;

	wxTreeItemId selId = mTreeCtrl->GetSelection();
	if(isProject(selId))
	{
		project = getProject(selId);
	}
	else if(isMaterial(selId))
	{
		wxTreeItemId projectId = mTreeCtrl->GetItemParent(selId);
		project = getProject(projectId);

		material = getMaterial(selId);
	}
	else if(isTechnique(selId))
	{
		wxTreeItemId materialId = mTreeCtrl->GetItemParent(selId);
		material = getMaterial(materialId);

		wxTreeItemId projectId = mTreeCtrl->GetItemParent(materialId);
		project = getProject(projectId);

		technique = getTechnique(selId);
	}

	PassWizard* wizard = new PassWizard();
	wizard->Create(this, wxID_ANY, wxT("New Pass"), wxNullBitmap, wxDefaultPosition, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
	wizard->getPassPage()->setProject(project);
	wizard->getPassPage()->setMaterial(material);
	wizard->getPassPage()->setTechnique(technique);
	wizard->RunWizard(wizard->getPassPage());

	wizard->Destroy();

	delete wizard;
}

void WorkspacePanel::OnAddMaterial(wxCommandEvent& event)
{
	wxFileDialog * openDialog = new wxFileDialog(this, wxT("Add a Material"), wxEmptyString, wxEmptyString,
		wxT("Material Files (*.material)|*.material|All Files (*.*)|*.*"));

	if(openDialog->ShowModal() == wxID_OK)
	{
		wxString path = openDialog->GetPath();
		if(path.EndsWith(wxT(".material")))
		{
			wxTreeItemId selId = mTreeCtrl->GetSelection();
			if(isProject(selId))
			{
				Project* project = getProject(selId);

				MaterialScriptEditor* editor = new MaterialScriptEditor(EditorManager::getSingletonPtr()->getEditorNotebook());
				editor->loadFile(path);
				int index = (int)path.find_last_of('\\');
				if(index == -1) index = (int)path.find_last_of('/');
				editor->setName((index != -1) ? path.substr(index + 1, path.Length()) : path);

				EditorManager::getSingletonPtr()->openEditor(editor);

				Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName("Ogre/Earring");
				project->addMaterial(mat);
			}
		}
	}
}

void WorkspacePanel::OnEdit(wxCommandEvent& event)
{
	wxTreeItemId selId = mTreeCtrl->GetSelection();
	if(isMaterial(selId))
	{
		MaterialController* mc = getMaterial(selId);

		EditorManager* editorManager = EditorManager::getSingletonPtr();
		Editor* editor = editorManager->findEditor(mc->getMaterial()->getName().c_str());
		Editor* editorMat = editorManager->findEditor(Ogre::String(mc->getMaterial()->getName() + ".material").c_str());
		if(editor != NULL)
		{
			editorManager->setActiveEditor(editor);
		}
		else if(editorMat != NULL)
		{
			editorManager->setActiveEditor(editorMat);
		}
		else
		{
			MaterialSerializer* ms = new MaterialSerializer();
			ms->queueForExport(mc->getMaterial(), true);
			String script = ms->getQueuedAsString();

			MaterialScriptEditor* materialEditor = new MaterialScriptEditor(editorManager->getEditorNotebook(), wxID_ANY);
			wxString name = mc->getMaterial()->getName().c_str();
			name += wxT(".material");
			materialEditor->setName(name);
			materialEditor->SetText(script);

			editorManager->openEditor(materialEditor);
		}
	}
}

void WorkspacePanel::OnUpdateMaterialMenuItem(wxUpdateUIEvent& event)
{
	event.Enable(!Workspace::getSingletonPtr()->getProjects()->empty());
}

void WorkspacePanel::OnUpdateTechniqueMenuItem(wxUpdateUIEvent& event)
{
	bool enable = false;
	const ProjectList* projects = Workspace::getSingletonPtr()->getProjects();

	ProjectList::const_iterator it;
	for(it = projects->begin(); it != projects->end(); ++it)
	{
		if(!(*it)->getMaterials()->empty())
		{
			enable = true;
			break;
		}
	}

	event.Enable(enable);
}

void WorkspacePanel::OnUpdatePassMenuItem(wxUpdateUIEvent& event)
{
	bool enable = false;
	const ProjectList* projects = Workspace::getSingletonPtr()->getProjects();

	ProjectList::const_iterator pit;
	for(pit = projects->begin(); pit != projects->end(); ++pit)
	{
		const MaterialControllerList* materials = (*pit)->getMaterials();
		MaterialControllerList::const_iterator mit;
		for(mit = materials->begin(); mit != materials->end(); ++mit)
		{
			if(!(*mit)->getTechniqueControllers()->empty())
			{
				enable = true;
				break;
			}
		}
	}

	event.Enable(enable);
}

void WorkspacePanel::projectAdded(EventArgs& args)
{
	WorkspaceEventArgs wea = dynamic_cast<WorkspaceEventArgs&>(args);
	Project* project = wea.getProject();
	subscribe(project);

	wxTreeItemId id = mTreeCtrl->AppendItem(mRootId, project->getName().c_str(), PROJECT_IMAGE);
	mTreeCtrl->SelectItem(id, true);

	mProjectIdMap[project] = id;
}

void WorkspacePanel::projectRemoved(EventArgs& args)
{
	// TODO: Implement projectRemoved
}

void WorkspacePanel::projectNameChanged(EventArgs& args)
{
	ProjectEventArgs pea = dynamic_cast<ProjectEventArgs&>(args);
	Project* project = pea.getProject();

	wxTreeItemId projectId = mProjectIdMap[project];
	mTreeCtrl->SetItemText(projectId, project->getName().c_str());
}

void WorkspacePanel::projectMaterialAdded(EventArgs& args)
{
	ProjectEventArgs pea = dynamic_cast<ProjectEventArgs&>(args);
	Project* project = pea.getProject();
	MaterialController* material = pea.getMaterial();

	wxTreeItemId projectId = mProjectIdMap[project];
	wxTreeItemId id = mTreeCtrl->AppendItem(projectId, material->getMaterial()->getName().c_str(), MATERIAL_IMAGE);
	mTreeCtrl->SelectItem(id, true);

	mMaterialIdMap[material] = id;

	subscribe(material);
}

void WorkspacePanel::projectMaterialRemoved(EventArgs& args)
{
	// TODO: Implement projectMaterialRemoved
}

void WorkspacePanel::materialNameChanged(EventArgs& args)
{
	MaterialEventArgs mea = dynamic_cast<MaterialEventArgs&>(args);
	MaterialController* mc = mea.getMaterialController();

	wxTreeItemId materialId = mMaterialIdMap[mc];
	mTreeCtrl->SetItemText(materialId, mc->getMaterial()->getName().c_str());
}

void WorkspacePanel::materialTechniqueAdded(EventArgs& args)
{
	MaterialEventArgs mea = dynamic_cast<MaterialEventArgs&>(args);
	MaterialController* mc = mea.getMaterialController();
	TechniqueController* tc = mea.getTechniqueController();

	wxTreeItemId materialId = mMaterialIdMap[mc];
	wxTreeItemId id = mTreeCtrl->AppendItem(materialId, tc->getTechnique()->getName().c_str(), TECHNIQUE_IMAGE);
	mTreeCtrl->SelectItem(id, true);

	mTechniqueIdMap[tc] = id;

	subscribe(tc);
}

void WorkspacePanel::materialTechniqueRemoved(EventArgs& args)
{
	// TODO: Implement materialTechniqueRemoved
}

void WorkspacePanel::techniqueNameChanged(EventArgs& args)
{
	TechniqueEventArgs tea = dynamic_cast<TechniqueEventArgs&>(args);
	TechniqueController* tc = tea.getTechniqueController();

	wxTreeItemId techniqueId = mTechniqueIdMap[tc];
	mTreeCtrl->SetItemText(techniqueId, tc->getTechnique()->getName().c_str());
}

void WorkspacePanel::techniquePassAdded(EventArgs& args)
{
	TechniqueEventArgs tea = dynamic_cast<TechniqueEventArgs&>(args);
	TechniqueController* tc = tea.getTechniqueController();
	PassController* pc = tea.getPassController();

	wxTreeItemId techniqueId = mTechniqueIdMap[tc];
	wxTreeItemId id = mTreeCtrl->AppendItem(techniqueId, pc->getPass()->getName().c_str(), PASS_IMAGE);
	mTreeCtrl->SelectItem(id, true);

	mPassIdMap[pc] = id;
}

void WorkspacePanel::techniquePassRemoved(EventArgs& args)
{
	// TODO: Implement materialTechniqueRemoved
}

max_stars_repo_name: MrTypename/ogre-code

max_issues_repo_name: MrTypename/ogre-code

max_forks_repo_name: MrTypename/ogre-code


text:
#include <sbpl_interface/bfs3d/BFS_3D.h>
#include <iostream>
#include <boost/thread.hpp>

namespace sbpl_interface
{
#define EXPAND_NEIGHBOR(offset)                                                                                \
  if (distance_grid[currentNode + offset] < 0)                                                                         \
  {                                                                                \
    queue[queue_tail++] = currentNode + offset;                                                                        \
    distance_grid[currentNode + offset] = currentCost;                                                                 \
    boost::this_thread::interruption_point();                                                                          \
  }

void BFS_3D::search(int width, int planeSize, int volatile* distance_grid, int* queue, int& queue_head, int& queue_tail)
{
  while (queue_head < queue_tail)
  {
    int currentNode = queue[queue_head++];
    int currentCost = distance_grid[currentNode] + 1;

    EXPAND_NEIGHBOR(-width);
    EXPAND_NEIGHBOR(1);
    EXPAND_NEIGHBOR(width);
    EXPAND_NEIGHBOR(-1);
    EXPAND_NEIGHBOR(-width - 1);
    EXPAND_NEIGHBOR(-width + 1);
    EXPAND_NEIGHBOR(width + 1);
    EXPAND_NEIGHBOR(width - 1);
    EXPAND_NEIGHBOR(planeSize);
    EXPAND_NEIGHBOR(-width + planeSize);
    EXPAND_NEIGHBOR(1 + planeSize);
    EXPAND_NEIGHBOR(width + planeSize);
    EXPAND_NEIGHBOR(-1 + planeSize);
    EXPAND_NEIGHBOR(-width - 1 + planeSize);
    EXPAND_NEIGHBOR(-width + 1 + planeSize);
    EXPAND_NEIGHBOR(width + 1 + planeSize);
    EXPAND_NEIGHBOR(width - 1 + planeSize);
    EXPAND_NEIGHBOR(-planeSize);
    EXPAND_NEIGHBOR(-width - planeSize);
    EXPAND_NEIGHBOR(1 - planeSize);
    EXPAND_NEIGHBOR(width - planeSize);
    EXPAND_NEIGHBOR(-1 - planeSize);
    EXPAND_NEIGHBOR(-width - 1 - planeSize);
    EXPAND_NEIGHBOR(-width + 1 - planeSize);
    EXPAND_NEIGHBOR(width + 1 - planeSize);
    EXPAND_NEIGHBOR(width - 1 - planeSize);
  }
  // std::cerr << "Search thread done" << std::endl;
  running = false;
}
}

max_stars_repo_name: simonschmeisser/moveit

max_issues_repo_name: simonschmeisser/moveit

max_forks_repo_name: simonschmeisser/moveit


text:
///////////////////////////////////////////////////////////////////////////////
// detail_fwd.hpp
//
//  Copyright 2008 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_DETAIL_DETAIL_FWD_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_DETAIL_FWD_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/mpl/bool.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/xpressive/xpressive_fwd.hpp>
#include <climits> // for INT_MAX
#include <map>
#include <string>
#include <typeinfo>
#include <vector>

namespace boost
{
namespace xpressive
{
namespace detail
{
typedef unsigned int uint_t;

template <uint_t Min, uint_t Max = Min>
struct generic_quant_tag;

struct modifier_tag;

struct check_tag;

typedef mpl::size_t<INT_MAX / 2 - 1> unknown_width;

struct type_info_less;

typedef std::map<std::type_info const*, void*, type_info_less> action_args_type;

struct action_context;

struct ReplaceAlgo;

///////////////////////////////////////////////////////////////////////////////
// placeholders
//
struct mark_placeholder;

struct posix_charset_placeholder;

template <typename Cond>
struct assert_word_placeholder;

template <typename Char>
struct range_placeholder;

struct assert_bol_placeholder;

struct assert_eol_placeholder;

struct logical_newline_placeholder;

struct self_placeholder;

template <typename Nbr>
struct attribute_placeholder;

///////////////////////////////////////////////////////////////////////////////
// matchers
//
struct end_matcher;

struct independent_end_matcher;

struct assert_bos_matcher;

struct assert_eos_matcher;

template <typename Traits>
struct assert_bol_matcher;

template <typename Traits>
struct assert_eol_matcher;

template <typename Cond, typename Traits>
struct assert_word_matcher;

struct true_matcher;

template <typename Alternates, typename Traits>
struct alternate_matcher;

struct alternate_end_matcher;

template <typename Traits>
struct posix_charset_matcher;

template <typename BidiIter>
struct sequence;

template <typename Traits, typename ICase>
struct mark_matcher;

struct mark_begin_matcher;

struct mark_end_matcher;

template <typename BidiIter>
struct regex_matcher;

template <typename BidiIter>
struct regex_byref_matcher;

template <typename Traits>
struct compound_charset;

template <typename Traits, typename ICase,
          typename CharSet = compound_charset<Traits>>
struct charset_matcher;

template <typename Traits, typename ICase>
struct range_matcher;

template <typename Traits, typename Size>
struct set_matcher;

template <typename Xpr, typename Greedy>
struct simple_repeat_matcher;

struct repeat_begin_matcher;

template <typename Greedy>
struct repeat_end_matcher;

template <typename Traits, typename ICase, typename Not>
struct literal_matcher;

template <typename Traits, typename ICase>
struct string_matcher;

template <typename Actor>
struct action_matcher;

template <typename Predicate>
struct predicate_matcher;

template <typename Xpr, typename Greedy>
struct optional_matcher;

template <typename Xpr, typename Greedy>
struct optional_mark_matcher;

template <typename Matcher, typename Traits, typename ICase>
struct attr_matcher;

template <typename Nbr>
struct attr_begin_matcher;

struct attr_end_matcher;

template <typename Xpr>
struct is_modifiable;

template <typename Head, typename Tail>
struct alternates_list;

template <typename Modifier>
struct modifier_op;

struct icase_modifier;

template <typename BidiIter, typename ICase, typename Traits>
struct xpression_visitor;

template <typename BidiIter>
struct regex_impl;

struct epsilon_matcher;

template <typename BidiIter>
struct nested_results;

template <typename BidiIter>
struct regex_id_filter_predicate;

template <typename Xpr>
struct keeper_matcher;

template <typename Xpr>
struct lookahead_matcher;

template <typename Xpr>
struct lookbehind_matcher;

template <typename IsBoundary>
struct word_boundary;

template <typename BidiIter, typename Matcher>
sequence<BidiIter> make_dynamic(Matcher const& matcher);

template <typename Char>
struct xpression_linker;

template <typename Char>
struct xpression_peeker;

struct any_matcher;

template <typename Traits>
struct logical_newline_matcher;

typedef proto::expr<proto::tag::terminal,
                    proto::term<logical_newline_placeholder>, 0>
    logical_newline_xpression;

struct set_initializer;

typedef proto::expr<proto::tag::terminal, proto::term<set_initializer>, 0>
    set_initializer_type;

struct lookahead_tag;

struct lookbehind_tag;

struct keeper_tag;

template <typename Locale>
struct locale_modifier;

template <typename Matcher>
struct matcher_wrapper;

template <typename Locale, typename BidiIter>
struct regex_traits_type;

template <typename Expr>
struct let_;

template <typename Args, typename BidiIter>
void bind_args(let_<Args> const&, match_results<BidiIter>&);

///////////////////////////////////////////////////////////////////////////////
// Misc.
struct no_next;

template <typename BidiIter>
struct core_access;

template <typename BidiIter>
struct match_state;

template <typename BidiIter>
struct matchable;

template <typename BidiIter>
struct matchable_ex;

template <typename Matcher, typename BidiIter>
struct dynamic_xpression;

template <typename BidiIter>
struct shared_matchable;

template <typename BidiIter>
struct alternates_vector;

template <typename Matcher, typename Next>
struct static_xpression;

typedef static_xpression<end_matcher, no_next> end_xpression;

typedef static_xpression<alternate_end_matcher, no_next>
    alternate_end_xpression;

typedef static_xpression<independent_end_matcher, no_next>
    independent_end_xpression;

typedef static_xpression<true_matcher, no_next> true_xpression;

template <typename Matcher, typename Next = end_xpression>
struct static_xpression;

template <typename Top, typename Next>
struct stacked_xpression;

template <typename Xpr>
struct is_static_xpression;

template <typename BidiIter>
struct sub_match_impl;

template <typename T>
struct list;

template <typename BidiIter>
struct results_cache;

template <typename T>
struct sequence_stack;

template <typename BidiIter>
struct results_extras;

template <typename BidiIter>
struct match_context;

template <typename BidiIter>
struct sub_match_vector;

template <typename T, typename U>
struct action_arg;

struct actionable;

template <typename Char>
struct traits;

template <typename Traits, typename BidiIter>
Traits const& traits_cast(match_state<BidiIter> const& state);

template <typename Char>
struct basic_chset;

template <typename Char>
struct named_mark;

template <typename BidiIter>
struct memento;

template <typename Char, typename Traits>
void set_char(compound_charset<Traits>& chset, Char ch, Traits const& tr,
              bool icase);

template <typename Char, typename Traits>
void set_range(compound_charset<Traits>& chset, Char from, Char to,
               Traits const& tr, bool icase);

template <typename Traits>
void set_class(compound_charset<Traits>& chset,
               typename Traits::char_class_type char_class, bool no,
               Traits const& tr);

template <typename Char, typename Traits>
void set_char(basic_chset<Char>& chset, Char ch, Traits const& tr, bool icase);

template <typename Char, typename Traits>
void set_range(basic_chset<Char>& chset, Char from, Char to, Traits const& tr,
               bool icase);

template <typename Char, typename Traits>
void set_class(basic_chset<Char>& chset,
               typename Traits::char_class_type char_class, bool no,
               Traits const& tr);

template <typename Matcher>
static_xpression<Matcher> const make_static(Matcher const& matcher);

template <typename Matcher, typename Next>
static_xpression<Matcher, Next> const make_static(Matcher const& matcher,
                                                  Next const& next);

int get_mark_number(basic_mark_tag const&);

template <typename Xpr, typename BidiIter>
void static_compile(Xpr const& xpr,
                    shared_ptr<regex_impl<BidiIter>> const& impl);

struct quant_spec;

template <typename BidiIter, typename Xpr>
void make_simple_repeat(quant_spec const& spec, sequence<BidiIter>& seq,
                        Xpr const& xpr);

template <typename BidiIter>
void make_simple_repeat(quant_spec const& spec, sequence<BidiIter>& seq);

template <typename BidiIter>
void make_repeat(quant_spec const& spec, sequence<BidiIter>& seq, int mark_nbr);

template <typename BidiIter>
void make_repeat(quant_spec const& spec, sequence<BidiIter>& seq);

template <typename BidiIter>
void make_optional(quant_spec const& spec, sequence<BidiIter>& seq);

template <typename BidiIter>
void make_optional(quant_spec const& spec, sequence<BidiIter>& seq,
                   int mark_nbr);

template <typename Char>
struct string_type
{
    typedef std::vector<Char> type;
};

template <>
struct string_type<char>
{
    typedef std::string type;
};

#ifndef BOOST_XPRESSIVE_NO_WREGEX
template <>
struct string_type<wchar_t>
{
    typedef std::wstring type;
};
#endif

} // namespace detail
} // namespace xpressive
} // namespace boost

namespace boost
{
namespace xpressive
{
namespace grammar_detail
{
using proto::_;
using proto::_child;
using proto::_data;
using proto::_deep_copy;
using proto::_left;
using proto::_right;
using proto::_state;
using proto::_value;
using proto::assign;
using proto::binary_expr;
using proto::bitwise_or;
using proto::call;
using proto::callable;
using proto::comma;
using proto::complement;
using proto::dereference;
using proto::fold;
using proto::fold_tree;
using proto::if_;
using proto::logical_not;
using proto::make;
using proto::nary_expr;
using proto::negate;
using proto::not_;
using proto::or_;
using proto::otherwise;
using proto::reverse_fold;
using proto::reverse_fold_tree;
using proto::shift_right;
using proto::subscript;
using proto::switch_;
using proto::terminal;
using proto::transform;
using proto::unary_expr;
using proto::unary_plus;
using proto::vararg;
using proto::when;
namespace tag = proto::tag;
} // namespace grammar_detail
} // namespace xpressive
} // namespace boost

namespace boost
{
namespace xpressive
{
namespace op
{
struct push;
struct push_back;
struct pop;
struct push_front;
struct pop_back;
struct pop_front;
struct back;
struct front;
struct top;
struct first;
struct second;
struct matched;
struct length;
struct str;
struct insert;
struct make_pair;

template <typename T>
struct as;
template <typename T>
struct static_cast_;
template <typename T>
struct dynamic_cast_;
template <typename T>
struct const_cast_;
template <typename T>
struct construct;
template <typename T>
struct throw_;
} // namespace op
} // namespace xpressive
} // namespace boost

/// INTERNAL ONLY
namespace boost
{
namespace xpressive
{

/// INTERNAL ONLY
template <typename Traits, std::size_t N>
typename Traits::char_class_type lookup_classname(Traits const& traits,
                                                  char const (&cname)[N],
                                                  bool icase = false);

} // namespace xpressive
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
#ifndef _SIMPLE_CFG_GRAMMAR_HPP_
#define _SIMPLE_CFG_GRAMMAR_HPP_

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include "SimpleCFGStructure.hpp"

namespace cfg
{
    namespace qi = boost::spirit::qi;
    namespace standard_wide = boost::spirit::standard_wide;

    template <typename Iterator>
    struct simple_cfg_grammar
    : qi::grammar<Iterator, config_file(), standard_wide::space_type>
    {
        simple_cfg_grammar()
        : simple_cfg_grammar::base_type(file)
        {
            using qi::lexeme;
            using qi::eol;
            using qi::omit;
            using qi::raw;
            using qi::skip;
            using qi::lit;
            using standard_wide::char_;
            using standard_wide::alnum;
            using standard_wide::alpha;
            using standard_wide::space;
            using standard_wide::blank;

            comments %=
                    lexeme[omit[+lit("//")] >> *(char_ - eol) >> eol]
            ;

            name %=
                    lexeme[(alpha | char_('_')) >> *(alnum | char_('_'))]
            ;

            type %=
                    raw[-standard_wide::string("unsigned") >> name >>  -char_('*')]
			;

            parameter %=
                    type
            ;

            attribute_prototype %=
                    type
                >>  name
                >>  lit("::")
                >>  name
            ;

            function_prototype %=
                    type
                >>  name
                >>  lit("::")
                >>  name
                >>  '('
                >>  -(parameter % ',')
                >>  ')'
            ;

            identifier %=
                  '[' >> (function_prototype | attribute_prototype | lexeme[+(alnum | char_('_') | char_('-'))]) >> ']'
            ;

            branch %=
                    +char_('-') | name
            ;

            element %=
                    branch
                >>  *identifier
            ;

            path %=
                    ((char_('.') | element) % '/')
            ;

            value %=
                    raw[+(char_ - ';')] >> ';'
            ;

            text %=
                   "${"
                >> lexeme[+(char_ - lit("}$"))]
                >> "}$"
            ;

            content %=
                    (text | value)
            ;

            property %=
                    path
                >>  '='
                >>  content
            ;

            line %=
                    (property | path) >> eol
            ;

            file %=
                    *(skip(blank)[omit[comments] | line | eol])
            ;
        }

        qi::rule<Iterator, config_file(),      standard_wide::space_type> file;
        qi::rule<Iterator, config_line(),      standard_wide::blank_type> line;
        qi::rule<Iterator, config_property(),  standard_wide::blank_type> property;
        qi::rule<Iterator, config_path(),      standard_wide::blank_type> path;
        qi::rule<Iterator, config_content(),   standard_wide::blank_type> content;
        qi::rule<Iterator, config_value(),     standard_wide::blank_type> value;
        qi::rule<Iterator, config_text(),      standard_wide::blank_type> text;
        qi::rule<Iterator, config_element(),   standard_wide::blank_type> element;
        qi::rule<Iterator, config_branch(),    standard_wide::blank_type> branch;
        qi::rule<Iterator, config_identifier(),standard_wide::blank_type> identifier;
        qi::rule<Iterator, config_attribute(), standard_wide::blank_type> attribute_prototype;
        qi::rule<Iterator, config_function(),  standard_wide::blank_type> function_prototype;
        qi::rule<Iterator, fct_parameter(),    standard_wide::blank_type> parameter;
        qi::rule<Iterator, std::wstring(),     standard_wide::blank_type> type;
        qi::rule<Iterator, std::wstring(),     standard_wide::blank_type> name;
        qi::rule<Iterator, std::vector<std::wstring>(), standard_wide::blank_type> comments;
    };

}

#endif // _SIMPLE_CFG_GRAMMAR_HPP_