<commit_before>// $Id: RegularExpression_test.C,v 1.6 2000/07/27 20:00:12 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/DATATYPE/regExp.h>

///////////////////////////

START_TEST(RegularExpression, "$Id: RegularExpression_test.C,v 1.6 2000/07/27 20:00:12 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
String filename;
using std::ofstream;
using std::ios;

RegularExpression* re;

CHECK(RegularExpression())
	re = new RegularExpression();
	TEST_NOT_EQUAL(re, 0)
RESULT

CHECK(~RegularExpression())
	delete re;
RESULT

CHECK(RegularExpression(const String& pattern, bool wildcard_pattern = false))
	re = new RegularExpression("abc");
	TEST_NOT_EQUAL(re, 0)
	if (re != 0)
	{
		TEST_EQUAL((*re).getPattern(), "abc");
	}
	delete re;
RESULT

RegularExpression re1("abc");
RegularExpression re2("abc");

CHECK(RegularExpression(const RegularExpression& regular_expression, bool deep = true))
	re = new RegularExpression(re1);
	TEST_NOT_EQUAL(re, 0)
	if (re != 0)
	{
		TEST_EQUAL((*re).getPattern(), "abc");
	}
	delete re;
RESULT

CHECK(clear)
	re1.clear();
	TEST_EQUAL(re1.getPattern(), "");
RESULT

CHECK(destroy)
	re2.clear();
	TEST_EQUAL(re2.getPattern(), "");
RESULT

CHECK(RegularExpression::set(const String& pattern, bool wildcard_pattern = false))
	re1.set("abc*d", true);
	TEST_EQUAL(re1.getPattern(), "abc.*d");
	re1.set("abc", true);
	TEST_EQUAL(re1.getPattern(), "abc");
RESULT

CHECK(RegularExpression::set(const RegularExpression& regular_expression, bool deep = true))
	re2.set(re1);
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::get(RegularExpression& regular_expression, bool deep = true) const )
	re2.clear();
	re1.get(re2);
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::getPattern() const )
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::countSubexpressions() const )
	TEST_EQUAL(re2.countSubexpressions(), 0);
	re2.set("[A-Z]+[0-9]+");
	TEST_EQUAL(re2.countSubexpressions(), 2);//???????????????
RESULT

CHECK(RegularExpression::match(const char* text, const char* pattern, int compile_flags = 0 | REG_EXTENDED | REG_NOSUB, int execute_flags = 0 ))
	char* c = 0;
	TEST_EXCEPTION(Exception::NullPointer, re2.match(c, "*bd"))
	TEST_EXCEPTION(Exception::NullPointer, re2.match("*bd", c))
	TEST_EQUAL(re2.match("abbcbbd", "*bd"), true)//???????????
	TEST_EQUAL(re2.match("abbcbbd", "bd"), true)
	TEST_EQUAL(re2.match("abbcbbd", "b.a"), false)
	TEST_EQUAL(re2.match("abbcbbd", "a*d"), true)
	TEST_EQUAL(re2.match("abbcbbd", "a..d"), false)
	TEST_EQUAL(re2.match("abbcbbd", "x"), false)
	TEST_EQUAL(re2.match("abbcbbd", "a[bc]+d"), true)
	TEST_EQUAL(re2.match("abbcbbd", "a[bc][bc]d"), false)
	TEST_EQUAL(re2.match("abbcbbd", "a[b]+d"), false)
	TEST_EQUAL(re2.match("abbcbbd", "a[BC]+d"), false)
RESULT

CHECK(RegularExpression::match(const String& text, Index from = 0, int execute_flags = 0 ) const )
	re2.set("a[bc]+d");
	String s = "abbcbbd";
	TEST_EQUAL(re2.match(s), true)
	TEST_EQUAL(re2.match(s, 1, 0), false)
RESULT

CHECK(RegularExpression::match(const Substring& text, Index from = 0, int execute_flags = 0) const )
	String s = "abbcbbd";
	Substring ss;
	ss.bind(s);
	TEST_EQUAL(re2.match(ss), true)
	TEST_EQUAL(re2.match(ss, 1, 0), false)
RESULT

CHECK(RegularExpression::match(const char* text, int execute_flags = 0) const )
	char* s = "abbcbbd";
	TEST_EQUAL(re2.match(s), true)
RESULT

CHECK(RegularExpression::find(const char* text, const char* pattern, const char** found_substring_from = 0, const char** found_substring_to = 0, int compile_flags = 0 | REG_EXTENDED, int execute_flags = 0))
	/*char* s = "abbcbbd";
	char* c1 = 0;
	char* c2 = 0;
	TEST_EQUAL(re2.find(s, "bb", &c1, &c2), true)
	TEST_EQUAL(*c1, 0)
	TEST_EQUAL(*c2, 0)*/
RESULT

CHECK(RegularExpression::find(const String& text, Substring& found, Index from = 0, int execute_flags = 0) const )
	Substring sub;
	String text("1234ABC123");
	RegularExpression re("[A-Z]+");
	bool result = re.find(text, sub);
	TEST_EQUAL(result, true)
	TEST_EQUAL(sub.isBound(), true)
	TEST_EQUAL(sub.size(), 3)
	TEST_EQUAL(sub.getFirstIndex(), 4)
	sub.set("");
	TEST_EQUAL(text, "1234123")
RESULT

CHECK(RegularExpression::find(const String& text, Substring found_subexpression[], Size number_of_subexpressions, Index from = 0, int execute_flags = 0) const )
	re2.set("bb?");
	String s = "abbcbbd";
	Substring ss[5];
	TEST_EQUAL(re2.find(s, ss, 5, 0), true)
	TEST_EQUAL(ss[0].isBound(), true)
	TEST_EQUAL(ss[0].size(), 2)
	TEST_EQUAL(ss[0].getFirstIndex(), 1)
	TEST_EQUAL(ss[1].isBound(), true)
	TEST_EQUAL(ss[0], "bb")
	TEST_EQUAL(re2.find(s, ss, 5, 5), false)
RESULT

CHECK(RegularExpression::find(const Substring& text, Substring& found, Index from = 0, int execute_flags = 0) const )
	String s = "abbcbbd";
	Substring ss(s);
	Substring sss;
	TEST_EQUAL(re2.find(ss, sss), true)
	TEST_EQUAL(sss.isBound(), true)
	TEST_EQUAL(sss, "bb")
	TEST_EQUAL(re2.find(s, sss, 5, 0), false)
RESULT

CHECK(RegularExpression::find(const Substring& text, Substring found_subexpressions[], Size number_of_subexpressions, Index from = 0, int execute_flags = 0) const )
	String s = "abbcbbd";
	Substring ss(s);
	Substring sa[5];
	TEST_EQUAL(re2.find(ss, sa, 5), true)
	TEST_EQUAL(sa[0].isBound(), true)
	TEST_EQUAL(sa[1].isBound(), true)
	TEST_EQUAL(sa[0], "bb")
	TEST_EQUAL(re2.find(ss, sa, 5, 5), false)
RESULT

CHECK(RegularExpression::find(const char* text, const char** found_substrings_from = 0, const char** found_substring_to = 0, int execute_flags = 0) const )
	char* s = "abbcbbd";
	char* from = 0;
	char* to = 0;
	//TEST_EQUAL(re2.find(s, from, to), true)
RESULT

CHECK(RegularExpression::isEmpty() const )
	re2.set("abc");
	TEST_EQUAL(re2.isEmpty(), false)
	re2.set("");
	TEST_EQUAL(re2.isEmpty(), true)
RESULT

CHECK(RegularExpression::bool operator == (const RegularExpression& regular_expression) const )
	re2.set("abc");
	re1.set("abc");
	TEST_EQUAL(re2 == re1, true)
	re2.set("");
	TEST_EQUAL(re2 == re1, false)
RESULT

