<commit_before>/*
 * Copyright (c) 2008-2018 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/
 *
 * MRtrix3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * For more details, see http://www.mrtrix.org/
 */

#include "command.h"
#include "progressbar.h"
#include "types.h"

#include "file/path.h"
#include "math/stats/glm.h"
#include "math/stats/permutation.h"
#include "math/stats/typedefs.h"

#include "connectome/enhance.h"
#include "connectome/mat2vec.h"

#include "stats/permtest.h"

using namespace MR;
using namespace App;

const char* algorithms[] = { "nbs", "nbse", "none", nullptr };

// TODO Eventually these will move to some kind of TFCE header
#define TFCE_DH_DEFAULT 0.1
#define TFCE_E_DEFAULT 0.4
#define TFCE_H_DEFAULT 3.0

void usage ()
{
  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";

  SYNOPSIS = "Connectome group-wise statistics at the edge level using non-parametric permutation testing";

  ARGUMENTS
  + Argument ("input", "a text file listing the file names of the input connectomes").type_file_in ()

  + Argument ("algorithm", "the algorithm to use in network-based clustering/enhancement. "
                           "Options are: " + join(algorithms, ", ")).type_choice (algorithms)

  + Argument ("design", "the design matrix. Note that a column of 1's will need to be added for correlations.").type_file_in ()

  + Argument ("contrast", "the contrast vector, specified as a single row of weights").type_file_in ()

  + Argument ("output", "the filename prefix for all output.").type_text();

  OPTIONS

  + Stats::PermTest::Options (true)

  // TODO OptionGroup these, and provide a generic loader function
  + Stats::TFCE::Options (TFCE_DH_DEFAULT, TFCE_E_DEFAULT, TFCE_H_DEFAULT)

  + OptionGroup ("Additional options for connectomestats")

  + Option ("threshold", "the t-statistic value to use in threshold-based clustering algorithms")
  + Argument ("value").type_float (0.0);

  REFERENCES + "* If using the NBS algorithm: \n"
               "Zalesky, A.; Fornito, A. & Bullmore, E. T. Network-based statistic: Identifying differences in brain networks. \n"
               "NeuroImage, 2010, 53, 1197-1207"

             + "* If using the NBSE algorithm: \n"
               "Vinokur, L.; Zalesky, A.; Raffelt, D.; Smith, R.E. & Connelly, A. A Novel Threshold-Free Network-Based Statistics Method: Demonstration using Simulated Pathology. \n"
               "OHBM, 2015, 4144"

             + "* If using the -nonstationary option: \n"
               "Salimi-Khorshidi, G.; Smith, S.M. & Nichols, T.E. Adjusting the effect of nonstationarity in cluster-based and TFCE inference. \n"
               "Neuroimage, 2011, 54(3), 2006-19";

}

using Math::Stats::matrix_type;
using Math::Stats::vector_type;

void load_tfce_parameters (Stats::TFCE::Wrapper& enhancer)
{
  const default_type dH = get_option_value ("tfce_dh", TFCE_DH_DEFAULT);
  const default_type E  = get_option_value ("tfce_e", TFCE_E_DEFAULT);
  const default_type H  = get_option_value ("tfce_h", TFCE_H_DEFAULT);
  enhancer.set_tfce_parameters (dH, E, H);
}

void run()
{

  // Read filenames
  vector<std::string> filenames;
  {
    std::string folder = Path::dirname (argument[0]);
    std::ifstream ifs (argument[0].c_str());
    std::string temp;
    while (getline (ifs, temp)) {
      std::string filename (Path::join (folder, temp));
      size_t p = filename.find_last_not_of(" \t");
      if (std::string::npos != p)
        filename.erase(p+1);
      if (filename.size()) {
        if (!MR::Path::exists (filename))
          throw Exception ("Input connectome file not found: \"" + filename + "\"");
        filenames.push_back (filename);
      }
    }
  }

  const MR::Connectome::matrix_type example_connectome = load_matrix (filenames.front());
  if (example_connectome.rows() != example_connectome.cols())
    throw Exception ("Connectome of first subject is not square (" + str(example_connectome.rows()) + " x " + str(example_connectome.cols()) + ")");
  const MR::Connectome::node_t num_nodes = example_connectome.rows();

  // Initialise enhancement algorithm
  std::shared_ptr<Stats::EnhancerBase> enhancer;
  switch (int(argument[1])) {
    case 0: {
      auto opt = get_options ("threshold");
      if (!opt.size())
        throw Exception ("For NBS algorithm, -threshold option must be provided");
      enhancer.reset (new MR::Connectome::Enhance::NBS (num_nodes, opt[0][0]));
      }
      break;
    case 1: {
      std::shared_ptr<Stats::TFCE::EnhancerBase> base (new MR::Connectome::Enhance::NBS (num_nodes));
      enhancer.reset (new Stats::TFCE::Wrapper (base));
      load_tfce_parameters (*(dynamic_cast<Stats::TFCE::Wrapper*>(enhancer.get())));
      if (get_options ("threshold").size())
        WARN (std::string (argument[1]) + " is a threshold-free algorithm; -threshold option ignored");
      }
      break;
    case 2: {
      enhancer.reset (new MR::Connectome::Enhance::PassThrough());
      if (get_options ("threshold").size())
        WARN ("No enhancement algorithm being used; -threshold option ignored");
      }
      break;
    default:
      throw Exception ("Unknown enhancement algorithm");
  }

  size_t num_perms = get_option_value ("nperms", DEFAULT_NUMBER_PERMUTATIONS);
  const bool do_nonstationary_adjustment = get_options ("nonstationary").size();
  size_t nperms_nonstationary = get_option_value ("nperms_nonstationarity", DEFAULT_NUMBER_PERMUTATIONS_NONSTATIONARITY);

  // Load design matrix
  const matrix_type design = load_matrix (argument[2]);
  if (size_t(design.rows()) != filenames.size())
    throw Exception ("number of subjects does not match number of rows in design matrix");

  // Load permutations file if supplied
  auto opt = get_options("permutations");
  vector<vector<size_t> > permutations;
  if (opt.size()) {
    permutations = Math::Stats::Permutation::load_permutations_file (opt[0][0]);
    num_perms = permutations.size();
    if (permutations[0].size() != (size_t)design.rows())
      throw Exception ("number of rows in the permutations file (" + str(opt[0][0]) + ") does not match number of rows in design matrix");
  }

  // Load non-stationary correction permutations file if supplied
  opt = get_options("permutations_nonstationary");
  vector<vector<size_t> > permutations_nonstationary;
  if (opt.size()) {
    permutations_nonstationary = Math::Stats::Permutation::load_permutations_file (opt[0][0]);
    nperms_nonstationary = permutations.size();
    if (permutations_nonstationary[0].size() != (size_t)design.rows())
      throw Exception ("number of rows in the nonstationary permutations file (" + str(opt[0][0]) + ") does not match number of rows in design matrix");
  }

  // Load contrast matrix
  matrix_type contrast = load_matrix (argument[3]);
  if (contrast.cols() > design.cols())
    throw Exception ("too many contrasts for design matrix");
  contrast.conservativeResize (contrast.rows(), design.cols());

  const std::string output_prefix = argument[4];

  // Load input data
  // For compatibility with existing statistics code, symmetric matrix data is adjusted
  //   into vector form - one row per edge in the symmetric connectome. The Mat2Vec class
  //   deals with the re-ordering of matrix data into this form.
  MR::Connectome::Mat2Vec mat2vec (num_nodes);
  const size_t num_edges = mat2vec.vec_size();
  matrix_type data (num_edges, filenames.size());
  {
    ProgressBar progress ("Loading input connectome data", filenames.size());
    for (size_t subject = 0; subject < filenames.size(); subject++) {

      const std::string& path (filenames[subject]);
      MR::Connectome::matrix_type subject_data;
      try {
        subject_data = load_matrix (path);
      } catch (Exception& e) {
        throw Exception (e, "Error loading connectome data for subject #" + str(subject) + " (file \"" + path + "\"");
      }

      try {
        MR::Connectome::to_upper (subject_data);
        if (size_t(subject_data.rows()) != num_nodes)
          throw Exception ("Connectome matrix is not the correct size (" + str(subject_data.rows()) + ", should be " + str(num_nodes) + ")");
      } catch (Exception& e) {
        throw Exception (e, "Connectome for subject #" + str(subject) + " (file \"" + path + "\") invalid");
      }

      for (size_t i = 0; i != num_edges; ++i)
        data(i, subject) = subject_data (mat2vec(i).first, mat2vec(i).second);

      ++progress;
    }
  }

  {
    ProgressBar progress ("outputting beta coefficients, effect size and standard deviation...", contrast.cols() + 3);

    const matrix_type betas = Math::Stats::GLM::solve_betas (data, design);
    for (size_t i = 0; i < size_t(contrast.cols()); ++i) {
      save_matrix (mat2vec.V2M (betas.col(i)), output_prefix + "_beta_" + str(i) + ".csv");
      ++progress;
    }

    const matrix_type abs_effects = Math::Stats::GLM::abs_effect_size (data, design, contrast);
    save_matrix (mat2vec.V2M (abs_effects.col(0)), output_prefix + "_abs_effect.csv");
    ++progress;

    const matrix_type std_effects = Math::Stats::GLM::std_effect_size (data, design, contrast);
    matrix_type first_std_effect = mat2vec.V2M (std_effects.col (0));
    for (MR::Connectome::node_t i = 0; i != num_nodes; ++i) {
      for (MR::Connectome::node_t j = 0; j != num_nodes; ++j) {
        if (!std::isfinite (first_std_effect (i, j)))
          first_std_effect (i, j) = 0.0;
      }
    }
    save_matrix (first_std_effect, output_prefix + "_std_effect.csv");
    ++progress;

    const matrix_type stdevs = Math::Stats::GLM::stdev (data, design);
    save_vector (stdevs.col(0), output_prefix + "_std_dev.csv");
  }

  Math::Stats::GLMTTest glm_ttest (data, design, contrast);

  // If performing non-stationarity adjustment we need to pre-compute the empirical statistic
  vector_type empirical_statistic;
  if (do_nonstationary_adjustment) {
    empirical_statistic = vector_type::Zero (num_edges);
    if (permutations_nonstationary.size()) {
      Stats::PermTest::PermutationStack perm_stack (permutations_nonstationary, "precomputing empirical statistic for non-stationarity adjustment...");
      Stats::PermTest::precompute_empirical_stat (glm_ttest, enhancer, perm_stack, empirical_statistic);
    } else {
      Stats::PermTest::PermutationStack perm_stack (nperms_nonstationary, design.rows(), "precomputing empirical statistic for non-stationarity adjustment...", true);
      Stats::PermTest::precompute_empirical_stat (glm_ttest, enhancer, perm_stack, empirical_statistic);
    }
    save_matrix (mat2vec.V2M (empirical_statistic), output_prefix + "_empirical.csv");
  }

  // Precompute default statistic and enhanced statistic
  vector_type tvalue_output   (num_edges);
  vector_type enhanced_output (num_edges);

  Stats::PermTest::precompute_default_permutation (glm_ttest, enhancer, empirical_statistic, enhanced_output, std::shared_ptr<vector_type>(), tvalue_output);

  save_matrix (mat2vec.V2M (tvalue_output),   output_prefix + "_tvalue.csv");
  save_matrix (mat2vec.V2M (enhanced_output), output_prefix + "_enhanced.csv");

  // Perform permutation testing
  if (!get_options ("notest").size()) {

    // FIXME Getting NANs in the null distribution
    // Check: was result of pre-nulled subject data
    vector_type null_distribution (num_perms);
    vector_type uncorrected_pvalues (num_edges);

    if (permutations.size()) {
      Stats::PermTest::run_permutations (permutations, glm_ttest, enhancer, empirical_statistic,
                                         enhanced_output, std::shared_ptr<vector_type>(),
                                         null_distribution, std::shared_ptr<vector_type>(),
                                         uncorrected_pvalues, std::shared_ptr<vector_type>());
    } else {
      Stats::PermTest::run_permutations (num_perms, glm_ttest, enhancer, empirical_statistic,
                                         enhanced_output, std::shared_ptr<vector_type>(),
                                         null_distribution, std::shared_ptr<vector_type>(),
                                         uncorrected_pvalues, std::shared_ptr<vector_type>());
    }

    save_vector (null_distribution, output_prefix + "_null_dist.txt");
    vector_type pvalue_output (num_edges);
    Math::Stats::Permutation::statistic2pvalue (null_distribution, enhanced_output, pvalue_output);
    save_matrix (mat2vec.V2M (pvalue_output),       output_prefix + "_fwe_pvalue.csv");
    save_matrix (mat2vec.V2M (uncorrected_pvalues), output_prefix + "_uncorrected_pvalue.csv");

  }

}
<commit_msg>connectomestats: Fix stdev output<commit_after>/*
 * Copyright (c) 2008-2018 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/
 *
 * MRtrix3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * For more details, see http://www.mrtrix.org/
 */