CHECK(RegularExpression::bool operator != (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 != re1, true)
	re2.set("abc");
	TEST_EQUAL(re2 != re1, false)
RESULT

CHECK(RegularExpression::bool operator < (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 < re1, false)
	re2.set("abb");
	TEST_EQUAL(re2 < re1, true)
RESULT

CHECK(RegularExpression::bool operator <= (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 <= re1, true)
	re2.set(re1);
	TEST_EQUAL(re2 <= re1, true)
	re2.set("abd");
	TEST_EQUAL(re2 <= re1, false)
RESULT

CHECK(RegularExpression::bool operator >= (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 >= re1, true)
	re2.set(re1);
	TEST_EQUAL(re2 >= re1, true)
	re2.set("abb");
	TEST_EQUAL(re2 >= re1, false)
RESULT

CHECK(RegularExpression::bool operator > (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 > re1, false)
	re2.set("abd");
	TEST_EQUAL(re2 > re1, true)
RESULT

CHECK(RegularExpression::isValid() const )
	re2.set("abc");
	TEST_EQUAL(re2.isValid(), true)
RESULT

CHECK(RegularExpression::dump(::std::ostream& s = ::std::cout, Size depth = 0) const )
	re2.set("[A-Z]+");
	NEW_TMP_FILE(filename)
	std::ofstream outfile(filename.c_str(), File::OUT);
	re2.dump(outfile);
	outfile.close();
	TEST_FILE(filename.c_str(), "data/Regular_Expression.txt", false)
RESULT

CHECK(RegularExpression::friend::std::ostream& operator << (::std::ostream& s, const RegularExpression& regular_expression))
	NEW_TMP_FILE(filename)
	std::ofstream outstr(filename.c_str(), File::OUT);
	outstr << re2;
	outstr.close();
	TEST_FILE(filename.c_str(), "data/Regular_Expression2.txt", false)
RESULT

CHECK(RegularExpression::friend::std::istream& operator >> (::std::istream& s, RegularExpression& regular_expression))
	std::ifstream instr("data/Regular_Expression2.txt");
	re2.clear();
	instr >> re2;
	instr.close();
	TEST_EQUAL(re2.getPattern(), "[A-Z]+")
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: removed tests for obsolete methods<commit_after>// $Id: RegularExpression_test.C,v 1.7 2000/10/20 16:30:47 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/DATATYPE/regExp.h>

///////////////////////////

START_TEST(RegularExpression, "$Id: RegularExpression_test.C,v 1.7 2000/10/20 16:30:47 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
String filename;
using std::ofstream;
using std::ios;

RegularExpression* re;

CHECK(RegularExpression())
	re = new RegularExpression();
	TEST_NOT_EQUAL(re, 0)
RESULT

CHECK(~RegularExpression())
	delete re;
RESULT

CHECK(RegularExpression(const String& pattern, bool wildcard_pattern = false))
	re = new RegularExpression("abc");
	TEST_NOT_EQUAL(re, 0)
	if (re != 0)
	{
		TEST_EQUAL((*re).getPattern(), "abc");
	}
	delete re;
RESULT

RegularExpression re1("abc");
RegularExpression re2("abc");

CHECK(RegularExpression(const RegularExpression& regular_expression, bool deep = true))
	re = new RegularExpression(re1);
	TEST_NOT_EQUAL(re, 0)
	if (re != 0)
	{
		TEST_EQUAL((*re).getPattern(), "abc");
	}
	delete re;
RESULT

CHECK(clear)
	re1.clear();
	TEST_EQUAL(re1.getPattern(), "");
RESULT

CHECK(destroy)
	re2.clear();
	TEST_EQUAL(re2.getPattern(), "");
RESULT

CHECK(RegularExpression::set(const String& pattern, bool wildcard_pattern = false))
	re1.set("abc*d", true);
	TEST_EQUAL(re1.getPattern(), "abc.*d");
	re1.set("abc", true);
	TEST_EQUAL(re1.getPattern(), "abc");
RESULT

CHECK(RegularExpression::set(const RegularExpression& regular_expression, bool deep = true))
	re2.set(re1);
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::get(RegularExpression& regular_expression, bool deep = true) const )
	re2.clear();
	re1.get(re2);
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::getPattern() const )
	TEST_EQUAL(re2.getPattern(), "abc");
RESULT

CHECK(RegularExpression::countSubexpressions() const )
	TEST_EQUAL(re2.countSubexpressions(), 0);
	TEST_EQUAL(re2.isValid(), true)
	re2.set("([A-Z]+[0-9]+).*([0-9])");
	TEST_EQUAL(re2.isValid(), true)
	TEST_EQUAL(re2.countSubexpressions(), 2);
RESULT

CHECK(RegularExpression::match(const char* text, const char* pattern, int compile_flags = 0 | REG_EXTENDED | REG_NOSUB, int execute_flags = 0 ))
	char* c = 0;
	TEST_EXCEPTION(Exception::NullPointer, RegularExpression::match(c, "a*bd"))
	TEST_EXCEPTION(Exception::NullPointer, RegularExpression::match("a*bd", c))
	TEST_EQUAL(RegularExpression::match("abbcbbd", ".*bd"), true)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "bd"), true)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "b.a"), false)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a*d"), true)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a..d"), false)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "x"), false)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a[bc]+d"), true)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a[bc][bc]d"), false)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a[b]+d"), false)
	TEST_EQUAL(RegularExpression::match("abbcbbd", "a[BC]+d"), false)
RESULT

CHECK(RegularExpression::match(const String& text, Index from = 0, int execute_flags = 0 ) const )
	re2.set("a[bc]+d");
	String s = "abbcbbd";
	TEST_EQUAL(re2.isValid(), true)
	TEST_EQUAL(re2.match(s), true)
	TEST_EQUAL(re2.match(s, 1, 0), false)
	re2.set(".*bd");
	TEST_EQUAL(re2.isValid(), true)
	TEST_EQUAL(re2.match(s), true)
RESULT

CHECK(RegularExpression::match(const Substring& text, Index from = 0, int execute_flags = 0) const )
	re2.set("a[bc]+d");
	String s = "abbcbbd";
	Substring ss;
	ss.bind(s);
	TEST_EQUAL(re2.match(ss), true)
	TEST_EQUAL(re2.match(ss, 1, 0), false)
RESULT

CHECK(RegularExpression::match(const char* text, int execute_flags = 0) const )
	char* s = "abbcbbd";
	TEST_EQUAL(re2.match(s), true)
RESULT

CHECK(RegularExpression::find(const String& text, Substring& found, Index from = 0, int execute_flags = 0) const )
	Substring sub;
	String text("1234ABC123");
	RegularExpression re("[A-Z]+");
	bool result = re.find(text, sub);
	TEST_EQUAL(result, true)
	TEST_EQUAL(sub.isBound(), true)
	TEST_EQUAL(sub.size(), 3)
	TEST_EQUAL(sub.getFirstIndex(), 4)
	sub.set("");
	TEST_EQUAL(text, "1234123")
RESULT

CHECK(RegularExpression::find(const String& text, vector<Substring>& subexpressions, Index from = 0, int execute_flags = 0) const )
	re2.set("(bb).*(bd)");
	String s = "abbcbbd";
	vector<Substring> ss;
	TEST_EQUAL(re2.find(s, ss, 0), true)
	TEST_EQUAL(ss.size(), 3)
	TEST_EQUAL(ss[0].isBound(), true)
	TEST_EQUAL(ss[0].size(), 6)
	TEST_EQUAL(ss[0], "bbcbbd")
	TEST_EQUAL(ss[1].isBound(), true)
	TEST_EQUAL(ss[1].size(), 2)
	TEST_EQUAL(ss[1], "bb")
	TEST_EQUAL(ss[2].isBound(), true)
	TEST_EQUAL(ss[2].size(), 2)
	TEST_EQUAL(ss[2], "bd")
	TEST_EQUAL(re2.find(s, ss, 5), false)
RESULT

CHECK(RegularExpression::isEmpty() const )
	re2.set("abc");
	TEST_EQUAL(re2.isEmpty(), false)
	re2.set("");
	TEST_EQUAL(re2.isEmpty(), true)
RESULT

CHECK(RegularExpression::bool operator == (const RegularExpression& regular_expression) const )
	re2.set("abc");
	re1.set("abc");
	TEST_EQUAL(re2 == re1, true)
	re2.set("");
	TEST_EQUAL(re2 == re1, false)
RESULT

CHECK(RegularExpression::bool operator != (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 != re1, true)
	re2.set("abc");
	TEST_EQUAL(re2 != re1, false)
RESULT

CHECK(RegularExpression::bool operator < (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 < re1, false)
	re2.set("abb");
	TEST_EQUAL(re2 < re1, true)
RESULT

CHECK(RegularExpression::bool operator <= (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 <= re1, true)
	re2.set(re1);
	TEST_EQUAL(re2 <= re1, true)
	re2.set("abd");
	TEST_EQUAL(re2 <= re1, false)
RESULT

CHECK(RegularExpression::bool operator >= (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 >= re1, true)
	re2.set(re1);
	TEST_EQUAL(re2 >= re1, true)
	re2.set("abb");
	TEST_EQUAL(re2 >= re1, false)
RESULT

CHECK(RegularExpression::bool operator > (const RegularExpression& regular_expression) const )
	TEST_EQUAL(re2 > re1, false)
	re2.set("abd");
	TEST_EQUAL(re2 > re1, true)
RESULT

CHECK(RegularExpression::isValid() const )
	re2.set("abc");
	TEST_EQUAL(re2.isValid(), true)
RESULT

CHECK(RegularExpression::dump(::std::ostream& s = ::std::cout, Size depth = 0) const )
	re2.set("[A-Z]+");
	NEW_TMP_FILE(filename)
	std::ofstream outfile(filename.c_str(), File::OUT);
	re2.dump(outfile);
	outfile.close();
	TEST_FILE(filename.c_str(), "data/Regular_Expression.txt", false)
RESULT

CHECK(RegularExpression::friend::std::ostream& operator << (::std::ostream& s, const RegularExpression& regular_expression))
	NEW_TMP_FILE(filename)
	std::ofstream outstr(filename.c_str(), File::OUT);
	outstr << re2;
	outstr.close();
	TEST_FILE(filename.c_str(), "data/Regular_Expression2.txt", false)
RESULT

CHECK(RegularExpression::friend::std::istream& operator >> (::std::istream& s, RegularExpression& regular_expression))
	std::ifstream instr("data/Regular_Expression2.txt");
	re2.clear();
	instr >> re2;
	instr.close();
	TEST_EQUAL(re2.getPattern(), "[A-Z]+")
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


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

#include <math.h>

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

#include <pcl/PointIndices.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>

#include <pcl/recognition/linemod.h>
#include <pcl/recognition/color_gradient_modality.h>
#include <pcl/recognition/surface_normal_modality.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

typedef pcl::PointCloud<pcl::PointXYZRGBA> PointCloudXYZRGBA;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input1.pcd input2.pcd input3.pcd (etc.)\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("           -min_depth z_min   = the depth of the near clipping plane\n");
  print_info ("           -max_depth z_max   = the depth of the far clipping plane\n");
  print_info ("           -max_height y_max  = the height of the vertical clipping plane\n");
  print_info ("Two new template files will be created for each input file.  They will append ");
  print_info ("the following suffixes to the original filename:\n");
  print_info ("   _template.pcd (A PCD containing segmented points)\n");
  print_info ("   _template.sqmmt (A file storing LINEMOD's 'Sparse Quantized Multi-Modal Template' representation)\n");

}

void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
  print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
  print_value ("%d", w*h); print_info (" points]\n");
}

bool
loadCloud (const std::string & filename, PointCloudXYZRGBA & cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);

  printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);

  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

std::vector<bool>
maskForegroundPoints (const PointCloudXYZRGBA::ConstPtr & input,
                      float min_depth, float max_depth, float max_height)
{
  std::vector<bool> foreground_mask (input->size (), false);

  // Mask off points outside the specified near and far depth thresholds
  pcl::IndicesPtr indices (new std::vector<int>);
  for (size_t i = 0; i < input->size (); ++i)
  {
    const float z = input->points[i].z;
    if (min_depth < z && z < max_depth)
    {
      foreground_mask[i] = true;
      indices->push_back (static_cast<int> (i));
    }
  }

  // Find the dominant plane between the specified near/far thresholds
  const float distance_threshold = 0.02f;
  const int max_iterations = 500;
  pcl::SACSegmentation<pcl::PointXYZRGBA> seg;
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_PLANE);
  seg.setMethodType (pcl::SAC_RANSAC);
  seg.setDistanceThreshold (distance_threshold);
  seg.setMaxIterations (max_iterations);
  seg.setInputCloud (input);
  seg.setIndices (indices);
  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients ());
  pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());
  seg.segment (*inliers, *coefficients);

  // Mask off the plane inliers
  for (size_t i = 0; i < inliers->indices.size (); ++i)
    foreground_mask[inliers->indices[i]] = false;

  // Mask off any foreground points that are too high above the detected plane
  const std::vector<float> & c = coefficients->values;
  for (size_t i = 0; i < input->size (); ++i)
  {
    if (foreground_mask[i])
    {
      const pcl::PointXYZRGBA & p = input->points[i];
      float d = fabsf (c[0]*p.x + c[1]*p.y + c[2]*p.z + c[3]);
      foreground_mask[i] = (d < max_height);
    }
  }

  return (foreground_mask);
}