#include "command.h"
#include "progressbar.h"
#include "types.h"

#include "file/path.h"
#include "math/stats/glm.h"
#include "math/stats/permutation.h"
#include "math/stats/typedefs.h"

#include "connectome/enhance.h"
#include "connectome/mat2vec.h"

#include "stats/permtest.h"

using namespace MR;
using namespace App;

const char* algorithms[] = { "nbs", "nbse", "none", nullptr };

// TODO Eventually these will move to some kind of TFCE header
#define TFCE_DH_DEFAULT 0.1
#define TFCE_E_DEFAULT 0.4
#define TFCE_H_DEFAULT 3.0

void usage ()
{
  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";

  SYNOPSIS = "Connectome group-wise statistics at the edge level using non-parametric permutation testing";

  ARGUMENTS
  + Argument ("input", "a text file listing the file names of the input connectomes").type_file_in ()

  + Argument ("algorithm", "the algorithm to use in network-based clustering/enhancement. "
                           "Options are: " + join(algorithms, ", ")).type_choice (algorithms)

  + Argument ("design", "the design matrix. Note that a column of 1's will need to be added for correlations.").type_file_in ()

  + Argument ("contrast", "the contrast vector, specified as a single row of weights").type_file_in ()

  + Argument ("output", "the filename prefix for all output.").type_text();

  OPTIONS

  + Stats::PermTest::Options (true)

  // TODO OptionGroup these, and provide a generic loader function
  + Stats::TFCE::Options (TFCE_DH_DEFAULT, TFCE_E_DEFAULT, TFCE_H_DEFAULT)

  + OptionGroup ("Additional options for connectomestats")

  + Option ("threshold", "the t-statistic value to use in threshold-based clustering algorithms")
  + Argument ("value").type_float (0.0);

  REFERENCES + "* If using the NBS algorithm: \n"
               "Zalesky, A.; Fornito, A. & Bullmore, E. T. Network-based statistic: Identifying differences in brain networks. \n"
               "NeuroImage, 2010, 53, 1197-1207"

             + "* If using the NBSE algorithm: \n"
               "Vinokur, L.; Zalesky, A.; Raffelt, D.; Smith, R.E. & Connelly, A. A Novel Threshold-Free Network-Based Statistics Method: Demonstration using Simulated Pathology. \n"
               "OHBM, 2015, 4144"

             + "* If using the -nonstationary option: \n"
               "Salimi-Khorshidi, G.; Smith, S.M. & Nichols, T.E. Adjusting the effect of nonstationarity in cluster-based and TFCE inference. \n"
               "Neuroimage, 2011, 54(3), 2006-19";

}

using Math::Stats::matrix_type;
using Math::Stats::vector_type;

void load_tfce_parameters (Stats::TFCE::Wrapper& enhancer)
{
  const default_type dH = get_option_value ("tfce_dh", TFCE_DH_DEFAULT);
  const default_type E  = get_option_value ("tfce_e", TFCE_E_DEFAULT);
  const default_type H  = get_option_value ("tfce_h", TFCE_H_DEFAULT);
  enhancer.set_tfce_parameters (dH, E, H);
}