void
trainTemplate (const PointCloudXYZRGBA::ConstPtr & input, const std::vector<bool> &foreground_mask,
               pcl::LINEMOD & linemod)
{
  pcl::ColorGradientModality<pcl::PointXYZRGBA> color_grad_mod;
  color_grad_mod.setInputCloud (input);
  color_grad_mod.processInputData ();

  pcl::SurfaceNormalModality<pcl::PointXYZRGBA> surface_norm_mod;
  surface_norm_mod.setInputCloud (input);
  surface_norm_mod.processInputData ();

  std::vector<pcl::QuantizableModality*> modalities (2);
  modalities[0] = &color_grad_mod;
  modalities[1] = &surface_norm_mod;

  size_t min_x (input->width), min_y (input->height), max_x (0), max_y (0);
  pcl::MaskMap mask_map (input->width, input->height);
  for (size_t j = 0; j < input->height; ++j)
  {
    for (size_t i = 0; i < input->width; ++i)
    {
      mask_map (i,j) = foreground_mask[j*input->width+i];
      if (foreground_mask[j*input->width+i])
      {
        min_x = std::min (min_x, i);
        max_x = std::max (max_x, i);
        min_y = std::min (min_y, j);
        max_y = std::max (max_y, j);
      }
    }
  }

  std::vector<pcl::MaskMap*> masks (2);
  masks[0] = &mask_map;
  masks[1] = &mask_map;

  pcl::RegionXY region;
  region.x = static_cast<int> (min_x);
  region.y = static_cast<int> (min_y);
  region.width = static_cast<int> (max_x - min_x + 1);
  region.height = static_cast<int> (max_y - min_y + 1);

  printf ("%d %d %d %d\n", region.x, region.y, region.width, region.height);

  linemod.createAndAddTemplate (modalities, masks, region);
}

void
compute (const PointCloudXYZRGBA::ConstPtr & input, float min_depth, float max_depth, float max_height,
         const std::string & template_pcd_filename, const std::string & template_sqmmt_filename)
{
  // Segment the foreground object
  std::vector<bool> foreground_mask = maskForegroundPoints (input, min_depth, max_depth, max_height);

  // Save the masked template cloud (masking with NaNs to preserve its organized structure)
  PointCloudXYZRGBA template_cloud (*input);
  for (size_t i = 0; i < foreground_mask.size (); ++i)
  {
    if (!foreground_mask[i])
    {
      pcl::PointXYZRGBA & p = template_cloud.points[i];
      p.x = p.y = p.z = 0.0f / 0.0f;
    }
  }
  pcl::io::savePCDFile (template_pcd_filename, template_cloud);

  // Create a LINEMOD template
  pcl::LINEMOD linemod;
  trainTemplate (input, foreground_mask, linemod);

  // Save the LINEMOD template
  std::ofstream file_stream;
  file_stream.open (template_sqmmt_filename.c_str (), std::ofstream::out | std::ofstream::binary);
  linemod.getTemplate (0).serialize (file_stream);
  file_stream.close ();
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Train one or more linemod templates. For more information, use: %s -h\n", argv[0]);

  // If no arguments are given, print the help text
  if (argc == 1)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.empty ())
  {
    print_error ("Need at least one input PCD file.\n");
    return (-1);
  }

  // Parse the min_depth, max_depth, and max_height parameters
  float min_depth = 0;
  parse_argument (argc, argv, "-min_depth", min_depth);

  float max_depth = std::numeric_limits<float>::max ();
  parse_argument (argc, argv, "-max_depth", max_depth);

  float max_height = std::numeric_limits<float>::max ();
  parse_argument (argc, argv, "-max_height", max_height);

  // Segment and create templates for each input file
  for (size_t i_file = 0; i_file < p_file_indices.size (); ++i_file)
  {
    // Load input file
    const std::string input_filename = argv[p_file_indices[i_file]];
    PointCloudXYZRGBA::Ptr cloud (new PointCloudXYZRGBA);
    if (!loadCloud (input_filename, *cloud))
      return (-1);

    // Construct output filenames
    std::string sqmmt_filename = input_filename;
    sqmmt_filename.replace(sqmmt_filename.length () - 4, 13, "_template.sqmmt");

    std::string pcd_filename = input_filename;
    pcd_filename.replace(pcd_filename.length () - 4, 13, "_template.pcd");

    std::cout << sqmmt_filename << std::endl;
    std::cout << pcd_filename << std::endl;

    // Train the LINE-MOD template and output it to the specified file
    compute (cloud, min_depth, max_depth, max_height, pcd_filename, sqmmt_filename);
  }

}

<commit_msg>fixed compiling error<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#include <math.h>

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

#include <pcl/PointIndices.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>

#include <pcl/recognition/linemod.h>
#include <pcl/recognition/color_gradient_modality.h>
#include <pcl/recognition/surface_normal_modality.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

typedef pcl::PointCloud<pcl::PointXYZRGBA> PointCloudXYZRGBA;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input1.pcd input2.pcd input3.pcd (etc.)\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("           -min_depth z_min   = the depth of the near clipping plane\n");
  print_info ("           -max_depth z_max   = the depth of the far clipping plane\n");
  print_info ("           -max_height y_max  = the height of the vertical clipping plane\n");
  print_info ("Two new template files will be created for each input file.  They will append ");
  print_info ("the following suffixes to the original filename:\n");
  print_info ("   _template.pcd (A PCD containing segmented points)\n");
  print_info ("   _template.sqmmt (A file storing LINEMOD's 'Sparse Quantized Multi-Modal Template' representation)\n");

}

void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
  print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
  print_value ("%d", w*h); print_info (" points]\n");
}

bool
loadCloud (const std::string & filename, PointCloudXYZRGBA & cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);

  printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);

  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

std::vector<bool>
maskForegroundPoints (const PointCloudXYZRGBA::ConstPtr & input,
                      float min_depth, float max_depth, float max_height)
{
  std::vector<bool> foreground_mask (input->size (), false);

  // Mask off points outside the specified near and far depth thresholds
  pcl::IndicesPtr indices (new std::vector<int>);
  for (size_t i = 0; i < input->size (); ++i)
  {
    const float z = input->points[i].z;
    if (min_depth < z && z < max_depth)
    {
      foreground_mask[i] = true;
      indices->push_back (static_cast<int> (i));
    }
  }

  // Find the dominant plane between the specified near/far thresholds
  const float distance_threshold = 0.02f;
  const int max_iterations = 500;
  pcl::SACSegmentation<pcl::PointXYZRGBA> seg;
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_PLANE);
  seg.setMethodType (pcl::SAC_RANSAC);
  seg.setDistanceThreshold (distance_threshold);
  seg.setMaxIterations (max_iterations);
  seg.setInputCloud (input);
  seg.setIndices (indices);
  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients ());
  pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());
  seg.segment (*inliers, *coefficients);

  // Mask off the plane inliers
  for (size_t i = 0; i < inliers->indices.size (); ++i)
    foreground_mask[inliers->indices[i]] = false;

  // Mask off any foreground points that are too high above the detected plane
  const std::vector<float> & c = coefficients->values;
  for (size_t i = 0; i < input->size (); ++i)
  {
    if (foreground_mask[i])
    {
      const pcl::PointXYZRGBA & p = input->points[i];
      float d = fabsf (c[0]*p.x + c[1]*p.y + c[2]*p.z + c[3]);
      foreground_mask[i] = (d < max_height);
    }
  }

  return (foreground_mask);
}

void
trainTemplate (const PointCloudXYZRGBA::ConstPtr & input, const std::vector<bool> &foreground_mask,
               pcl::LINEMOD & linemod)
{
  pcl::ColorGradientModality<pcl::PointXYZRGBA> color_grad_mod;
  color_grad_mod.setInputCloud (input);
  color_grad_mod.processInputData ();

  pcl::SurfaceNormalModality<pcl::PointXYZRGBA> surface_norm_mod;
  surface_norm_mod.setInputCloud (input);
  surface_norm_mod.processInputData ();

  std::vector<pcl::QuantizableModality*> modalities (2);
  modalities[0] = &color_grad_mod;
  modalities[1] = &surface_norm_mod;

  size_t min_x (input->width), min_y (input->height), max_x (0), max_y (0);
  pcl::MaskMap mask_map (input->width, input->height);
  for (size_t j = 0; j < input->height; ++j)
  {
    for (size_t i = 0; i < input->width; ++i)
    {
      mask_map (i,j) = foreground_mask[j*input->width+i];
      if (foreground_mask[j*input->width+i])
      {
        min_x = std::min (min_x, i);
        max_x = std::max (max_x, i);
        min_y = std::min (min_y, j);
        max_y = std::max (max_y, j);
      }
    }
  }

  std::vector<pcl::MaskMap*> masks (2);
  masks[0] = &mask_map;
  masks[1] = &mask_map;

  pcl::RegionXY region;
  region.x = static_cast<int> (min_x);
  region.y = static_cast<int> (min_y);
  region.width = static_cast<int> (max_x - min_x + 1);
  region.height = static_cast<int> (max_y - min_y + 1);

  printf ("%d %d %d %d\n", region.x, region.y, region.width, region.height);

  linemod.createAndAddTemplate (modalities, masks, region);
}