void run()
{

  // Read filenames
  vector<std::string> filenames;
  {
    std::string folder = Path::dirname (argument[0]);
    std::ifstream ifs (argument[0].c_str());
    std::string temp;
    while (getline (ifs, temp)) {
      std::string filename (Path::join (folder, temp));
      size_t p = filename.find_last_not_of(" \t");
      if (std::string::npos != p)
        filename.erase(p+1);
      if (filename.size()) {
        if (!MR::Path::exists (filename))
          throw Exception ("Input connectome file not found: \"" + filename + "\"");
        filenames.push_back (filename);
      }
    }
  }

  const MR::Connectome::matrix_type example_connectome = load_matrix (filenames.front());
  if (example_connectome.rows() != example_connectome.cols())
    throw Exception ("Connectome of first subject is not square (" + str(example_connectome.rows()) + " x " + str(example_connectome.cols()) + ")");
  const MR::Connectome::node_t num_nodes = example_connectome.rows();

  // Initialise enhancement algorithm
  std::shared_ptr<Stats::EnhancerBase> enhancer;
  switch (int(argument[1])) {
    case 0: {
      auto opt = get_options ("threshold");
      if (!opt.size())
        throw Exception ("For NBS algorithm, -threshold option must be provided");
      enhancer.reset (new MR::Connectome::Enhance::NBS (num_nodes, opt[0][0]));
      }
      break;
    case 1: {
      std::shared_ptr<Stats::TFCE::EnhancerBase> base (new MR::Connectome::Enhance::NBS (num_nodes));
      enhancer.reset (new Stats::TFCE::Wrapper (base));
      load_tfce_parameters (*(dynamic_cast<Stats::TFCE::Wrapper*>(enhancer.get())));
      if (get_options ("threshold").size())
        WARN (std::string (argument[1]) + " is a threshold-free algorithm; -threshold option ignored");
      }
      break;
    case 2: {
      enhancer.reset (new MR::Connectome::Enhance::PassThrough());
      if (get_options ("threshold").size())
        WARN ("No enhancement algorithm being used; -threshold option ignored");
      }
      break;
    default:
      throw Exception ("Unknown enhancement algorithm");
  }

  size_t num_perms = get_option_value ("nperms", DEFAULT_NUMBER_PERMUTATIONS);
  const bool do_nonstationary_adjustment = get_options ("nonstationary").size();
  size_t nperms_nonstationary = get_option_value ("nperms_nonstationarity", DEFAULT_NUMBER_PERMUTATIONS_NONSTATIONARITY);

  // Load design matrix
  const matrix_type design = load_matrix (argument[2]);
  if (size_t(design.rows()) != filenames.size())
    throw Exception ("number of subjects does not match number of rows in design matrix");

  // Load permutations file if supplied
  auto opt = get_options("permutations");
  vector<vector<size_t> > permutations;
  if (opt.size()) {
    permutations = Math::Stats::Permutation::load_permutations_file (opt[0][0]);
    num_perms = permutations.size();
    if (permutations[0].size() != (size_t)design.rows())
      throw Exception ("number of rows in the permutations file (" + str(opt[0][0]) + ") does not match number of rows in design matrix");
  }

  // Load non-stationary correction permutations file if supplied
  opt = get_options("permutations_nonstationary");
  vector<vector<size_t> > permutations_nonstationary;
  if (opt.size()) {
    permutations_nonstationary = Math::Stats::Permutation::load_permutations_file (opt[0][0]);
    nperms_nonstationary = permutations.size();
    if (permutations_nonstationary[0].size() != (size_t)design.rows())
      throw Exception ("number of rows in the nonstationary permutations file (" + str(opt[0][0]) + ") does not match number of rows in design matrix");
  }

  // Load contrast matrix
  matrix_type contrast = load_matrix (argument[3]);
  if (contrast.cols() > design.cols())
    throw Exception ("too many contrasts for design matrix");
  contrast.conservativeResize (contrast.rows(), design.cols());

  const std::string output_prefix = argument[4];

  // Load input data
  // For compatibility with existing statistics code, symmetric matrix data is adjusted
  //   into vector form - one row per edge in the symmetric connectome. The Mat2Vec class
  //   deals with the re-ordering of matrix data into this form.
  MR::Connectome::Mat2Vec mat2vec (num_nodes);
  const size_t num_edges = mat2vec.vec_size();
  matrix_type data (num_edges, filenames.size());
  {
    ProgressBar progress ("Loading input connectome data", filenames.size());
    for (size_t subject = 0; subject < filenames.size(); subject++) {

      const std::string& path (filenames[subject]);
      MR::Connectome::matrix_type subject_data;
      try {
        subject_data = load_matrix (path);
      } catch (Exception& e) {
        throw Exception (e, "Error loading connectome data for subject #" + str(subject) + " (file \"" + path + "\"");
      }

      try {
        MR::Connectome::to_upper (subject_data);
        if (size_t(subject_data.rows()) != num_nodes)
          throw Exception ("Connectome matrix is not the correct size (" + str(subject_data.rows()) + ", should be " + str(num_nodes) + ")");
      } catch (Exception& e) {
        throw Exception (e, "Connectome for subject #" + str(subject) + " (file \"" + path + "\") invalid");
      }

      for (size_t i = 0; i != num_edges; ++i)
        data(i, subject) = subject_data (mat2vec(i).first, mat2vec(i).second);

      ++progress;
    }
  }

  {
    ProgressBar progress ("outputting beta coefficients, effect size and standard deviation...", contrast.cols() + 3);

    const matrix_type betas = Math::Stats::GLM::solve_betas (data, design);
    for (size_t i = 0; i < size_t(contrast.cols()); ++i) {
      save_matrix (mat2vec.V2M (betas.col(i)), output_prefix + "_beta_" + str(i) + ".csv");
      ++progress;
    }

    const matrix_type abs_effects = Math::Stats::GLM::abs_effect_size (data, design, contrast);
    save_matrix (mat2vec.V2M (abs_effects.col(0)), output_prefix + "_abs_effect.csv");
    ++progress;

    const matrix_type std_effects = Math::Stats::GLM::std_effect_size (data, design, contrast);
    matrix_type first_std_effect = mat2vec.V2M (std_effects.col (0));
    for (MR::Connectome::node_t i = 0; i != num_nodes; ++i) {
      for (MR::Connectome::node_t j = 0; j != num_nodes; ++j) {
        if (!std::isfinite (first_std_effect (i, j)))
          first_std_effect (i, j) = 0.0;
      }
    }
    save_matrix (first_std_effect, output_prefix + "_std_effect.csv");
    ++progress;

    const matrix_type stdev = Math::Stats::GLM::stdev (data, design);
    save_matrix (mat2vec.V2M(stdev.row(0)), output_prefix + "_std_dev.csv");
  }

  Math::Stats::GLMTTest glm_ttest (data, design, contrast);

  // If performing non-stationarity adjustment we need to pre-compute the empirical statistic
  vector_type empirical_statistic;
  if (do_nonstationary_adjustment) {
    empirical_statistic = vector_type::Zero (num_edges);
    if (permutations_nonstationary.size()) {
      Stats::PermTest::PermutationStack perm_stack (permutations_nonstationary, "precomputing empirical statistic for non-stationarity adjustment...");
      Stats::PermTest::precompute_empirical_stat (glm_ttest, enhancer, perm_stack, empirical_statistic);
    } else {
      Stats::PermTest::PermutationStack perm_stack (nperms_nonstationary, design.rows(), "precomputing empirical statistic for non-stationarity adjustment...", true);
      Stats::PermTest::precompute_empirical_stat (glm_ttest, enhancer, perm_stack, empirical_statistic);
    }
    save_matrix (mat2vec.V2M (empirical_statistic), output_prefix + "_empirical.csv");
  }

  // Precompute default statistic and enhanced statistic
  vector_type tvalue_output   (num_edges);
  vector_type enhanced_output (num_edges);

  Stats::PermTest::precompute_default_permutation (glm_ttest, enhancer, empirical_statistic, enhanced_output, std::shared_ptr<vector_type>(), tvalue_output);

  save_matrix (mat2vec.V2M (tvalue_output),   output_prefix + "_tvalue.csv");
  save_matrix (mat2vec.V2M (enhanced_output), output_prefix + "_enhanced.csv");

  // Perform permutation testing
  if (!get_options ("notest").size()) {

    // FIXME Getting NANs in the null distribution
    // Check: was result of pre-nulled subject data
    vector_type null_distribution (num_perms);
    vector_type uncorrected_pvalues (num_edges);

    if (permutations.size()) {
      Stats::PermTest::run_permutations (permutations, glm_ttest, enhancer, empirical_statistic,
                                         enhanced_output, std::shared_ptr<vector_type>(),
                                         null_distribution, std::shared_ptr<vector_type>(),
                                         uncorrected_pvalues, std::shared_ptr<vector_type>());
    } else {
      Stats::PermTest::run_permutations (num_perms, glm_ttest, enhancer, empirical_statistic,
                                         enhanced_output, std::shared_ptr<vector_type>(),
                                         null_distribution, std::shared_ptr<vector_type>(),
                                         uncorrected_pvalues, std::shared_ptr<vector_type>());
    }

    save_vector (null_distribution, output_prefix + "_null_dist.txt");
    vector_type pvalue_output (num_edges);
    Math::Stats::Permutation::statistic2pvalue (null_distribution, enhanced_output, pvalue_output);
    save_matrix (mat2vec.V2M (pvalue_output),       output_prefix + "_fwe_pvalue.csv");
    save_matrix (mat2vec.V2M (uncorrected_pvalues), output_prefix + "_uncorrected_pvalue.csv");

  }

}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. 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 OWNERff 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.
 *
 * $Id: pcl_base.cpp 34570 2010-12-06 19:01:39Z rusu $
 *
 */

/**

\author Radu Bogdan Rusu

**/

#include "pcl/pcl_base.h"

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** \brief Provide a pointer to the input dataset
  * \param cloud the const boost shared pointer to a PointCloud message
  */