void
compute (const PointCloudXYZRGBA::ConstPtr & input, float min_depth, float max_depth, float max_height,
         const std::string & template_pcd_filename, const std::string & template_sqmmt_filename)
{
  // Segment the foreground object
  std::vector<bool> foreground_mask = maskForegroundPoints (input, min_depth, max_depth, max_height);

  // Save the masked template cloud (masking with NaNs to preserve its organized structure)
  PointCloudXYZRGBA template_cloud (*input);
  for (size_t i = 0; i < foreground_mask.size (); ++i)
  {
    if (!foreground_mask[i])
    {
      pcl::PointXYZRGBA & p = template_cloud.points[i];
      p.x = p.y = p.z = std::numeric_limits<float>::quiet_NaN ();
    }
  }
  pcl::io::savePCDFile (template_pcd_filename, template_cloud);

  // Create a LINEMOD template
  pcl::LINEMOD linemod;
  trainTemplate (input, foreground_mask, linemod);

  // Save the LINEMOD template
  std::ofstream file_stream;
  file_stream.open (template_sqmmt_filename.c_str (), std::ofstream::out | std::ofstream::binary);
  linemod.getTemplate (0).serialize (file_stream);
  file_stream.close ();
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Train one or more linemod templates. For more information, use: %s -h\n", argv[0]);

  // If no arguments are given, print the help text
  if (argc == 1)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.empty ())
  {
    print_error ("Need at least one input PCD file.\n");
    return (-1);
  }

  // Parse the min_depth, max_depth, and max_height parameters
  float min_depth = 0;
  parse_argument (argc, argv, "-min_depth", min_depth);

  float max_depth = std::numeric_limits<float>::max ();
  parse_argument (argc, argv, "-max_depth", max_depth);

  float max_height = std::numeric_limits<float>::max ();
  parse_argument (argc, argv, "-max_height", max_height);

  // Segment and create templates for each input file
  for (size_t i_file = 0; i_file < p_file_indices.size (); ++i_file)
  {
    // Load input file
    const std::string input_filename = argv[p_file_indices[i_file]];
    PointCloudXYZRGBA::Ptr cloud (new PointCloudXYZRGBA);
    if (!loadCloud (input_filename, *cloud))
      return (-1);

    // Construct output filenames
    std::string sqmmt_filename = input_filename;
    sqmmt_filename.replace(sqmmt_filename.length () - 4, 13, "_template.sqmmt");

    std::string pcd_filename = input_filename;
    pcd_filename.replace(pcd_filename.length () - 4, 13, "_template.pcd");

    std::cout << sqmmt_filename << std::endl;
    std::cout << pcd_filename << std::endl;

    // Train the LINE-MOD template and output it to the specified file
    compute (cloud, min_depth, max_depth, max_height, pcd_filename, sqmmt_filename);
  }

}

<|endoftext|>


<commit_before>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QSqlDatabase>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/storage/factory.hh"
#include "com/centreon/broker/storage/internal.hh"
#include "com/centreon/broker/storage/stream.hh"
#include "com/centreon/broker/storage/metric.hh"
#include "com/centreon/broker/storage/rebuild.hh"
#include "com/centreon/broker/storage/remove_graph.hh"
#include "com/centreon/broker/storage/status.hh"

using namespace com::centreon::broker;

// Load count.
static unsigned int instances(0);

extern "C" {
  /**
   *  Module deinitialization routine.
   */
  void broker_module_deinit() {
    // Decrement instance number.
    if (!--instances) {
      // Deregister storage layer.
      // Remove events.
      io::events::instance().unregister_category(io::events::storage);
      io::protocols::instance().unreg("storage");

      // Remove the workaround connection.
      if (QSqlDatabase::contains())
        QSqlDatabase::removeDatabase(QSqlDatabase::defaultConnection);
    }
    return ;
  }

  /**
   *  Module initialization routine.
   *
   *  @param[in] arg Configuration object.
   */
  void broker_module_init(void const* arg) {
    (void)arg;

    // Increment instance number.
    if (!instances++) {
      // Storage module.
      logging::info(logging::high)
        << "storage: module for Centreon Broker "
        << CENTREON_BROKER_VERSION;

      io::events& e(io::events::instance());

      // Register category.
      int storage_category(e.register_category("storage", io::events::storage));
      if (storage_category != io::events::storage) {
        e.unregister_category(storage_category);
        --instances;
        throw (exceptions::msg() << "storage: category " << io::events::storage
               << " is already registered whereas it should be "
               << "reserved for the storage module");
      }

      // Register events.
      {
        e.register_event(
            io::events::storage,
            storage::de_metric,
            io::event_info(
                  "metric",
                  &storage::metric::operations,
                  storage::metric::entries));
        e.register_event(
            io::events::storage,
            storage::de_rebuild,
            io::event_info(
                  "rebuild",
                  &storage::rebuild::operations,
                  storage::rebuild::entries));
        e.register_event(
            io::events::storage,
            storage::de_remove_graph,
            io::event_info(
                  "metric",
                  &storage::remove_graph::operations,
                  storage::remove_graph::entries));
        e.register_event(
            io::events::storage,
            storage::de_status,
            io::event_info(
                  "metric",
                  &storage::status::operations,
                  storage::status::entries));
      }

      // This is a workaround to keep a mysql driver open.
      if (!QSqlDatabase::contains())
        QSqlDatabase::addDatabase("QMYSQL");

      // Register storage layer.
      io::protocols::instance().reg(
                                  "storage",
                                  storage::factory(),
                                  1,
                                  7);
    }
    return ;
  }
}
<commit_msg>Storage: add metric and status mapping mappings.<commit_after>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QSqlDatabase>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/storage/factory.hh"
#include "com/centreon/broker/storage/internal.hh"
#include "com/centreon/broker/storage/stream.hh"
#include "com/centreon/broker/storage/metric.hh"
#include "com/centreon/broker/storage/metric_mapping.hh"
#include "com/centreon/broker/storage/rebuild.hh"
#include "com/centreon/broker/storage/remove_graph.hh"
#include "com/centreon/broker/storage/status.hh"
#include "com/centreon/broker/storage/status_mapping.hh"

using namespace com::centreon::broker;

// Load count.
static unsigned int instances(0);

extern "C" {
  /**
   *  Module deinitialization routine.
   */
  void broker_module_deinit() {
    // Decrement instance number.
    if (!--instances) {
      // Deregister storage layer.
      // Remove events.
      io::events::instance().unregister_category(io::events::storage);
      io::protocols::instance().unreg("storage");

      // Remove the workaround connection.
      if (QSqlDatabase::contains())
        QSqlDatabase::removeDatabase(QSqlDatabase::defaultConnection);
    }
    return ;
  }

  /**
   *  Module initialization routine.
   *
   *  @param[in] arg Configuration object.
   */
  void broker_module_init(void const* arg) {
    (void)arg;

    // Increment instance number.
    if (!instances++) {
      // Storage module.
      logging::info(logging::high)
        << "storage: module for Centreon Broker "
        << CENTREON_BROKER_VERSION;

      io::events& e(io::events::instance());

      // Register category.
      int storage_category(e.register_category("storage", io::events::storage));
      if (storage_category != io::events::storage) {
        e.unregister_category(storage_category);
        --instances;
        throw (exceptions::msg() << "storage: category " << io::events::storage
               << " is already registered whereas it should be "
               << "reserved for the storage module");
      }

      // Register events.
      {
        e.register_event(
            io::events::storage,
            storage::de_metric,
            io::event_info(
                  "metric",
                  &storage::metric::operations,
                  storage::metric::entries));
        e.register_event(
            io::events::storage,
            storage::de_rebuild,
            io::event_info(
                  "rebuild",
                  &storage::rebuild::operations,
                  storage::rebuild::entries));
        e.register_event(
            io::events::storage,
            storage::de_remove_graph,
            io::event_info(
                  "metric",
                  &storage::remove_graph::operations,
                  storage::remove_graph::entries));
        e.register_event(
            io::events::storage,
            storage::de_status,
            io::event_info(
                  "metric",
                  &storage::status::operations,
                  storage::status::entries));
        e.register_event(
            io::events::storage,
            storage::de_metric_mapping,
            io::event_info(
                  "metric_mapping",
                  &storage::metric_mapping::operations,
                  storage::metric_mapping::entries));
        e.register_event(
            io::events::storage,
            storage::de_status_mapping,
            io::event_info(
                  "status_mapping",
                  &storage::status_mapping::operations,
                  storage::status_mapping::entries));
      }

      // This is a workaround to keep a mysql driver open.
      if (!QSqlDatabase::contains())
        QSqlDatabase::addDatabase("QMYSQL");

      // Register storage layer.
      io::protocols::instance().reg(
                                  "storage",
                                  storage::factory(),
                                  1,
                                  7);
    }
    return ;
  }
}
<|endoftext|>


<commit_before>//  Powiter
/* 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/. */
/*
 *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
 *contact: immarespond at gmail dot com
 *
 */

#include "Project.h"

#include <fstream>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QXmlStreamWriter>

#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/vector.hpp>

#include "Global/AppManager.h"

#include "Engine/TimeLine.h"
#include "Engine/Node.h"
#include "Engine/OfxNode.h"
#include "Engine/Knob.h"
#include "Engine/ViewerNode.h"