void
pcl::PCLBase<sensor_msgs::PointCloud2>::setInputCloud (const PointCloud2ConstPtr &cloud)
{
  input_ = cloud;

  for (size_t d = 0; d < cloud->fields.size (); ++d)
  {
    if (cloud->fields[d].name == x_field_name_)
      x_idx_ = d;
    if (cloud->fields[d].name == y_field_name_)
      y_idx_ = d;
    if (cloud->fields[d].name == z_field_name_)
      z_idx_ = d;
  }

  // Obtain the size of all fields. Restrict to sizeof FLOAT32 for now
  field_sizes_.resize (input_->fields.size ());
  for (size_t d = 0; d < input_->fields.size (); ++d)
  {
    int fsize;
    switch (input_->fields[d].datatype)
    {
      case sensor_msgs::PointField::INT8:
      case sensor_msgs::PointField::UINT8:
        fsize = 1;

      case sensor_msgs::PointField::INT16:
      case sensor_msgs::PointField::UINT16:
        fsize = 2;

      case sensor_msgs::PointField::INT32:
      case sensor_msgs::PointField::UINT32:
      case sensor_msgs::PointField::FLOAT32:
        fsize = 4;

      case sensor_msgs::PointField::FLOAT64:
        fsize = 8;

      default:
        fsize = 0;
    }
    field_sizes_[d] = (std::min) (fsize, (int)sizeof (float));
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** \brief This method should get called after finishing the actual computation. */
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::deinitCompute ()
{
  // Reset the indices
  if (fake_indices_)
  {
    indices_.reset ();
    fake_indices_ = false;
  }
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** \brief This method should get called before starting the actual computation. */
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::initCompute ()
{
  // Check if input was set
  if (!input_)
    return (false);

  // If no point indices have been given, construct a set of indices for the entire input point cloud
  if (!indices_)
  {
    fake_indices_ = true;
    std::vector<int> *indices = new std::vector<int> (input_->width * input_->height);
    for (size_t i = 0; i < indices->size (); ++i) { (*indices)[i] = i; }
    indices_.reset (indices);
  }
  return (true);
}

<commit_msg>fixed a grave bug where the field sizes were incorrectly set<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. 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 OWNERff 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.
 *
 * $Id: pcl_base.cpp 34570 2010-12-06 19:01:39Z rusu $
 *
 */

/**

\author Radu Bogdan Rusu

**/

#include "pcl/pcl_base.h"

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::PCLBase<sensor_msgs::PointCloud2>::setInputCloud (const PointCloud2ConstPtr &cloud)
{
  input_ = cloud;

  for (size_t d = 0; d < cloud->fields.size (); ++d)
  {
    if (cloud->fields[d].name == x_field_name_)
      x_idx_ = d;
    if (cloud->fields[d].name == y_field_name_)
      y_idx_ = d;
    if (cloud->fields[d].name == z_field_name_)
      z_idx_ = d;
  }

  // Obtain the size of all fields. Restrict to sizeof FLOAT32 for now
  field_sizes_.resize (input_->fields.size ());
  for (size_t d = 0; d < input_->fields.size (); ++d)
  {
    int fsize;
    switch (input_->fields[d].datatype)
    {
      case sensor_msgs::PointField::INT8:
      case sensor_msgs::PointField::UINT8:
      {
        fsize = 1;
        break;
      }

      case sensor_msgs::PointField::INT16:
      case sensor_msgs::PointField::UINT16:
      {
        fsize = 2;
        break;
      }

      case sensor_msgs::PointField::INT32:
      case sensor_msgs::PointField::UINT32:
      case sensor_msgs::PointField::FLOAT32:
      {
        fsize = 4;
        break;
      }

      case sensor_msgs::PointField::FLOAT64:
      {
        fsize = 8;
        break;
      }

      default:
      {
        ROS_ERROR ("[PCLBase::setInputCloud] Invalid field type (%d)!", input_->fields[d].datatype);
        fsize = 0;
        break;
      }
    }
    field_sizes_[d] = (std::min) (fsize, (int)sizeof (float));
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::deinitCompute ()
{
  // Reset the indices
  if (fake_indices_)
  {
    indices_.reset ();
    fake_indices_ = false;
  }
  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::PCLBase<sensor_msgs::PointCloud2>::initCompute ()
{
  // Check if input was set
  if (!input_)
    return (false);

  // If no point indices have been given, construct a set of indices for the entire input point cloud
  if (!indices_)
  {
    fake_indices_ = true;
    std::vector<int> *indices = new std::vector<int> (input_->width * input_->height);
    for (size_t i = 0; i < indices->size (); ++i) { (*indices)[i] = i; }
    indices_.reset (indices);
  }
  return (true);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: TableRow.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2001-04-11 10:37:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBAUI_TABLEROW_HXX
#include "TableRow.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#include <algorithm>

using namespace dbaui;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//========================================================================
// class OTableRow
//========================================================================
DBG_NAME(OTableRow);
//------------------------------------------------------------------------------
OTableRow::OTableRow()
    :m_pActFieldDescr( NULL )
    ,m_nPos( -1 )
    ,m_bReadOnly( sal_False )
    ,m_bFirstNameModify( sal_True )
    ,m_bFirstDescrModify( sal_True )
    ,m_bOwnsDescriptions(sal_False)
{
    DBG_CTOR(OTableRow,NULL);
}
//------------------------------------------------------------------------------
OTableRow::OTableRow(const Reference< XPropertySet >& xAffectedCol)
    :m_pActFieldDescr( NULL )
    ,m_nPos( -1 )
    ,m_bReadOnly( sal_False )
    ,m_bFirstNameModify( sal_True )
    ,m_bFirstDescrModify( sal_True )
    ,m_bOwnsDescriptions(sal_True)
{
    DBG_CTOR(OTableRow,NULL);
    m_pActFieldDescr = new OFieldDescription(xAffectedCol);
}
//------------------------------------------------------------------------------
OTableRow::OTableRow( const OTableRow& rRow, long nPosition ) :
    m_nPos( nPosition )
    ,m_bReadOnly(rRow.IsReadOnly())
    ,m_bFirstNameModify(rRow.IsFirstNameModify())
    ,m_bFirstDescrModify(rRow.IsFirstDescrModify())
    ,m_pActFieldDescr(NULL)
    ,m_bOwnsDescriptions(sal_False)
{
    DBG_CTOR(OTableRow,NULL);

    OFieldDescription* pSrcField = rRow.GetActFieldDescr();
    if(pSrcField)
        m_pActFieldDescr = new OFieldDescription(*pSrcField);
}

//------------------------------------------------------------------------------
OTableRow::~OTableRow()
{
    if(m_bOwnsDescriptions)
        delete m_pActFieldDescr;
    DBG_DTOR(OTableRow,NULL);
}

//------------------------------------------------------------------------------
void OTableRow::SetPrimaryKey( sal_Bool bSet )
{
    DBG_CHKTHIS(OTableRow,NULL);
    if(m_pActFieldDescr)
        m_pActFieldDescr->SetPrimaryKey(bSet);
}
// -----------------------------------------------------------------------------
sal_Bool OTableRow::IsPrimaryKey() const
{
    DBG_CHKTHIS(OTableRow,NULL);
    return m_pActFieldDescr && m_pActFieldDescr->IsPrimaryKey();
}
// -----------------------------------------------------------------------------
void OTableRow::SetFieldType( const OTypeInfo* _pType )
{
    DBG_CHKTHIS(OTableRow,NULL);
    if(_pType)
    {
        if( !m_pActFieldDescr )
        {
            m_pActFieldDescr = new OFieldDescription();
            m_bOwnsDescriptions = sal_True;
            switch(_pType->nType)
            {
                case DataType::CHAR:
                case DataType::VARCHAR:
                    m_pActFieldDescr->SetPrecision(::std::min<sal_Int32>(sal_Int32(50),_pType->nPrecision));
                    break;
                default:
                    if(_pType->nPrecision && _pType->nMaximumScale)
                    {
                        m_pActFieldDescr->SetPrecision(5);
                        m_pActFieldDescr->SetScale(0);
                    }
                    else if(_pType->nPrecision)
                        m_pActFieldDescr->SetPrecision(::std::min<sal_Int32>(sal_Int32(16),_pType->nPrecision));
            }
        }
        // type checking
        if(m_pActFieldDescr->GetPrecision() > _pType->nPrecision)
            m_pActFieldDescr->SetPrecision(_pType->nPrecision);
        if(m_pActFieldDescr->GetScale() > _pType->nMaximumScale)
            m_pActFieldDescr->SetScale(0);
        if(!_pType->bNullable && m_pActFieldDescr->IsNullable())
            m_pActFieldDescr->SetIsNullable(ColumnValue::NO_NULLS);
        if(!_pType->bAutoIncrement && m_pActFieldDescr->IsAutoIncrement())
            m_pActFieldDescr->SetAutoIncrement(sal_False);

        m_pActFieldDescr->SetType(_pType);
    }
    else
    {
        delete m_pActFieldDescr;
        m_pActFieldDescr = NULL;
    }
}
// -----------------------------------------------------------------------------
namespace dbaui
{
    // -----------------------------------------------------------------------------
    SvStream& operator<<( SvStream& _rStr, const OTableRow& _rRow )
    {
        _rStr << _rRow.m_nPos;
        OFieldDescription* pFieldDesc = _rRow.GetActFieldDescr();
        if(pFieldDesc)
        {
            _rStr.WriteByteString(pFieldDesc->GetName());
            _rStr.WriteByteString(pFieldDesc->GetDescription());
            _rStr.WriteByteString(pFieldDesc->GetDefaultValue());

            _rStr << pFieldDesc->GetType();

            _rStr << pFieldDesc->GetPrecision();
            _rStr << pFieldDesc->GetScale();
            _rStr << pFieldDesc->GetIsNullable();
            _rStr << pFieldDesc->GetFormatKey();
            _rStr << (sal_Int32)pFieldDesc->GetHorJustify();
            _rStr << sal_Int32(pFieldDesc->IsAutoIncrement() ? 1 : 0);
            _rStr << sal_Int32(pFieldDesc->IsPrimaryKey() ? 1 : 0);
            _rStr << sal_Int32(pFieldDesc->IsCurrency() ? 1 : 0);
        }
        return _rStr;
    }
    // -----------------------------------------------------------------------------
    SvStream& operator>>( SvStream& _rStr, OTableRow& _rRow )
    {
        _rStr >> _rRow.m_nPos;

        OFieldDescription* pFieldDesc = new OFieldDescription();
        _rRow.m_pActFieldDescr = pFieldDesc;
        if(pFieldDesc)
        {
            String sValue;
            _rStr.ReadByteString(sValue);
            pFieldDesc->SetName(sValue);

            _rStr.ReadByteString(sValue);
            pFieldDesc->SetDescription(sValue);

            _rStr.ReadByteString(sValue);
            pFieldDesc->SetDefaultValue(sValue);

            sal_Int32 nValue;
            _rStr >> nValue;
            pFieldDesc->SetTypeValue(nValue);

            _rStr >> nValue;
            pFieldDesc->SetPrecision(nValue);
            _rStr >> nValue;
            pFieldDesc->SetScale(nValue);
            _rStr >> nValue;
            pFieldDesc->SetIsNullable(nValue);
            _rStr >> nValue;
            pFieldDesc->SetFormatKey(nValue);
            _rStr >> nValue;
            pFieldDesc->SetHorJustify((SvxCellHorJustify)nValue);

            _rStr >> nValue;
            pFieldDesc->SetAutoIncrement(nValue != 0);
            _rStr >> nValue;
            pFieldDesc->SetPrimaryKey(nValue != 0);
            _rStr >> nValue;
            pFieldDesc->SetCurrency(nValue != 0);
        }
        return _rStr;
    }
    // -----------------------------------------------------------------------------
}

<commit_msg>#87998# SetFieldType: set scale/precision if forced<commit_after>/*************************************************************************
 *
 *  $RCSfile: TableRow.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-12 09:59:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBAUI_TABLEROW_HXX
#include "TableRow.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#include <algorithm>

using namespace dbaui;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//========================================================================
// class OTableRow
//========================================================================
DBG_NAME(OTableRow);
//------------------------------------------------------------------------------
OTableRow::OTableRow()
    :m_pActFieldDescr( NULL )
    ,m_nPos( -1 )
    ,m_bReadOnly( sal_False )
    ,m_bFirstNameModify( sal_True )
    ,m_bFirstDescrModify( sal_True )
    ,m_bOwnsDescriptions(sal_False)
{
    DBG_CTOR(OTableRow,NULL);
}
//------------------------------------------------------------------------------
OTableRow::OTableRow(const Reference< XPropertySet >& xAffectedCol)
    :m_pActFieldDescr( NULL )
    ,m_nPos( -1 )
    ,m_bReadOnly( sal_False )
    ,m_bFirstNameModify( sal_True )
    ,m_bFirstDescrModify( sal_True )
    ,m_bOwnsDescriptions(sal_True)
{
    DBG_CTOR(OTableRow,NULL);
    m_pActFieldDescr = new OFieldDescription(xAffectedCol);
}
//------------------------------------------------------------------------------
OTableRow::OTableRow( const OTableRow& rRow, long nPosition ) :
    m_nPos( nPosition )
    ,m_bReadOnly(rRow.IsReadOnly())
    ,m_bFirstNameModify(rRow.IsFirstNameModify())
    ,m_bFirstDescrModify(rRow.IsFirstDescrModify())
    ,m_pActFieldDescr(NULL)
    ,m_bOwnsDescriptions(sal_False)
{
    DBG_CTOR(OTableRow,NULL);

    OFieldDescription* pSrcField = rRow.GetActFieldDescr();
    if(pSrcField)
        m_pActFieldDescr = new OFieldDescription(*pSrcField);
}

//------------------------------------------------------------------------------
OTableRow::~OTableRow()
{
    if(m_bOwnsDescriptions)
        delete m_pActFieldDescr;
    DBG_DTOR(OTableRow,NULL);
}

//------------------------------------------------------------------------------
void OTableRow::SetPrimaryKey( sal_Bool bSet )
{
    DBG_CHKTHIS(OTableRow,NULL);
    if(m_pActFieldDescr)
        m_pActFieldDescr->SetPrimaryKey(bSet);
}
// -----------------------------------------------------------------------------
sal_Bool OTableRow::IsPrimaryKey() const
{
    DBG_CHKTHIS(OTableRow,NULL);
    return m_pActFieldDescr && m_pActFieldDescr->IsPrimaryKey();
}
// -----------------------------------------------------------------------------
void OTableRow::SetFieldType( const OTypeInfo* _pType, sal_Bool _bForce )
{
    DBG_CHKTHIS(OTableRow,NULL);
    if(_pType)
    {
        if( !m_pActFieldDescr )
        {
            m_pActFieldDescr = new OFieldDescription();
            m_bOwnsDescriptions = sal_True;
            switch(_pType->nType)
            {
                case DataType::CHAR:
                case DataType::VARCHAR:
                    m_pActFieldDescr->SetPrecision(::std::min<sal_Int32>(sal_Int32(50),_pType->nPrecision));
                    break;
                default:
                    if(_pType->nPrecision && _pType->nMaximumScale)
                    {
                        m_pActFieldDescr->SetPrecision(5);
                        m_pActFieldDescr->SetScale(0);
                    }
                    else if(_pType->nPrecision)
                        m_pActFieldDescr->SetPrecision(::std::min<sal_Int32>(sal_Int32(16),_pType->nPrecision));
            }
        }

        // type checking
        if (_bForce || (m_pActFieldDescr->GetPrecision() > _pType->nPrecision))
            m_pActFieldDescr->SetPrecision(_pType->nPrecision);

        if (_bForce || (m_pActFieldDescr->GetScale() > _pType->nMaximumScale))
            m_pActFieldDescr->SetScale(_pType->nMinimumScale);

        if(!_pType->bNullable && m_pActFieldDescr->IsNullable())
            m_pActFieldDescr->SetIsNullable(ColumnValue::NO_NULLS);
        if(!_pType->bAutoIncrement && m_pActFieldDescr->IsAutoIncrement())
            m_pActFieldDescr->SetAutoIncrement(sal_False);

        m_pActFieldDescr->SetType(_pType);
    }
    else
    {
        delete m_pActFieldDescr;
        m_pActFieldDescr = NULL;
    }
}
// -----------------------------------------------------------------------------
namespace dbaui
{
    // -----------------------------------------------------------------------------
    SvStream& operator<<( SvStream& _rStr, const OTableRow& _rRow )
    {
        _rStr << _rRow.m_nPos;
        OFieldDescription* pFieldDesc = _rRow.GetActFieldDescr();
        if(pFieldDesc)
        {
            _rStr.WriteByteString(pFieldDesc->GetName());
            _rStr.WriteByteString(pFieldDesc->GetDescription());
            _rStr.WriteByteString(pFieldDesc->GetDefaultValue());

            _rStr << pFieldDesc->GetType();

            _rStr << pFieldDesc->GetPrecision();
            _rStr << pFieldDesc->GetScale();
            _rStr << pFieldDesc->GetIsNullable();
            _rStr << pFieldDesc->GetFormatKey();
            _rStr << (sal_Int32)pFieldDesc->GetHorJustify();
            _rStr << sal_Int32(pFieldDesc->IsAutoIncrement() ? 1 : 0);
            _rStr << sal_Int32(pFieldDesc->IsPrimaryKey() ? 1 : 0);
            _rStr << sal_Int32(pFieldDesc->IsCurrency() ? 1 : 0);
        }
        return _rStr;
    }
    // -----------------------------------------------------------------------------
    SvStream& operator>>( SvStream& _rStr, OTableRow& _rRow )
    {
        _rStr >> _rRow.m_nPos;

        OFieldDescription* pFieldDesc = new OFieldDescription();
        _rRow.m_pActFieldDescr = pFieldDesc;
        if(pFieldDesc)
        {
            String sValue;
            _rStr.ReadByteString(sValue);
            pFieldDesc->SetName(sValue);

            _rStr.ReadByteString(sValue);
            pFieldDesc->SetDescription(sValue);

            _rStr.ReadByteString(sValue);
            pFieldDesc->SetDefaultValue(sValue);

            sal_Int32 nValue;
            _rStr >> nValue;
            pFieldDesc->SetTypeValue(nValue);

            _rStr >> nValue;
            pFieldDesc->SetPrecision(nValue);
            _rStr >> nValue;
            pFieldDesc->SetScale(nValue);
            _rStr >> nValue;
            pFieldDesc->SetIsNullable(nValue);
            _rStr >> nValue;
            pFieldDesc->SetFormatKey(nValue);
            _rStr >> nValue;
            pFieldDesc->SetHorJustify((SvxCellHorJustify)nValue);

            _rStr >> nValue;
            pFieldDesc->SetAutoIncrement(nValue != 0);
            _rStr >> nValue;
            pFieldDesc->SetPrimaryKey(nValue != 0);
            _rStr >> nValue;
            pFieldDesc->SetCurrency(nValue != 0);
        }
        return _rStr;
    }
    // -----------------------------------------------------------------------------
}

<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/parameter_handler.h>
#include <base/logstream.h>
#include <lac/vector_memory.h>

#include <numerics/operator.templates.h>
#include <numerics/newton.templates.h>
#include <numerics/theta_timestepping.templates.h>

#include <lac/vector.h>
#include <lac/block_vector.h>
#include <lac/petsc_vector.h>
#include <lac/petsc_block_vector.h>
#include <lac/trilinos_vector.h>
#include <lac/trilinos_block_vector.h>

DEAL_II_NAMESPACE_OPEN

using namespace Algorithms;

#include "operator.inst"

DEAL_II_NAMESPACE_CLOSE
<commit_msg>Explicit instantiations need to be qualified or in the proper namespace. Using declarations may not be enough.<commit_after>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/parameter_handler.h>
#include <base/logstream.h>
#include <lac/vector_memory.h>

#include <numerics/operator.templates.h>
#include <numerics/newton.templates.h>
#include <numerics/theta_timestepping.templates.h>

#include <lac/vector.h>
#include <lac/block_vector.h>
#include <lac/petsc_vector.h>
#include <lac/petsc_block_vector.h>
#include <lac/trilinos_vector.h>
#include <lac/trilinos_block_vector.h>

DEAL_II_NAMESPACE_OPEN

namespace Algorithms
{
#include "operator.inst"
}

DEAL_II_NAMESPACE_CLOSE
<|endoftext|>


<commit_before>#include "Animation_Holiday.hpp"

/* ~~~ Animation Holiday Halloween: Basic Orange/Purple Fade (All Windows) ~~~ */

void Animation_Holiday_Halloween_WinAllFade::init() {
 	Animation_Holiday::init();
 	this->name = F("Window[all]: Basic Halloween Fade");
    this->update_rate = 5;
	this->num_strips = 3;
 	this->strips = WINDOW_ALL;

	this->stack = new LocalStack();
	this->stack->push(new MemObj(new unsigned short int(0)));
	this->stack->push(new MemObj(new bool(true)));
}

void Animation_Holiday_Halloween_WinAllFade::step() {
	unsigned short int& i = this->stack->get(0)->get<unsigned short int>();
	bool& increasing = this->stack->get(1)->get<bool>();

    for (int x = 0; x < WINDOW_LENGTH; x++) {
    	window1.setPixelColor(x, window_generic.Color(i, (int)(((float)i / 255.0) * 50), 0));
        window2.setPixelColor(x, window_generic.Color((int)(((float)i / 255.0) * 150), 0, i));
        window3.setPixelColor(x, window_generic.Color(i, (int)(((float)i / 255.0) * 50), 0));
    }

    showAllWindowStrips();

    if (increasing) {
        if (i == 255) {
            i--;
            increasing = false;
        } else {
            i++;
        }
    } else {
        if (i == 0) {
            i++;
            increasing = true;
      		this->current_exec++;
        } else {
            i--;
        }
    }
}

void Animation_Holiday_Halloween_WinAllFade::clean() {
	this->stack->get(0)->destroy<unsigned short int>();
	this->stack->get(1)->destroy<bool>();

	delete this->stack;
}

/* ~~~ Animation Holiday Halloween: Randomized Sparkle Effect (All Windows) ~~~ */

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::init() {
 	Animation_Holiday::init();
 	this->name = F("Window[all]: Halloween Sparkle Fade");
    this->update_rate = 1000;
	this->num_strips = 3;
 	this->strips = WINDOW_ALL;

	this->stack = new LocalStack();
	this->stack->push(new MemObj(new unsigned int(0)));
	this->stack->push(new MemObj(new bool(true)));
	this->stack->push(new MemObj(new bool[WINDOW_LENGTH * 3] {false}));
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::step() {
	unsigned int& i = this->stack->get(0)->get<unsigned int>();
	bool& reset = this->stack->get(1)->get<bool>();
	bool*& increasing = this->stack->get(2)->get<bool*>();

	if (reset) {
		// randomize
		for (int x = 0; x < WINDOW_LENGTH; x++) {
			window1.setPixelColor(x, this->rand_halloween_color());
			window2.setPixelColor(x, this->rand_halloween_color());
			window3.setPixelColor(x, this->rand_halloween_color());
		}

		reset = false;
	} else {
		// fade for a bit
		this->sparkle_fade(increasing);

		i++;

		if (i == 256) {
			i = 0;
			reset = true;
      		this->current_exec++;
		}
	}

	showAllWindowStrips();

	Serial.println("heartbeat");
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::clean() {
	this->stack->get(0)->destroy<unsigned int>();
	this->stack->get(1)->destroy<unsigned short int>();
	bool* arr = this->stack->get(2)->get<bool[WINDOW_LENGTH * 3]>();
	delete [] arr;

	delete this->stack;
}

unsigned long int Animation_Holiday_Halloween_WinAllHalloweenSparkle::rand_halloween_color() {
	unsigned long int bright_orange = window_generic.Color(255, 50, 0);
	unsigned long int medium_orange = window_generic.Color(190, 37, 0);
	unsigned long int dim_orange = window_generic.Color(100, 20, 0);

	unsigned long int bright_purple = window_generic.Color(150, 0, 255);
	unsigned long int medium_purple = window_generic.Color(112, 0, 190);
	unsigned long int dim_purple = window_generic.Color(59, 0, 100);

	long int r = random(0,7);

	switch(r) {
		case 0:
			return COLOR_OFF;
		case 1:
			return bright_orange;
		case 2:
			return medium_orange;
		case 3:
			return dim_orange;
		case 4:
			return bright_purple;
		case 5:
			return medium_purple;
		case 6:
			return dim_purple;
		default:
			return COLOR_OFF;
	}
}

unsigned int Animation_Holiday_Halloween_WinAllHalloweenSparkle::floor_0(float x) {
	if (x <= 0.0) {
		// handle cases below 0
		return (unsigned int) 0;
	} else {
		// this will not be negative ever
		return (unsigned int) floor(x);
	}
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::sparkle_fade(bool*& inc) {
	const float ORANGE_R_SLOPE = 1.0;
	const float ORANGE_G_SLOPE = 0.196078;
	const float PURPLE_R_SLOPE = 0.588235;
	const float PURPLE_B_SLOPE = 1.0;

	Adafruit_NeoPixel* temp_win;

	// fade with absolute value since so many different values
	for (int x = 0; x < WINDOW_LENGTH * 3; x++) {
		int pixel = 0;

		if (x < WINDOW_LENGTH) {
			temp_win = &window1;
			pixel = x;
		} else if (x < WINDOW_LENGTH * 2) {
			temp_win = &window2;
			pixel = x - WINDOW_LENGTH;
		} else {
			temp_win = &window3;
			pixel = x - WINDOW_LENGTH * 2;
		}

		Adafruit_NeoPixel& win = *temp_win;

		unsigned long int color = win.getPixelColor(pixel);

		unsigned int red = redFromColor(color);
		unsigned int green = greenFromColor(color);
		unsigned int blue = blueFromColor(color);

		bool increasing = inc[x];

		// now check each value to see if one is zero (acts as a data bit indicating which color is being displayed)
		// if green is 0, purple is being displayed
		// if blue is 0, orange is being displayed
		// if red is 0, black (off) is being displayed

		if (red == 0) {
			// is off, randomly pick a color
			int r = random(0,2);

			if (increasing) {
				increasing = false;
			} else {
				increasing = true;
			}

			Serial.println(r);
			Serial.println(pixel);

			if (r == 0) {
				// purple
				win.setPixelColor(pixel, window_generic.Color(1,0,2));
			} else {
				// orange
				win.setPixelColor(pixel, window_generic.Color(5,1,0));
			}
		} else if (green == 0) {
			// was purple
			if (increasing) {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red + PURPLE_R_SLOPE), 0, floor_0((float)blue + PURPLE_B_SLOPE)));
			} else {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red - PURPLE_R_SLOPE), 0, floor_0((float)blue - PURPLE_B_SLOPE)));
			}
		} else if (blue == 0) {
			// was orange
			if (increasing) {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red + ORANGE_R_SLOPE), floor_0((float)green + ORANGE_G_SLOPE), 0));
			} else {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red - ORANGE_R_SLOPE), floor_0((float)green - ORANGE_G_SLOPE), 0));
			}
		}

		inc[x] = increasing;
	}
}
<commit_msg>unnecesary space<commit_after>#include "Animation_Holiday.hpp"