#include "Gui/NodeGui.h"
#include "Gui/ViewerTab.h"
#include "Gui/ViewerGL.h"

using namespace Powiter;
using std::cout; using std::endl;
using std::make_pair;

Project::Project(AppInstance* appInstance):
_projectName("Untitled."POWITER_PROJECT_FILE_EXTENION),
_hasProjectBeenSavedByUser(false),
_ageSinceLastSave(QDateTime::currentDateTime()),
_timeline(new TimeLine())
,_autoSetProjectFormat(true)
,_currentNodes()
,_availableFormats()
,_appInstance(appInstance)
{

    //    _format(*appPTR->findExistingFormat(1920, 1080,1.)),
    _formatKnob = dynamic_cast<ComboBox_Knob*>(appPTR->getKnobFactory().createKnob("ComboBox", NULL, "Output Format"));
    const std::vector<Format*>& appFormats = appPTR->getFormats();
    std::vector<std::string> entries;
    for (U32 i = 0; i < appFormats.size(); ++i) {
        Format* f = appFormats[i];
        QString formatStr;
        formatStr.append(f->getName().c_str());
        formatStr.append("  ");
        formatStr.append(QString::number(f->width()));
        if(f->width() == 1920 && f->height() == 1080){
            _formatKnob->setValue(i);
        }
        formatStr.append(" x ");
        formatStr.append(QString::number(f->height()));
        formatStr.append("  ");
        formatStr.append(QString::number(f->getPixelAspect()));
        entries.push_back(formatStr.toStdString());
        _availableFormats.push_back(*f);
    }

    _formatKnob->populate(entries);
    QObject::connect(_formatKnob,SIGNAL(valueChangedByUser()),this,SLOT(onProjectFormatChanged()));
    _projectKnobs.push_back(_formatKnob);
}
Project::~Project(){
    for (U32 i = 0; i < _currentNodes.size(); ++i) {
        _currentNodes[i]->deleteNode();
    }
    _currentNodes.clear();
}

void Project::onProjectFormatChanged(){
    const Format& f = _availableFormats[_formatKnob->getActiveEntry()];
    for(U32 i = 0 ; i < _currentNodes.size() ; ++i){
        if (_currentNodes[i]->className() == "Viewer") {
            ViewerNode* n = dynamic_cast<ViewerNode*>(_currentNodes[i]);
            n->getUiContext()->viewer->onProjectFormatChanged(f);
            n->refreshAndContinueRender();
        }
    }
}

const Format& Project::getProjectDefaultFormat() const{
    int index = _formatKnob->getActiveEntry();
    return _availableFormats[index];
}

void Project::initNodeCountersAndSetName(Node* n){
    assert(n);
    std::map<std::string,int>::iterator it = _nodeCounters.find(n->className());
    if(it != _nodeCounters.end()){
        it->second++;
        n->setName(QString(QString(n->className().c_str())+ "_" + QString::number(it->second)).toStdString());
    }else{
        _nodeCounters.insert(make_pair(n->className(), 1));
        n->setName(QString(QString(n->className().c_str())+ "_" + QString::number(1)).toStdString());
    }
    _currentNodes.push_back(n);
}

void Project::clearNodes(){
    foreach(Node* n,_currentNodes){
        n->deleteNode();
    }
    _currentNodes.clear();
}

void Project::setFrameRange(int first, int last){
    _timeline->setFrameRange(first,last);
}

void Project::seekFrame(int frame){
    _timeline->seekFrame(frame);
}

void Project::incrementCurrentFrame() {
    _timeline->incrementCurrentFrame();
}
void Project::decrementCurrentFrame(){
    _timeline->decrementCurrentFrame();
}

int Project::currentFrame() const {
    return _timeline->currentFrame();
}

int Project::firstFrame() const {
    return _timeline->firstFrame();
}

int Project::lastFrame() const {
    return _timeline->lastFrame();
}

void Project::loadProject(const QString& path,const QString& name){
    QString filePath = path+name;
    std::ifstream ifile(filePath.toStdString().c_str(),std::ifstream::in);
    boost::archive::xml_iarchive iArchive(ifile);
    std::list<NodeGui::SerializedState> nodeStates;
    iArchive >> boost::serialization::make_nvp("Nodes",nodeStates);
    iArchive >> boost::serialization::make_nvp("Project_formats",_availableFormats);

    ifile.close();

    /*first create all nodes and restore the knobs values*/
    for (std::list<NodeGui::SerializedState>::const_iterator it = nodeStates.begin() ; it!=nodeStates.end(); ++it) {
        const NodeGui::SerializedState& state = *it;
        Node* n = _appInstance->createNode(state.getClassName().c_str());
        if(!n){
            clearNodes();
            QString text("Failed to restore the graph! \n The node ");
            text.append(state.getClassName().c_str());
            text.append(" was found in the auto-save script but doesn't seem \n"
                        "to exist in the currently loaded plug-ins.");
            _appInstance->clearNodes();
            throw std::invalid_argument(text.toStdString());
        }
        n->setName(state.getName());
        const std::map<std::string,std::string>& knobsValues = state.getKnobsValues();
        for (std::map<std::string,std::string>::const_iterator v = knobsValues.begin(); v!=knobsValues.end(); ++v) {
            if(v->second.empty())
                continue;
            Knob* knob = n->getKnobByDescription(v->first);
            if(!knob){
                cout << "Couldn't restore knob value ( " << v->first << " )." << endl;
            }else{
                knob->restoreFromString(v->second);
            }
        }
        NodeGui* nGui = _appInstance->getNodeGui(n);
        nGui->setPos(state.getX(),state.getY());
        _appInstance->deselectAllNodes();
    }

    /*now that we have all nodes, just connect them*/
    for(std::list<NodeGui::SerializedState>::const_iterator it = nodeStates.begin() ; it!=nodeStates.end(); ++it){
        const std::map<int, std::string>& inputs = (*it).getInputs();
        Node* thisNode = NULL;
        for (U32 i = 0; i < _currentNodes.size(); ++i) {
            if (_currentNodes[i]->getName() == (*it).getName()) {
                thisNode = _currentNodes[i];
                break;
            }
        }
        for (std::map<int, std::string>::const_iterator input = inputs.begin(); input!=inputs.end(); ++input) {
            if(input->second.empty())
                continue;
            if(!_appInstance->connect(input->first, input->second,thisNode)){
                cout << "Failed to connect " << (*it).getName() << " to " << input->second << endl;
            }
        }

    }

    QDateTime time = QDateTime::currentDateTime();
    setAutoSetProjectFormat(false);
    setHasProjectBeenSavedByUser(true);
    setProjectName(name);
    setProjectPath(path);
    setProjectAgeSinceLastSave(time);
    setProjectAgeSinceLastAutosaveSave(time);

    /*Refresh all viewers as it was*/
    _appInstance->checkViewersConnection();
}
void Project::saveProject(const QString& path,const QString& filename,bool autoSave){
    QString filePath;
    if(autoSave){
        filePath = AppInstance::autoSavesDir()+QDir::separator()+filename;
    }else{
        filePath = path+filename;
    }
    std::ofstream ofile(filePath.toStdString().c_str(),std::ofstream::out);
    boost::archive::xml_oarchive oArchive(ofile);
    if(!ofile.is_open()){
        cout << "Failed to open file " << filePath.toStdString() << endl;
        return;
    }
    std::list<NodeGui::SerializedState> nodeStates;
    const std::vector<NodeGui*>& activeNodes = _appInstance->getAllActiveNodes();
    for (U32 i = 0; i < activeNodes.size(); ++i) {
        NodeGui::SerializedState state = activeNodes[i]->serialize();
        nodeStates.push_back(state);
    }
    oArchive << boost::serialization::make_nvp("Nodes",nodeStates);
    oArchive << boost::serialization::make_nvp("Project_formats",_availableFormats);
    ofile.close();
}

const std::vector<Knob*>& Project::getProjectKnobs() const{

    return _projectKnobs;
}

int Project::tryAddProjectFormat(const Format& f){
    for (U32 i = 0; i < _availableFormats.size(); ++i) {
        if(f == _availableFormats[i]){
            return i;
        }
    }
    std::vector<Format> currentFormats = _availableFormats;
    _availableFormats.clear();
    std::vector<std::string> entries;
    for (U32 i = 0; i < currentFormats.size(); ++i) {
        const Format& f = currentFormats[i];
        QString formatStr;
        formatStr.append(f.getName().c_str());
        formatStr.append("  ");
        formatStr.append(QString::number(f.width()));
        formatStr.append(" x ");
        formatStr.append(QString::number(f.height()));
        formatStr.append("  ");
        formatStr.append(QString::number(f.getPixelAspect()));
        entries.push_back(formatStr.toStdString());
        _availableFormats.push_back(f);
    }
    QString formatStr;
    formatStr.append(f.getName().c_str());
    formatStr.append("  ");
    formatStr.append(QString::number(f.width()));
    formatStr.append(" x ");
    formatStr.append(QString::number(f.height()));
    formatStr.append("  ");
    formatStr.append(QString::number(f.getPixelAspect()));
    entries.push_back(formatStr.toStdString());
    _availableFormats.push_back(f);
    _formatKnob->populate(entries);
    return _availableFormats.size() - 1;
}

void Project::setProjectDefaultFormat(const Format& f) {
    int index = tryAddProjectFormat(f);
    _formatKnob->setValue(index);
    emit projectFormatChanged(f);

}
<commit_msg>Loading a project now remembers the output format.<commit_after>//  Powiter
/* 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/. */
/*
 *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
 *contact: immarespond at gmail dot com
 *
 */

#include "Project.h"

#include <fstream>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QXmlStreamWriter>

#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/vector.hpp>

#include "Global/AppManager.h"

#include "Engine/TimeLine.h"
#include "Engine/Node.h"
#include "Engine/OfxNode.h"
#include "Engine/Knob.h"
#include "Engine/ViewerNode.h"