/* ~~~ Animation Holiday Halloween: Basic Orange/Purple Fade (All Windows) ~~~ */

void Animation_Holiday_Halloween_WinAllFade::init() {
 	Animation_Holiday::init();
 	this->name = F("Window[all]: Basic Halloween Fade");
    this->update_rate = 5;
	this->num_strips = 3;
 	this->strips = WINDOW_ALL;

	this->stack = new LocalStack();
	this->stack->push(new MemObj(new unsigned short int(0)));
	this->stack->push(new MemObj(new bool(true)));
}

void Animation_Holiday_Halloween_WinAllFade::step() {
	unsigned short int& i = this->stack->get(0)->get<unsigned short int>();
	bool& increasing = this->stack->get(1)->get<bool>();

    for (int x = 0; x < WINDOW_LENGTH; x++) {
    	window1.setPixelColor(x, window_generic.Color(i, (int)(((float)i / 255.0) * 50), 0));
        window2.setPixelColor(x, window_generic.Color((int)(((float)i / 255.0) * 150), 0, i));
        window3.setPixelColor(x, window_generic.Color(i, (int)(((float)i / 255.0) * 50), 0));
    }

    showAllWindowStrips();

    if (increasing) {
        if (i == 255) {
            i--;
            increasing = false;
        } else {
            i++;
        }
    } else {
        if (i == 0) {
            i++;
            increasing = true;
      		this->current_exec++;
        } else {
            i--;
        }
    }
}