#include "Gui/NodeGui.h"
#include "Gui/ViewerTab.h"
#include "Gui/ViewerGL.h"

using namespace Powiter;
using std::cout; using std::endl;
using std::make_pair;

static QString generateStringFromFormat(const Format& f){
    QString formatStr;
    formatStr.append(f.getName().c_str());
    formatStr.append("  ");
    formatStr.append(QString::number(f.width()));
    formatStr.append(" x ");
    formatStr.append(QString::number(f.height()));
    formatStr.append("  ");
    formatStr.append(QString::number(f.getPixelAspect()));
    return formatStr;
}

Project::Project(AppInstance* appInstance):
_projectName("Untitled."POWITER_PROJECT_FILE_EXTENION),
_hasProjectBeenSavedByUser(false),
_ageSinceLastSave(QDateTime::currentDateTime()),
_timeline(new TimeLine())
,_autoSetProjectFormat(true)
,_currentNodes()
,_availableFormats()
,_appInstance(appInstance)
{

    //    _format(*appPTR->findExistingFormat(1920, 1080,1.)),
    _formatKnob = dynamic_cast<ComboBox_Knob*>(appPTR->getKnobFactory().createKnob("ComboBox", NULL, "Output Format"));
    const std::vector<Format*>& appFormats = appPTR->getFormats();
    std::vector<std::string> entries;
    for (U32 i = 0; i < appFormats.size(); ++i) {
        Format* f = appFormats[i];
        QString formatStr = generateStringFromFormat(*f);
                if(f->width() == 1920 && f->height() == 1080){
            _formatKnob->setValue(i);
        }
        entries.push_back(formatStr.toStdString());
        _availableFormats.push_back(*f);
    }

    _formatKnob->populate(entries);
    QObject::connect(_formatKnob,SIGNAL(valueChangedByUser()),this,SLOT(onProjectFormatChanged()));
    _projectKnobs.push_back(_formatKnob);
}
Project::~Project(){
    for (U32 i = 0; i < _currentNodes.size(); ++i) {
        _currentNodes[i]->deleteNode();
    }
    _currentNodes.clear();
}

void Project::onProjectFormatChanged(){
    const Format& f = _availableFormats[_formatKnob->getActiveEntry()];
    for(U32 i = 0 ; i < _currentNodes.size() ; ++i){
        if (_currentNodes[i]->className() == "Viewer") {
            ViewerNode* n = dynamic_cast<ViewerNode*>(_currentNodes[i]);
            n->getUiContext()->viewer->onProjectFormatChanged(f);
            n->refreshAndContinueRender();
        }
    }
}

const Format& Project::getProjectDefaultFormat() const{
    int index = _formatKnob->getActiveEntry();
    return _availableFormats[index];
}

void Project::initNodeCountersAndSetName(Node* n){
    assert(n);
    std::map<std::string,int>::iterator it = _nodeCounters.find(n->className());
    if(it != _nodeCounters.end()){
        it->second++;
        n->setName(QString(QString(n->className().c_str())+ "_" + QString::number(it->second)).toStdString());
    }else{
        _nodeCounters.insert(make_pair(n->className(), 1));
        n->setName(QString(QString(n->className().c_str())+ "_" + QString::number(1)).toStdString());
    }
    _currentNodes.push_back(n);
}

void Project::clearNodes(){
    foreach(Node* n,_currentNodes){
        n->deleteNode();
    }
    _currentNodes.clear();
}

void Project::setFrameRange(int first, int last){
    _timeline->setFrameRange(first,last);
}

void Project::seekFrame(int frame){
    _timeline->seekFrame(frame);
}

void Project::incrementCurrentFrame() {
    _timeline->incrementCurrentFrame();
}
void Project::decrementCurrentFrame(){
    _timeline->decrementCurrentFrame();
}

int Project::currentFrame() const {
    return _timeline->currentFrame();
}

int Project::firstFrame() const {
    return _timeline->firstFrame();
}

int Project::lastFrame() const {
    return _timeline->lastFrame();
}

void Project::loadProject(const QString& path,const QString& name){
    QString filePath = path+name;
    std::ifstream ifile(filePath.toStdString().c_str(),std::ifstream::in);
    boost::archive::xml_iarchive iArchive(ifile);
    std::list<NodeGui::SerializedState> nodeStates;
    iArchive >> boost::serialization::make_nvp("Nodes",nodeStates);
    iArchive >> boost::serialization::make_nvp("Project_formats",_availableFormats);

    /*we must restore the entries in the combobox before restoring the value*/
    std::vector<std::string> entries;
    for (U32 i = 0; i < _availableFormats.size(); ++i) {
        QString formatStr = generateStringFromFormat(_availableFormats[i]);
        entries.push_back(formatStr.toStdString());
    }
    _formatKnob->populate(entries);
    std::string currentFormat;
    iArchive >> boost::serialization::make_nvp("Project_output_format",currentFormat);
    _formatKnob->restoreFromString(currentFormat);
    setAutoSetProjectFormat(false);

    ifile.close();

    /*first create all nodes and restore the knobs values*/
    for (std::list<NodeGui::SerializedState>::const_iterator it = nodeStates.begin() ; it!=nodeStates.end(); ++it) {
        const NodeGui::SerializedState& state = *it;
        Node* n = _appInstance->createNode(state.getClassName().c_str());
        if(!n){
            clearNodes();
            QString text("Failed to restore the graph! \n The node ");
            text.append(state.getClassName().c_str());
            text.append(" was found in the auto-save script but doesn't seem \n"
                        "to exist in the currently loaded plug-ins.");
            _appInstance->clearNodes();
            throw std::invalid_argument(text.toStdString());
        }
        n->setName(state.getName());
        const std::map<std::string,std::string>& knobsValues = state.getKnobsValues();
        for (std::map<std::string,std::string>::const_iterator v = knobsValues.begin(); v!=knobsValues.end(); ++v) {
            if(v->second.empty())
                continue;
            Knob* knob = n->getKnobByDescription(v->first);
            if(!knob){
                cout << "Couldn't restore knob value ( " << v->first << " )." << endl;
            }else{
                knob->restoreFromString(v->second);
            }
        }
        NodeGui* nGui = _appInstance->getNodeGui(n);
        nGui->setPos(state.getX(),state.getY());
        _appInstance->deselectAllNodes();
    }

    /*now that we have all nodes, just connect them*/
    for(std::list<NodeGui::SerializedState>::const_iterator it = nodeStates.begin() ; it!=nodeStates.end(); ++it){
        const std::map<int, std::string>& inputs = (*it).getInputs();
        Node* thisNode = NULL;
        for (U32 i = 0; i < _currentNodes.size(); ++i) {
            if (_currentNodes[i]->getName() == (*it).getName()) {
                thisNode = _currentNodes[i];
                break;
            }
        }
        for (std::map<int, std::string>::const_iterator input = inputs.begin(); input!=inputs.end(); ++input) {
            if(input->second.empty())
                continue;
            if(!_appInstance->connect(input->first, input->second,thisNode)){
                cout << "Failed to connect " << (*it).getName() << " to " << input->second << endl;
            }
        }

    }

    QDateTime time = QDateTime::currentDateTime();
    setAutoSetProjectFormat(false);
    setHasProjectBeenSavedByUser(true);
    setProjectName(name);
    setProjectPath(path);
    setProjectAgeSinceLastSave(time);
    setProjectAgeSinceLastAutosaveSave(time);

    /*Refresh all viewers as it was*/
    emit projectFormatChanged(_availableFormats[_formatKnob->getActiveEntry()]);
    _appInstance->checkViewersConnection();
}
void Project::saveProject(const QString& path,const QString& filename,bool autoSave){
    QString filePath;
    if(autoSave){
        filePath = AppInstance::autoSavesDir()+QDir::separator()+filename;
    }else{
        filePath = path+filename;
    }
    std::ofstream ofile(filePath.toStdString().c_str(),std::ofstream::out);
    boost::archive::xml_oarchive oArchive(ofile);
    if(!ofile.is_open()){
        cout << "Failed to open file " << filePath.toStdString() << endl;
        return;
    }
    std::list<NodeGui::SerializedState> nodeStates;
    const std::vector<NodeGui*>& activeNodes = _appInstance->getAllActiveNodes();
    for (U32 i = 0; i < activeNodes.size(); ++i) {
        NodeGui::SerializedState state = activeNodes[i]->serialize();
        nodeStates.push_back(state);
    }
    oArchive << boost::serialization::make_nvp("Nodes",nodeStates);
    oArchive << boost::serialization::make_nvp("Project_formats",_availableFormats);
    std::string currentFormat = _formatKnob->serialize();
    oArchive << boost::serialization::make_nvp("Project_output_format",currentFormat);
    ofile.close();
}

const std::vector<Knob*>& Project::getProjectKnobs() const{

    return _projectKnobs;
}

int Project::tryAddProjectFormat(const Format& f){
    for (U32 i = 0; i < _availableFormats.size(); ++i) {
        if(f == _availableFormats[i]){
            return i;
        }
    }
    std::vector<Format> currentFormats = _availableFormats;
    _availableFormats.clear();
    std::vector<std::string> entries;
    for (U32 i = 0; i < currentFormats.size(); ++i) {
        const Format& f = currentFormats[i];
        QString formatStr = generateStringFromFormat(f);
        entries.push_back(formatStr.toStdString());
        _availableFormats.push_back(f);
    }
    QString formatStr = generateStringFromFormat(f);
    entries.push_back(formatStr.toStdString());
    _availableFormats.push_back(f);
    _formatKnob->populate(entries);
    return _availableFormats.size() - 1;
}

void Project::setProjectDefaultFormat(const Format& f) {
    int index = tryAddProjectFormat(f);
    _formatKnob->setValue(index);
    emit projectFormatChanged(f);

}
<|endoftext|>


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

#include "rawToAMR.h"

const char *description = R"description(
Creates an adaptive mesh refinement (AMR) representation of the provided
structured volume data.