void Animation_Holiday_Halloween_WinAllFade::clean() {
	this->stack->get(0)->destroy<unsigned short int>();
	this->stack->get(1)->destroy<bool>();

	delete this->stack;
}

/* ~~~ Animation Holiday Halloween: Randomized Sparkle Effect (All Windows) ~~~ */

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::init() {
 	Animation_Holiday::init();
 	this->name = F("Window[all]: Halloween Sparkle Fade");
    this->update_rate = 1000;
	this->num_strips = 3;
 	this->strips = WINDOW_ALL;

	this->stack = new LocalStack();
	this->stack->push(new MemObj(new unsigned int(0)));
	this->stack->push(new MemObj(new bool(true)));
	this->stack->push(new MemObj(new bool[WINDOW_LENGTH * 3] {false}));
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::step() {
	unsigned int& i = this->stack->get(0)->get<unsigned int>();
	bool& reset = this->stack->get(1)->get<bool>();
	bool*& increasing = this->stack->get(2)->get<bool*>();

	if (reset) {
		// randomize
		for (int x = 0; x < WINDOW_LENGTH; x++) {
			window1.setPixelColor(x, this->rand_halloween_color());
			window2.setPixelColor(x, this->rand_halloween_color());
			window3.setPixelColor(x, this->rand_halloween_color());
		}

		reset = false;
	} else {
		// fade for a bit
		this->sparkle_fade(increasing);

		i++;

		if (i == 256) {
			i = 0;
			reset = true;
      		this->current_exec++;
		}
	}

	showAllWindowStrips();

	Serial.println("heartbeat");
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::clean() {
	this->stack->get(0)->destroy<unsigned int>();
	this->stack->get(1)->destroy<unsigned short int>();
	bool* arr = this->stack->get(2)->get<bool[WINDOW_LENGTH * 3]>();
	delete[] arr;

	delete this->stack;
}

unsigned long int Animation_Holiday_Halloween_WinAllHalloweenSparkle::rand_halloween_color() {
	unsigned long int bright_orange = window_generic.Color(255, 50, 0);
	unsigned long int medium_orange = window_generic.Color(190, 37, 0);
	unsigned long int dim_orange = window_generic.Color(100, 20, 0);

	unsigned long int bright_purple = window_generic.Color(150, 0, 255);
	unsigned long int medium_purple = window_generic.Color(112, 0, 190);
	unsigned long int dim_purple = window_generic.Color(59, 0, 100);

	long int r = random(0,7);

	switch(r) {
		case 0:
			return COLOR_OFF;
		case 1:
			return bright_orange;
		case 2:
			return medium_orange;
		case 3:
			return dim_orange;
		case 4:
			return bright_purple;
		case 5:
			return medium_purple;
		case 6:
			return dim_purple;
		default:
			return COLOR_OFF;
	}
}

unsigned int Animation_Holiday_Halloween_WinAllHalloweenSparkle::floor_0(float x) {
	if (x <= 0.0) {
		// handle cases below 0
		return (unsigned int) 0;
	} else {
		// this will not be negative ever
		return (unsigned int) floor(x);
	}
}

void Animation_Holiday_Halloween_WinAllHalloweenSparkle::sparkle_fade(bool*& inc) {
	const float ORANGE_R_SLOPE = 1.0;
	const float ORANGE_G_SLOPE = 0.196078;
	const float PURPLE_R_SLOPE = 0.588235;
	const float PURPLE_B_SLOPE = 1.0;

	Adafruit_NeoPixel* temp_win;

	// fade with absolute value since so many different values
	for (int x = 0; x < WINDOW_LENGTH * 3; x++) {
		int pixel = 0;

		if (x < WINDOW_LENGTH) {
			temp_win = &window1;
			pixel = x;
		} else if (x < WINDOW_LENGTH * 2) {
			temp_win = &window2;
			pixel = x - WINDOW_LENGTH;
		} else {
			temp_win = &window3;
			pixel = x - WINDOW_LENGTH * 2;
		}

		Adafruit_NeoPixel& win = *temp_win;

		unsigned long int color = win.getPixelColor(pixel);

		unsigned int red = redFromColor(color);
		unsigned int green = greenFromColor(color);
		unsigned int blue = blueFromColor(color);

		bool increasing = inc[x];

		// now check each value to see if one is zero (acts as a data bit indicating which color is being displayed)
		// if green is 0, purple is being displayed
		// if blue is 0, orange is being displayed
		// if red is 0, black (off) is being displayed

		if (red == 0) {
			// is off, randomly pick a color
			int r = random(0,2);

			if (increasing) {
				increasing = false;
			} else {
				increasing = true;
			}

			Serial.println(r);
			Serial.println(pixel);

			if (r == 0) {
				// purple
				win.setPixelColor(pixel, window_generic.Color(1,0,2));
			} else {
				// orange
				win.setPixelColor(pixel, window_generic.Color(5,1,0));
			}
		} else if (green == 0) {
			// was purple
			if (increasing) {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red + PURPLE_R_SLOPE), 0, floor_0((float)blue + PURPLE_B_SLOPE)));
			} else {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red - PURPLE_R_SLOPE), 0, floor_0((float)blue - PURPLE_B_SLOPE)));
			}
		} else if (blue == 0) {
			// was orange
			if (increasing) {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red + ORANGE_R_SLOPE), floor_0((float)green + ORANGE_G_SLOPE), 0));
			} else {
				//win.setPixelColor(pixel, window_generic.Color(floor_0((float)red - ORANGE_R_SLOPE), floor_0((float)green - ORANGE_G_SLOPE), 0));
			}
		}

		inc[x] = increasing;
	}
}
<|endoftext|>


<commit_before>/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/

#include <vigra/matlab.hxx>
#include <vigra/labelimage.hxx>
#include <vigra/labelvolume.hxx>
#include <vigra/matlab_FLEXTYPE.hxx>

//this could be a typedef but if you want outType to be the same type as inType then you can just
//set outType to T

using namespace vigra;
using namespace matlab;

#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){

    /***************************************************************************************************
    **              INIT PART                                                                         **
    ***************************************************************************************************/
    typedef UInt32 OutputType;
    MultiArrayView<3,T>     in3D        =       inputs.getMultiArray<3,T>(0, v_required());
    MultiArrayView<3,OutputType>     out3D        =       inputs.getMultiArray<3,OutputType>("output", v_required());
    BasicImageView<T>       in          =       makeBasicImageView(in3D.bindOuter(0));
    Int32                     numOfDim    =       inputs.getDimOfInput(0, v_required());

    Int32                     v2Dconn[2]  =       {8, 4};
    Int32                     v3Dconn[2]  =       {26, 6};
    Int32                     connectivity=       inputs.getScalarVals2D3D<Int32>("conn", v_default(8,26,numOfDim),
                                                                                v2Dconn, v2Dconn+2,
                                                                                v3Dconn, v3Dconn+2,
                                                                                numOfDim);
    /*{
        if(numOfDim == 2 && connectivity!= 8 && connectivity != 4)
            mexErrMsgTxt("Connectivity for 2D data must be 8 or 4");
        else if(numOfDim == 3 && connectivity!= 26 && connectivity != 6)
            mexErrMsgTxt("Connectivity for 3D data must be 26 or 6");
    }*/

    bool                    hasBackground;
    T                       backgroundValue = inputs.getScalar<T>("backgroundValue", v_optional(hasBackground));

    //MultiArrayView<3,OutputType>     out3D           = outputs.createMultiArray      <3,OutputType>   (0, v_required(), in3D.shape());
    BasicImageView<OutputType>       out(out3D.data(), in3D.shape(0), in3D.shape(1));

    Int32                     max_region_label = (hasBackground == true)? 1: 0;

    /***************************************************************************************************
    **              CODE PART                                                                         **
    ****************************************************************************************************/
    #ifdef RN_DEBUG
    mexPrintf("---%d---%d---%d---", max_region_label, numOfDim, connectivity);
    #endif
    switch(cantorPair(hasBackground , numOfDim, connectivity)){
        //cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
        //Code is basically the code on the VIGRA-reference page
        case cP3_(0, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 8");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), true);
            break;
        case cP3_(0, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 4");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), false);
            break;
        case cP3_(0, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 26");
            #endif
            max_region_label = labelVolumeSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
            break;
        case cP3_(0, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 6");
            #endif
            max_region_label = labelVolume(srcMultiArrayRange(in3D), destMultiArray(out3D), NeighborCode3DTwentySix());
            break;
        case cP3_(1, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 8");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), true, backgroundValue);
            break;
        case cP3_(1, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 4");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), false, backgroundValue);
            break;
        case cP3_(1, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 26");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DSix(), backgroundValue);
            break;
        case cP3_(1, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 6");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DTwentySix(), backgroundValue);
            #ifdef RN_DEBUG
            mexWarnMsgTxt("DONE");
            #endif
            break;
        default:
            mexErrMsgTxt("Something went wrong");
    }

    #ifdef RN_DEBUG
    mexWarnMsgTxt("Out of Switch");
    #endif
    outputs.createScalar<int> (1, v_optional(), max_region_label);
}

/***************************************************************************************************
**           VIGRA GATEWAY                                                                        **
****************************************************************************************************/
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
    /*
    FLEXIBLE_TYPE_START(0, in);
        ALLOW_D;
    FLEXIBLE_TYPE_END;
    */

    //mxClassID inClass;
    //FLEX_TYPE(inClass, 0, in);
    switch(inputs.typeOf(0))
    {
        ALLOW_FD
	ALLOW_UINT_8_64
	ALLOW_INT_8_64
        default:
	    mexErrMsgTxt("Type of input 0 not supported");
    }
}

/*+++++++++++++++++++++++MexEntryFunc++++++++++++++++++++++++++++++++*/
/* Gatewayfunction - see matlab.hxx for details.
/* if a certain class is NOT supported - you will have to copy the
/* body of the callMexFunctor function and edit it here.
/* Supports (u)int[8|16|32|64], float and double.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/** MATLAB
function D = vigraConnectedComponents(inputArray)
function D = vigraConnectedComponents(inputArray, options);

D = vigraConnectedComponents(inputArray) performs connected components labeling
        using the default options.
D = vigraConnectedComponents(inputImage, options)  does the same with user options.

inputArray - a 2D or 3D array of numeric type

options    - is a struct with the following possible fields:
    'conn':            The neighborhood to be used
                       2D: 4 (default) or  8
                       3D: 6 (default) or 26
    'backgroundValue': Specify the value of a background region not to be labeled (will be labeled 0
                       in the result array, even when it doesn't form a single connected component).
                       If this option in not present, the entire image/volume will be labeled.

Usage:
    opt = struct('conn', 8);
    out = vigraConnectedComponents(in, opt);

*/
<commit_msg>boundscheck used in vigra COnnected Components<commit_after>/*++++++++++++++++++++INCLUDES+and+Definitions++++++++++++++++++++++++*/

#define VIGRA_CHECK_BOUNDS
#include <vigra/matlab.hxx>
#include <vigra/labelimage.hxx>
#include <vigra/labelvolume.hxx>
#include <vigra/matlab_FLEXTYPE.hxx>

//this could be a typedef but if you want outType to be the same type as inType then you can just
//set outType to T

using namespace vigra;
using namespace matlab;

#define RN_DEBUG
#define cP3_(a, b , c) cP3<a, b, c>::value
template <class T>
void vigraMain(matlab::OutputArray outputs, matlab::InputArray inputs){

    /***************************************************************************************************
    **              INIT PART                                                                         **
    ***************************************************************************************************/
    typedef UInt32 OutputType;
    MultiArrayView<3,T>     in3D        =       inputs.getMultiArray<3,T>(0, v_required());
    MultiArrayView<3,OutputType>     out3D        =       inputs.getMultiArray<3,OutputType>("output", v_required());
    BasicImageView<T>       in          =       makeBasicImageView(in3D.bindOuter(0));
    Int32                     numOfDim    =       inputs.getDimOfInput(0, v_required());

    Int32                     v2Dconn[2]  =       {8, 4};
    Int32                     v3Dconn[2]  =       {26, 6};
    Int32                     connectivity=       inputs.getScalarVals2D3D<Int32>("conn", v_default(8,26,numOfDim),
                                                                                v2Dconn, v2Dconn+2,
                                                                                v3Dconn, v3Dconn+2,
                                                                                numOfDim);
    /*{
        if(numOfDim == 2 && connectivity!= 8 && connectivity != 4)
            mexErrMsgTxt("Connectivity for 2D data must be 8 or 4");
        else if(numOfDim == 3 && connectivity!= 26 && connectivity != 6)
            mexErrMsgTxt("Connectivity for 3D data must be 26 or 6");
    }*/

    bool                    hasBackground;
    T                       backgroundValue = inputs.getScalar<T>("backgroundValue", v_optional(hasBackground));

    //MultiArrayView<3,OutputType>     out3D           = outputs.createMultiArray      <3,OutputType>   (0, v_required(), in3D.shape());
    BasicImageView<OutputType>       out(out3D.data(), in3D.shape(0), in3D.shape(1));

    Int32                     max_region_label = (hasBackground == true)? 1: 0;

    /***************************************************************************************************
    **              CODE PART                                                                         **
    ****************************************************************************************************/
    #ifdef RN_DEBUG
    mexPrintf("---%d---%d---%d---", max_region_label, numOfDim, connectivity);
    #endif
    switch(cantorPair(hasBackground , numOfDim, connectivity)){
        //cP is the templated version o f the cantorPair function first value is Dimension of Inputimage, second the connectivity setting
        //Code is basically the code on the VIGRA-reference page
        case cP3_(0, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 8");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), true);
            break;
        case cP3_(0, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, IMAG, 4");
            #endif
            max_region_label = labelImage(srcImageRange(in), destImage(out), false);
            break;
        case cP3_(0, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 26");
            #endif
            max_region_label = labelVolumeSix(srcMultiArrayRange(in3D), destMultiArray(out3D));
            break;
        case cP3_(0, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("0, VOLUME, 6");
            #endif
            max_region_label = labelVolume(srcMultiArrayRange(in3D), destMultiArray(out3D), NeighborCode3DTwentySix());
            break;
        case cP3_(1, IMAG, 8):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 8");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), true, backgroundValue);
            break;
        case cP3_(1, IMAG, 4):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, IMAG, 4");
            #endif
            max_region_label = labelImageWithBackground(srcImageRange(in), destImage(out), false, backgroundValue);
            break;
        case cP3_(1, VOLUME, 26):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 26");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DSix(), backgroundValue);
            break;
        case cP3_(1, VOLUME, 6):
            #ifdef RN_DEBUG
            mexWarnMsgTxt("1, VOLUME, 6");
            #endif
            max_region_label = labelVolumeWithBackground(srcMultiArrayRange(in3D), destMultiArray(out3D),
                                                                                NeighborCode3DTwentySix(), backgroundValue);
            #ifdef RN_DEBUG
            mexWarnMsgTxt("DONE");
            #endif
            break;
        default:
            mexErrMsgTxt("Something went wrong");
    }

    #ifdef RN_DEBUG
    mexWarnMsgTxt("Out of Switch");
    #endif
    outputs.createScalar<int> (1, v_optional(), max_region_label);
}

/***************************************************************************************************
**           VIGRA GATEWAY                                                                        **
****************************************************************************************************/
void vigraMexFunction(vigra::matlab::OutputArray outputs, vigra::matlab::InputArray inputs)
{
    /*
    FLEXIBLE_TYPE_START(0, in);
        ALLOW_D;
    FLEXIBLE_TYPE_END;
    */

    //mxClassID inClass;
    //FLEX_TYPE(inClass, 0, in);
    switch(inputs.typeOf(0))
    {
        ALLOW_FD
	ALLOW_UINT_8_64
	ALLOW_INT_8_64
        default:
	    mexErrMsgTxt("Type of input 0 not supported");
    }
}

/*+++++++++++++++++++++++MexEntryFunc++++++++++++++++++++++++++++++++*/
/* Gatewayfunction - see matlab.hxx for details.
/* if a certain class is NOT supported - you will have to copy the
/* body of the callMexFunctor function and edit it here.
/* Supports (u)int[8|16|32|64], float and double.
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/** MATLAB
function D = vigraConnectedComponents(inputArray)
function D = vigraConnectedComponents(inputArray, options);

D = vigraConnectedComponents(inputArray) performs connected components labeling
        using the default options.
D = vigraConnectedComponents(inputImage, options)  does the same with user options.

inputArray - a 2D or 3D array of numeric type

options    - is a struct with the following possible fields:
    'conn':            The neighborhood to be used
                       2D: 4 (default) or  8
                       3D: 6 (default) or 26
    'backgroundValue': Specify the value of a background region not to be labeled (will be labeled 0
                       in the result array, even when it doesn't form a single connected component).
                       If this option in not present, the entire image/volume will be labeled.

Usage:
    opt = struct('conn', 8);
    out = vigraConnectedComponents(in, opt);

*/
<|endoftext|>


<commit_before>#include "core/global.h"
#include "MessageDirector.h"
#include "core/config.h"
#include "core/global.h"
#include "MDNetworkParticipant.h"
#include <boost/bind.hpp>
using boost::asio::ip::tcp; // I don't want to type all of that god damned shit
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");
ConfigVariable<std::string> connect_addr("messagedirector/connect", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
			std::string str_ip = bind_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_acceptor = new tcp::acceptor(io_service, *it, true);
			start_accept();
		}
		if(connect_addr.get_val() != "unspecified")
		{
			std::string str_ip = connect_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_remote_md = new tcp::socket(io_service);
			boost::system::error_code ec;
			m_remote_md->connect(*it, ec);
			if(ec.value() != 0)
			{
				gLogger->fatal() << "Could not connect to remote MD at IP: "
					<< connect_addr.get_val() << " With error code: "
					<< ec.value() << "(" << ec.category().message(ec.value()) << ")"
					<< std::endl;
				exit(1);
			}
		}
	}
}

void MessageDirector::handle_datagram(Datagram *dg, MDParticipantInterface *participant)
{
	DatagramIterator dgi(dg);
	unsigned char channels = dgi.read_uint8();
	if(channels == 1)
	{
		unsigned long long channel = dgi.read_uint64();
		if(channel == CONTROL_MESSAGE)
		{
			unsigned int msg_type = dgi.read_uint16();
			switch(msg_type)
			{
			}
			return;
		}
		else
		{
			dgi.seek(1);
		}
	}
	//TODO: loop through channels & route crap.
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false), m_remote_md(NULL)
{
}

void MessageDirector::start_accept()
{
	tcp::socket *socket = new tcp::socket(io_service);
	tcp::endpoint peerEndpoint;
	m_acceptor->async_accept(*socket, boost::bind(&MessageDirector::handle_accept,
		this, socket, boost::asio::placeholders::error));
}

void MessageDirector::handle_accept(tcp::socket *socket, const boost::system::error_code &ec)
{
	boost::asio::ip::tcp::endpoint remote = socket->remote_endpoint();
	gLogger->info() << "Got a Message Director connection from "
	                << remote.address() << ":" << remote.port() << std::endl;
	new MDNetworkParticipant(socket); //It deletes itsself when connection is lost
	start_accept();
}
<commit_msg>Implemented CONTROL_SET_CHANNEL<commit_after>#include "core/global.h"
#include "MessageDirector.h"
#include "core/config.h"
#include "core/global.h"
#include "MDNetworkParticipant.h"
#include <boost/bind.hpp>
using boost::asio::ip::tcp; // I don't want to type all of that god damned shit
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");
ConfigVariable<std::string> connect_addr("messagedirector/connect", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
			std::string str_ip = bind_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_acceptor = new tcp::acceptor(io_service, *it, true);
			start_accept();
		}
		if(connect_addr.get_val() != "unspecified")
		{
			std::string str_ip = connect_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_remote_md = new tcp::socket(io_service);
			boost::system::error_code ec;
			m_remote_md->connect(*it, ec);
			if(ec.value() != 0)
			{
				gLogger->fatal() << "Could not connect to remote MD at IP: "
					<< connect_addr.get_val() << " With error code: "
					<< ec.value() << "(" << ec.category().message(ec.value()) << ")"
					<< std::endl;
				exit(1);
			}
		}
	}
}

void MessageDirector::handle_datagram(Datagram *dg, MDParticipantInterface *participant)
{
	DatagramIterator dgi(dg);
	unsigned char channels = dgi.read_uint8();
	if(channels == 1)
	{
		unsigned long long channel = dgi.read_uint64();
		if(channel == CONTROL_MESSAGE && participant)
		{
			unsigned int msg_type = dgi.read_uint16();
			switch(msg_type)
			{
				case CONTROL_SET_CHANNEL:
				{
					ChannelList c;
					c.is_range = false;
					c.a = dgi.read_uint64();
					m_participant_channels[participant].insert(m_participant_channels[participant].end(), c);
				}
				break;
				default:
					gLogger->error() << "Unknown MD MsgType: " << msg_type << std::endl;
			}
			return;
		}
		dgi.seek(1);
	}
	//TODO: loop through channels & route crap.
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false), m_remote_md(NULL)
{
}

void MessageDirector::start_accept()
{
	tcp::socket *socket = new tcp::socket(io_service);
	tcp::endpoint peerEndpoint;
	m_acceptor->async_accept(*socket, boost::bind(&MessageDirector::handle_accept,
		this, socket, boost::asio::placeholders::error));
}

void MessageDirector::handle_accept(tcp::socket *socket, const boost::system::error_code &ec)
{
	boost::asio::ip::tcp::endpoint remote = socket->remote_endpoint();
	gLogger->info() << "Got a Message Director connection from "
	                << remote.address() << ":" << remote.port() << std::endl;
	new MDNetworkParticipant(socket); //It deletes itsself when connection is lost
	start_accept();
}
<|endoftext|>