The input structured volume data is used as the highest refinement level
(i.e. the finest resolution data). From this level, data that does not meet
the user-provided variance threshold is discarded. The average of the
discarded block is used in the next level down.

This simulates the effect that an adaptive simulation would have created
regions of higher refinement in the highly varying portions of the volume.
)description";

const char *usage = R"usage([-h | --help] input_volume variable_type
    x_dim y_dim z_dim num_levels block_size refinement_factor threshold
    output_basename
)usage";

const char *help = R"help(
input_volume        Structured volume in binary brick-of-data format
                    (string filepath)
variable_type       Type of structured volume, must be exactly one of:
                        float
                        byte
                        uchar
                        uint8
                        double
                        float64
                    (string)
x_dim               X dimensions of the structured volume grid (int)
y_dim               Y dimensions of the structured volume grid (int)
z_dim               Z dimensions of the structured volume grid (int)
num_levels          Number of refinement levels to simulate (int)
block_size          Size of blocks at each level in terms of cells. Blocks
                    are defined as cubes with this number of cells per edge.
                    Note that refinement levels change the width of the
                    cells, NOT the width of the blocks. Blocks will always
                    be this provided size in cell extents, but the width of
                    the cells will be smaller/larger depending on level.
                    For example, a block of 4x4x4 cells at the highest
                    refinement level will be converted into a single cell
                    at the next lower level, which would be part of that
                    level's block of 4x4x4 cells. (int)
refinement_factor   How much larger/smaller, in terms of cell extents, each
                    level's grid will be. Note that this is independent of
                    block_size above! For example, if the input data is a
                    512^3 grid, and block_size is 4^3, the highest
                    refinement level will have a 128^3 block grid. If this
                    value is 2, the next level will have a 64^3 block grid,
                    but will still be comprised of 4^3 blocks. That is, the
                    number of cells decreases from 512^3 to 256^3, and the
                    cell width increases to accommodate. (int)
threshold           Variance threshold used to determine whether a block
                    belongs to a higher refinement level. If the variance
                    within a block is above this threshold, it remains at
                    the current level. Otherwise, if the variance is low,
                    this block would have not have been selected for mesh
                    refinement by a numerical simulation, so this block is
                    discarded at this level. (variable_type, converted to
                    float)
output_basename     Basename for the output files. This application creates
                    three files with different extensions, with this basename
                    in common. (string)
)help";

std::string inFileName;
std::string format;
vec3i inDims;
int numLevels;
int blockSize;
int refinementLevel;
float threshold;
std::string outFileBase;

bool parseArguments(int argc, char **argv)
{
    if(std::string(argv[1]) == "-h" ||
       std::string(argv[1]) == "--help") {
        std::cerr << description << std::endl;
        std::cerr << "Usage: " << argv[0] << " " << usage << std::endl;
        std::cerr << help << std::endl;
        return false;
    }
    if(argc != 11) {
        std::cerr << argc - 1 << " argument" << ((argc > 2) ? "s " : " ");
        std::cerr << "provided, but 10 are needed" << std::endl;
        std::cerr << "Usage: " << argv[0] << " " << usage << std::endl;
        return false;
    }

    inFileName = argv[1];
    format = argv[2];
    inDims.x = atoi(argv[3]);
    inDims.y = atoi(argv[4]);
    inDims.z = atoi(argv[5]);
    numLevels = atoi(argv[6]);
    blockSize = atoi(argv[7]);
    refinementLevel = atoi(argv[8]);
    threshold = atof(argv[9]);
    outFileBase = argv[10];

    return true;
}

int main(int argc, char **argv)
{
    // ALOK: TODO
    // better argument handling and usage description
    bool parseSucceed = parseArguments(argc, argv);
    if(!parseSucceed) {
        return 1;
    }

    // ALOK: ultimately storing the data as float regardless of input type
    // (????)
    std::shared_ptr<Array3D<float>> in;
    if (format == "float") {
        in = mmapRAW<float>(inFileName, inDims);
    } else if (format == "byte" || format == "uchar" || format == "uint8") {
        in = std::make_shared<Array3DAccessor<unsigned char, float>>(
                mmapRAW<unsigned char>(inFileName, inDims));
    } else if (format == "double" || format == "float64") {
        in = std::make_shared<Array3DAccessor<double, float>>(
                mmapRAW<double>(inFileName, inDims));
    } else {
        throw std::runtime_error("unknown input voxel format");
    }

    std::vector<ospray::amr::BrickDesc> brickInfo;
    std::vector<std::vector<float>> brickData;

    ospray::amr::makeAMR(in, numLevels, blockSize, refinementLevel, threshold, brickInfo, brickData);
    ospray::amr::outputAMR(outFileBase, brickInfo, brickData, blockSize);

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

#include "rawToAMR.h"

const char *description = R"description(
Creates an adaptive mesh refinement (AMR) representation of the provided
structured volume data.

The input structured volume data is used as the highest refinement level
(i.e. the finest resolution data). From this level, data that does not meet
the user-provided variance threshold is discarded. The average of the
discarded block is used in the next level down.

This simulates the effect that an adaptive simulation would have created
regions of higher refinement in the highly varying portions of the volume.
)description";

const char *usage = R"usage([-h | --help] input_volume variable_type
    x_dim y_dim z_dim num_levels block_size refinement_factor threshold
    output_basename
)usage";

const char *help = R"help(
input_volume        Structured volume in binary brick-of-data format
                    (string filepath)
variable_type       Type of structured volume, must be exactly one of:
                        float
                        byte
                        uchar
                        uint8
                        double
                        float64
                    (string)
x_dim               X dimensions of the structured volume grid (int)
y_dim               Y dimensions of the structured volume grid (int)
z_dim               Z dimensions of the structured volume grid (int)
num_levels          Number of refinement levels to simulate (int)
block_size          Size of blocks at each level in terms of cells. Blocks
                    are defined as cubes with this number of cells per edge.
                    Note that refinement levels change the width of the
                    cells, NOT the width of the blocks. Blocks will always
                    be this provided size in cell extents, but the width of
                    the cells will be smaller/larger depending on level.
                    For example, a block of 4x4x4 cells at the highest
                    refinement level will be converted into a single cell
                    at the next lower level, which would be part of that
                    level's block of 4x4x4 cells. (int)
refinement_factor   How much larger/smaller, in terms of cell extents, each
                    level's grid will be. Note that this is independent of
                    block_size above! For example, if the input data is a
                    512^3 grid, and block_size is 4^3, the highest
                    refinement level will have a 128^3 block grid. If this
                    value is 2, the next level will have a 64^3 block grid,
                    but will still be comprised of 4^3 blocks. That is, the
                    number of cells decreases from 512^3 to 256^3, and the
                    cell width increases to accommodate. (int)
threshold           Variance threshold used to determine whether a block
                    belongs to a higher refinement level. If the variance
                    within a block is above this threshold, it remains at
                    the current level. Otherwise, if the variance is low,
                    this block would have not have been selected for mesh
                    refinement by a numerical simulation, so this block is
                    discarded at this level. (variable_type, converted to
                    float)
output_basename     Basename for the output files. This application creates
                    three files with different extensions, with this basename
                    in common. (string)
)help";

std::string inFileName;
std::string format;
vec3i inDims;
int numLevels;
int blockSize;
int refinementLevel;
float threshold;
std::string outFileBase;

bool parseArguments(int argc, char **argv)
{
    if(argc != 11) {
        if(argc > 1 &&
           (std::string(argv[1]) == "-h" ||
           std::string(argv[1]) == "--help")) {
            std::cerr << description << std::endl;
            std::cerr << "Usage: " << argv[0] << " " << usage << std::endl;
            std::cerr << help << std::endl;
        }
        else {
            std::cerr << argc - 1 << " argument" <<
                ((argc == 1 || argc > 2) ? "s " : " ");
            std::cerr << "provided, but 10 are needed" << std::endl;
            std::cerr << "Usage: " << argv[0] << " " << usage << std::endl;
        }
        return false;
    }

    inFileName = argv[1];
    format = argv[2];
    inDims.x = atoi(argv[3]);
    inDims.y = atoi(argv[4]);
    inDims.z = atoi(argv[5]);
    numLevels = atoi(argv[6]);
    blockSize = atoi(argv[7]);
    refinementLevel = atoi(argv[8]);
    threshold = atof(argv[9]);
    outFileBase = argv[10];

    return true;
}

int main(int argc, char **argv)
{
    // ALOK: TODO
    // better argument handling and usage description
    bool parseSucceed = parseArguments(argc, argv);
    if(!parseSucceed) {
        return 1;
    }

    // ALOK: ultimately storing the data as float regardless of input type
    // (????)
    std::shared_ptr<Array3D<float>> in;
    if (format == "float") {
        in = mmapRAW<float>(inFileName, inDims);
    } else if (format == "byte" || format == "uchar" || format == "uint8") {
        in = std::make_shared<Array3DAccessor<unsigned char, float>>(
                mmapRAW<unsigned char>(inFileName, inDims));
    } else if (format == "double" || format == "float64") {
        in = std::make_shared<Array3DAccessor<double, float>>(
                mmapRAW<double>(inFileName, inDims));
    } else {
        throw std::runtime_error("unknown input voxel format");
    }

    std::vector<ospray::amr::BrickDesc> brickInfo;
    std::vector<std::vector<float>> brickData;

    ospray::amr::makeAMR(in, numLevels, blockSize, refinementLevel, threshold, brickInfo, brickData);
    ospray::amr::outputAMR(outFileBase, brickInfo, brickData, blockSize);

    return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
FILE : api/cmiss_function_matrix.cpp

LAST MODIFIED : 6 August 2004

DESCRIPTION :
The public interface to the Cmiss_function matrix object.
==============================================================================*/

#include <new>
#include "api/cmiss_function_matrix.h"
#include "computed_variable/function_matrix.hpp"

// module typedefs
// ===============

typedef boost::intrusive_ptr< Function_matrix<Scalar> > Function_matrix_handle;

/*
Global functions
----------------
*/

Cmiss_function_id Cmiss_function_matrix_create(unsigned int number_of_rows,
	unsigned int number_of_columns,Scalar *values)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Creates a Cmiss_function matrix with the specified <number_of_rows>,
<number_of_columns> and <values>.  If <values> is NULL then the matrix is
initialized to zero.
==============================================================================*/
{
	Cmiss_function_id result;

	result=0;
	if (0<number_of_rows*number_of_columns)
	{
		Matrix values_matrix(number_of_rows,number_of_columns);
		Function_size_type i,j,k;

		if (values)
		{
			k=0;
			for (i=0;i<number_of_rows;i++)
			{
				for (j=0;j<number_of_columns;j++)
				{
					values_matrix(i,j)=values[k];
					k++;
				}
			}
		}
		else
		{
			for (i=0;i<number_of_rows;i++)
			{
				for (j=0;j<number_of_columns;j++)
				{
					values_matrix(i,j)=(Scalar)0;
				}
			}
		}
		result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
			new Function_matrix<Scalar>(values_matrix)));
	}

	return (result);
}

Cmiss_function_variable_id Cmiss_function_matrix_entry(
	Cmiss_function_id function_matrix,unsigned int row,unsigned int column)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Returns a variable that refers to the entry at the specified <row> and <column>.
If <row> is zero, then the variable refers to the <column>.  If <column> is
zero, then the variable refers to the <row>.  If <row> and <column> are both
zero, the variable refers to the whole matrix.
==============================================================================*/
{
	Cmiss_function_variable_id result;
	Function_matrix_handle *function_matrix_handle_address;

	if ((function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))&&
		(*function_matrix_handle_address))
	{
		result=reinterpret_cast<Cmiss_function_variable_id>(
			new Function_variable_handle(((*function_matrix_handle_address)->entry)(
			row,column)));
	}
	else
	{
		result=0;
	}

	return (result);
}

int Cmiss_function_matrix_get_dimensions(Cmiss_function_id function_matrix,
	unsigned int *number_of_rows_address,unsigned int *number_of_columns_address)
/*******************************************************************************
LAST MODIFIED : 24 February 2004

DESCRIPTION :
Gets the <*number_of_rows_address> and <*number_of_columns_address> for the
<function_matrix>.
==============================================================================*/
{
	int return_code;
	Function_matrix_handle *function_matrix_handle_address;

	return_code=0;
	if (function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))
	{
		return_code=1;
		if (number_of_rows_address)
		{
			*number_of_rows_address=
				((*function_matrix_handle_address)->number_of_rows)();
		}
		if (number_of_columns_address)
		{
			*number_of_columns_address=
				((*function_matrix_handle_address)->number_of_columns)();
		}
	}

	return (return_code);
}

Cmiss_function_id Cmiss_function_matrix_get_sub_matrix(
	Cmiss_function_id function_matrix,unsigned int row_low,unsigned int row_high,
	unsigned int column_low,unsigned int column_high)
/*******************************************************************************
LAST MODIFIED : 24 February 2004

DESCRIPTION :
Returns a Cmiss_function matrix which is the specified sub-matrix of
<function_matrix>.
==============================================================================*/
{
	Cmiss_function_id result;
	Function_matrix_handle *function_matrix_handle_address;

	result=0;
	if (function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))
	{
		result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
			((*function_matrix_handle_address)->sub_matrix)(row_low,row_high,
			column_low,column_high)));
	}

	return (result);
}

Cmiss_function_id Cmiss_function_matrix_solve(Cmiss_function_id function_matrix,
	Cmiss_function_id function_rhs)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Returns the solution of the linear system <function_matrix>*x=<function_rhs>.
<function_rhs> should be a matrix or a vector.
==============================================================================*/
{
	Cmiss_function_id result;
	Function_handle *function_matrix_handle_address;
	Function_handle *function_rhs_handle_address;
	Function_matrix_handle function_matrix_handle;
	Function_handle function_rhs_handle;

	result=0;
	if ((function_matrix_handle_address=
		reinterpret_cast<Function_handle *>(function_matrix))&&
		(*function_matrix_handle_address)&&
		(function_matrix_handle=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
		Function>(*function_matrix_handle_address))&&
		(function_rhs_handle_address=
		reinterpret_cast<Function_handle *>(function_rhs))&&
		(function_rhs_handle= *function_rhs_handle_address))
	{
		Function_matrix_handle function_matrix_rhs_handle;

		if (function_matrix_rhs_handle=
			boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
			function_rhs_handle))
		{
			result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
				function_matrix_handle->solve(function_matrix_rhs_handle)));
		}
	}

	return (result);
}
<commit_msg>Tidied comment style<commit_after>/*******************************************************************************
FILE : api/cmiss_function_matrix.cpp

LAST MODIFIED : 2 September 2004

DESCRIPTION :
The public interface to the Cmiss_function matrix object.
==============================================================================*/

#include <new>
#include "api/cmiss_function_matrix.h"
#include "computed_variable/function_matrix.hpp"

/*
Module typedefs
---------------
*/

typedef boost::intrusive_ptr< Function_matrix<Scalar> > Function_matrix_handle;

/*
Global functions
----------------
*/

Cmiss_function_id Cmiss_function_matrix_create(unsigned int number_of_rows,
	unsigned int number_of_columns,Scalar *values)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Creates a Cmiss_function matrix with the specified <number_of_rows>,
<number_of_columns> and <values>.  If <values> is NULL then the matrix is
initialized to zero.
==============================================================================*/
{
	Cmiss_function_id result;

	result=0;
	if (0<number_of_rows*number_of_columns)
	{
		Matrix values_matrix(number_of_rows,number_of_columns);
		Function_size_type i,j,k;

		if (values)
		{
			k=0;
			for (i=0;i<number_of_rows;i++)
			{
				for (j=0;j<number_of_columns;j++)
				{
					values_matrix(i,j)=values[k];
					k++;
				}
			}
		}
		else
		{
			for (i=0;i<number_of_rows;i++)
			{
				for (j=0;j<number_of_columns;j++)
				{
					values_matrix(i,j)=(Scalar)0;
				}
			}
		}
		result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
			new Function_matrix<Scalar>(values_matrix)));
	}

	return (result);
}

Cmiss_function_variable_id Cmiss_function_matrix_entry(
	Cmiss_function_id function_matrix,unsigned int row,unsigned int column)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Returns a variable that refers to the entry at the specified <row> and <column>.
If <row> is zero, then the variable refers to the <column>.  If <column> is
zero, then the variable refers to the <row>.  If <row> and <column> are both
zero, the variable refers to the whole matrix.
==============================================================================*/
{
	Cmiss_function_variable_id result;
	Function_matrix_handle *function_matrix_handle_address;

	if ((function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))&&
		(*function_matrix_handle_address))
	{
		result=reinterpret_cast<Cmiss_function_variable_id>(
			new Function_variable_handle(((*function_matrix_handle_address)->entry)(
			row,column)));
	}
	else
	{
		result=0;
	}

	return (result);
}

int Cmiss_function_matrix_get_dimensions(Cmiss_function_id function_matrix,
	unsigned int *number_of_rows_address,unsigned int *number_of_columns_address)
/*******************************************************************************
LAST MODIFIED : 24 February 2004

DESCRIPTION :
Gets the <*number_of_rows_address> and <*number_of_columns_address> for the
<function_matrix>.
==============================================================================*/
{
	int return_code;
	Function_matrix_handle *function_matrix_handle_address;

	return_code=0;
	if (function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))
	{
		return_code=1;
		if (number_of_rows_address)
		{
			*number_of_rows_address=
				((*function_matrix_handle_address)->number_of_rows)();
		}
		if (number_of_columns_address)
		{
			*number_of_columns_address=
				((*function_matrix_handle_address)->number_of_columns)();
		}
	}

	return (return_code);
}

Cmiss_function_id Cmiss_function_matrix_get_sub_matrix(
	Cmiss_function_id function_matrix,unsigned int row_low,unsigned int row_high,
	unsigned int column_low,unsigned int column_high)
/*******************************************************************************
LAST MODIFIED : 24 February 2004

DESCRIPTION :
Returns a Cmiss_function matrix which is the specified sub-matrix of
<function_matrix>.
==============================================================================*/
{
	Cmiss_function_id result;
	Function_matrix_handle *function_matrix_handle_address;

	result=0;
	if (function_matrix_handle_address=
		reinterpret_cast<Function_matrix_handle *>(function_matrix))
	{
		result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
			((*function_matrix_handle_address)->sub_matrix)(row_low,row_high,
			column_low,column_high)));
	}

	return (result);
}

Cmiss_function_id Cmiss_function_matrix_solve(Cmiss_function_id function_matrix,
	Cmiss_function_id function_rhs)
/*******************************************************************************
LAST MODIFIED : 6 August 2004

DESCRIPTION :
Returns the solution of the linear system <function_matrix>*x=<function_rhs>.
<function_rhs> should be a matrix or a vector.
==============================================================================*/
{
	Cmiss_function_id result;
	Function_handle *function_matrix_handle_address;
	Function_handle *function_rhs_handle_address;
	Function_matrix_handle function_matrix_handle;
	Function_handle function_rhs_handle;

	result=0;
	if ((function_matrix_handle_address=
		reinterpret_cast<Function_handle *>(function_matrix))&&
		(*function_matrix_handle_address)&&
		(function_matrix_handle=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
		Function>(*function_matrix_handle_address))&&
		(function_rhs_handle_address=
		reinterpret_cast<Function_handle *>(function_rhs))&&
		(function_rhs_handle= *function_rhs_handle_address))
	{
		Function_matrix_handle function_matrix_rhs_handle;

		if (function_matrix_rhs_handle=
			boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
			function_rhs_handle))
		{
			result=reinterpret_cast<Cmiss_function_id>(new Function_handle(
				function_matrix_handle->solve(function_matrix_rhs_handle)));
		}
	}

	return (result);
}
<|endoftext|>