<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <string>

// #define DODS_DEBUG
#include "DDS.h"
#include "ConstraintEvaluator.h"

#include "../tests/TestTypeFactory.h"
#include "../tests/TestSequence.h"
#include "../tests/TestInt32.h"
#include "../tests/TestStr.h"

#include "GNURegex.h"
#include "debug.h"

using namespace CppUnit;
using namespace std;

int test_variable_sleep_interval;

//  Note: MS VC++ won't tolerate the embedded newlines in strings, hence the \n
//  is explicit.
static const char *s_as_string = \
"BaseType \\(0x.*\\):\n\
          _name: s\n\
          _type: Sequence\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: i1\n\
          _type: Int32\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: str1\n\
          _type: String\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: i2\n\
          _type: Int32\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
\n";

static Regex s_regex(s_as_string);

class SequenceTest : public TestFixture {
private:
    DDS *dds;
    TestSequence *s, *ss, *ps, *sss, *ts, *tts;

public:
    SequenceTest() {}
    ~SequenceTest() {}

    void setUp() {
	// Set up a simple sequence. Used to test ctor, assigment, et cetera.
	s = new TestSequence("s");
	s->add_var(new TestInt32("i1"));
	s->add_var(new TestStr("str1"));
	s->add_var(new TestInt32("i2"));
        s->set_series_values(true);

        // Set ss, a two level sequence
        ss = new TestSequence("ss");
        ss->add_var(new TestInt32("i1"));

        ps = new TestSequence("child_of_ss");
        ps->add_var(new TestInt32("i2"));

        ss->add_var(ps);

	// Set up sss, used to test multi-level sequences
	sss = new TestSequence("sss");
	sss->add_var(new TestInt32("i1"));

	ts = new TestSequence("child_of_sss");
	ts->add_var(new TestStr("str1"));

	tts = new TestSequence("child_of_child_of_sss");
	tts->add_var(new TestInt32("i2"));
	ts->add_var(tts);

	sss->add_var(ts);	// This has to be here because add_var adds
				// copies of its argument.
        TestTypeFactory ttf;
        dds = new DDS(&ttf);
        dds->add_var(s);
        dds->add_var(ss);
        dds->add_var(sss);
    }

    void tearDown() {
	delete s; s = 0;
        delete ss; ss = 0;
        delete ps; ps = 0;
	delete sss; sss = 0;
	delete ts; ts = 0;
	delete tts; tts = 0;
        delete dds; dds = 0;
    }

    bool re_match(Regex &r, const char *s) {
	int match_position = r.match(s, strlen(s));
	DBG(cerr << "match position: " << match_position
	    << " string length: " << (int)strlen(s) << endl);
	return match_position == (int)strlen(s);
    }

    CPPUNIT_TEST_SUITE( SequenceTest );

    CPPUNIT_TEST(ctor_test);
    CPPUNIT_TEST(assignment);
    CPPUNIT_TEST(copy_ctor);
    CPPUNIT_TEST(test_set_leaf_sequence);
    CPPUNIT_TEST(test_set_leaf_sequence2);
    CPPUNIT_TEST(test_set_leaf_sequence3);

    CPPUNIT_TEST(transfer_data_for_leaf_test);

    CPPUNIT_TEST_SUITE_END();

    // Tests for methods
    void transfer_data_for_leaf_test() {
        ConstraintEvaluator ce;
        s->set_send_p(true);
        try {
            s->transfer_data_for_leaf("dummy", *dds, ce, true);
            BaseType *btp;

            // Test the first value in the first four rows
            btp = s->var_value(0, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 32);
            btp = s->var_value(1, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = s->var_value(2, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = s->var_value(3, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 1048576);
            DBG(s->print_val(stdout));
        }
        catch (Error &e) {
            cerr << e.get_error_message() << endl;
            CPPUNIT_ASSERT(!"Error in transfer_data_for_leaf_test()");
        }
    }

    void test_set_leaf_sequence3() {
        // Test for the rejection of a Sequence with two sequences in it.
        sss->add_var(ss);
        sss->set_send_p(true);
        try {
             sss->set_leaf_sequence(1);
             CPPUNIT_ASSERT(!"Should have thrown Error");
        }
        catch (Error &e) {
             cerr << e.get_error_message() << endl;
             CPPUNIT_ASSERT("Caught Error");
        }
    }

    void test_set_leaf_sequence2() {
        // Three level sequence
        sss->set_send_p(true);          // set send_p for whole seq
        // Now the lowest sequence is not longer to be sent. The middle sequence
        // is the lowest with fields to be sent and so should be the leaf.
        Sequence::Vars_iter i = sss->var_begin();
        Sequence *inner = dynamic_cast<Sequence*>(*++i);
        i = inner->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        inner->set_send_p(false);       // now clear send_p for the inner most seq
        sss->set_leaf_sequence(1);

        CPPUNIT_ASSERT(!sss->is_leaf_sequence());

        i = sss->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner && inner->is_leaf_sequence());

        i = inner->var_begin();
        Sequence *inner2 = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner2 && !inner2->is_leaf_sequence());
    }

    void test_set_leaf_sequence() {
        // One level sequence
        s->set_send_p(true);
        s->set_leaf_sequence(1);
        CPPUNIT_ASSERT(s->is_leaf_sequence());

        // Two level sequence
        ss->set_send_p(true);
        ss->set_leaf_sequence(1);
        CPPUNIT_ASSERT(!ss->is_leaf_sequence());
        // add_var() _copies_ the object, so ps should not be used here.
        Sequence::Vars_iter i = ss->var_begin();
        Sequence *inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner->type() == dods_sequence_c && inner->is_leaf_sequence());

        // Three level sequence
        sss->set_send_p(true);
        sss->set_leaf_sequence(1);
        CPPUNIT_ASSERT(!sss->is_leaf_sequence());

        i = sss->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner && !inner->is_leaf_sequence());

        i = inner->var_begin();
        Sequence *inner2 = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner2 && inner2->is_leaf_sequence());
    }

    void ctor_test() {
	DBG(cerr << "s: " << s->toString() << endl);
	CPPUNIT_ASSERT(re_match(s_regex, s->toString().c_str()));
    }

    void assignment() {
	Sequence ts2;

	ts2 = *s;
	DBG(cerr << "ts2: " << ts2.toString() << endl);
	CPPUNIT_ASSERT(re_match(s_regex, ts2.toString().c_str()));
    }

    void copy_ctor() {
	Sequence s2 = *s;
	CPPUNIT_ASSERT(re_match(s_regex, s2.toString().c_str()));
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION(SequenceTest);

int
main( int, char** )
{
    CppUnit::TextTestRunner runner;
    runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );

    bool wasSuccessful = runner.run( "", false ) ;

    return wasSuccessful ? 0 : 1;
}
<commit_msg>SequenceTest.cc: Now tests the new transfer_data() method.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <string>

//#define DODS_DEBUG

#include "DDS.h"
#include "ConstraintEvaluator.h"

#include "../tests/TestTypeFactory.h"
#include "../tests/TestSequence.h"
#include "../tests/TestInt32.h"
#include "../tests/TestStr.h"

#include "GNURegex.h"
#include "debug.h"

using namespace CppUnit;
using namespace std;

int test_variable_sleep_interval;

//  Note: MS VC++ won't tolerate the embedded newlines in strings, hence the \n
//  is explicit.
static const char *s_as_string = \
"BaseType \\(0x.*\\):\n\
          _name: s\n\
          _type: Sequence\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: i1\n\
          _type: Int32\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: str1\n\
          _type: String\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
BaseType \\(0x.*\\):\n\
          _name: i2\n\
          _type: Int32\n\
          _read_p: 0\n\
          _send_p: 0\n\
          _synthesized_p: 0\n\
          d_parent: 0x.*\n\
          d_attr: 0x.*\n\
\n";

static Regex s_regex(s_as_string);

class SequenceTest : public TestFixture {
private:
    DDS *dds;
    TestSequence *s, *ss, *ps, *sss, *ts, *tts;

public:
    SequenceTest() {}
    ~SequenceTest() {}

    void setUp() {
	// Set up a simple sequence. Used to test ctor, assigment, et cetera.
	s = new TestSequence("s");
	s->add_var(new TestInt32("i1"));
	s->add_var(new TestStr("str1"));
	s->add_var(new TestInt32("i2"));
        s->set_series_values(true);

        // Set ss, a two level sequence
        ss = new TestSequence("ss");
        ss->add_var(new TestInt32("i1"));
        ss->set_series_values(true);

        ps = new TestSequence("child_of_ss");
        ps->add_var(new TestInt32("i2"));
        ps->set_series_values(true);

        ss->add_var(ps);

	// Set up sss, used to test multi-level sequences
	sss = new TestSequence("sss");
	sss->add_var(new TestInt32("i1"));

	ts = new TestSequence("child_of_sss");
	ts->add_var(new TestStr("str1"));

	tts = new TestSequence("child_of_child_of_sss");
	tts->add_var(new TestInt32("i2"));
	ts->add_var(tts);

	sss->add_var(ts);	// This has to be here because add_var adds
				// copies of its argument.
        sss->set_series_values(true);

        TestTypeFactory ttf;
        dds = new DDS(&ttf);
        dds->add_var(s);
        dds->add_var(ss);
        dds->add_var(sss);
    }

    void tearDown() {
	delete s; s = 0;
        delete ss; ss = 0;
        delete ps; ps = 0;
	delete sss; sss = 0;
	delete ts; ts = 0;
	delete tts; tts = 0;

        delete dds; dds = 0;
    }

    bool re_match(Regex &r, const char *s) {
	int match_position = r.match(s, strlen(s));
	DBG(cerr << "match position: " << match_position
	    << " string length: " << (int)strlen(s) << endl);
	return match_position == (int)strlen(s);
    }

    CPPUNIT_TEST_SUITE( SequenceTest );

    CPPUNIT_TEST(ctor_test);
    CPPUNIT_TEST(assignment);
    CPPUNIT_TEST(copy_ctor);
    CPPUNIT_TEST(test_set_leaf_sequence);
    CPPUNIT_TEST(test_set_leaf_sequence2);
    CPPUNIT_TEST(test_set_leaf_sequence3);
    CPPUNIT_TEST(transfer_data_for_leaf_test);
    CPPUNIT_TEST(transfer_data_test1);
    CPPUNIT_TEST(transfer_data_test2);
    CPPUNIT_TEST(transfer_data_test3);

    CPPUNIT_TEST_SUITE_END();

    // Tests for methods
    void transfer_data_test1() {
        ConstraintEvaluator ce;
        s->set_send_p(true);
        s->set_leaf_sequence();
        try {
            s->transfer_data("dummy", ce, *dds);

            // Test the first value in the first four rows
            BaseType *btp = s->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = s->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = s->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = s->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);
            DBG(s->print_val(stdout));
        }
        catch (Error &e) {
            cerr << e.get_error_message() << endl;
            CPPUNIT_ASSERT(!"Error in transfer_data_for_leaf_test1()");
        }
    }

    void transfer_data_test2() {
        ConstraintEvaluator ce;
        ss->set_send_p(true);
        ss->set_leaf_sequence();
        try {
            ss->transfer_data("dummy", ce, *dds);
            DBG(ss->print_val(stdout));

            // Test the first value in the first four rows
            BaseType *btp = ss->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = ss->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = ss->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = ss->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);

            // Look at some values in the inner sequence
            Sequence *sp = dynamic_cast<Sequence*>(ss->var_value(0, 1));
            CPPUNIT_ASSERT(sp);
            btp = sp->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = sp->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = sp->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = sp->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);

            sp = dynamic_cast<Sequence*>(ss->var_value(3, 1));
            CPPUNIT_ASSERT(sp);
            btp = sp->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = sp->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = sp->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = sp->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);
        }
        catch (Error &e) {
            cerr << e.get_error_message() << endl;
            CPPUNIT_ASSERT(!"Error in transfer_data_test2()");
        }
    }

    void transfer_data_test3() {
        ConstraintEvaluator ce;
        sss->set_send_p(true);
        sss->set_leaf_sequence();
        try {
            sss->transfer_data("dummy", ce, *dds);
            DBG(sss->print_val_by_rows(stdout, "", true, true));
            // Test the first value in the first four rows
            BaseType *btp = sss->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = sss->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = sss->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = sss->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);

            // Look at some values in the inner-most sequence (skip the middle
            // sequence since I don't have a value() accessor for that yet.
            Sequence *sp = dynamic_cast<Sequence*>(sss->var_value(0, 1));
            CPPUNIT_ASSERT(sp);
            Sequence *ssp = dynamic_cast<Sequence*>(sp->var_value(0, 1));
            CPPUNIT_ASSERT(ssp);

            btp = ssp->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = ssp->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = ssp->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = ssp->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);

            sp = dynamic_cast<Sequence*>(sss->var_value(3, 1));
            CPPUNIT_ASSERT(sp);
            ssp = dynamic_cast<Sequence*>(sp->var_value(3, 1));
            CPPUNIT_ASSERT(ssp);

            btp = ssp->var_value(0, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32);
            btp = ssp->var_value(1, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = ssp->var_value(2, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = ssp->var_value(3, 0);
            CPPUNIT_ASSERT(btp && dynamic_cast<Int32&>(*btp).value() == 1048576);
        }
        catch (Error &e) {
            cerr << e.get_error_message() << endl;
            CPPUNIT_ASSERT(!"Error in transfer_data_test3()");
        }
    }

    void transfer_data_for_leaf_test() {
        ConstraintEvaluator ce;
        s->set_send_p(true);
        try {
            Sequence::sequence_values_stack_t sequence_values_stack;
            sequence_values_stack.push_back(&s->d_values);
            s->transfer_data_for_leaf("dummy", *dds, ce, sequence_values_stack);

            // Test the first value in the first four rows
            BaseType *btp = s->var_value(0, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 32);
            btp = s->var_value(1, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 1024);
            btp = s->var_value(2, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 32768);
            btp = s->var_value(3, 0);
            CPPUNIT_ASSERT(dynamic_cast<Int32&>(*btp).value() == 1048576);
            DBG(s->print_val(stdout));
        }
        catch (Error &e) {
            cerr << e.get_error_message() << endl;
            CPPUNIT_ASSERT(!"Error in transfer_data_for_leaf_test()");
        }
    }

    void test_set_leaf_sequence3() {
        // Test for the rejection of a Sequence with two sequences in it.
        sss->add_var(ss);
        sss->set_send_p(true);
        try {
             sss->set_leaf_sequence(1);
             CPPUNIT_ASSERT(!"Should have thrown Error");
        }
        catch (Error &e) {
             cerr << e.get_error_message() << endl;
             CPPUNIT_ASSERT("Caught Error");
        }
    }

    void test_set_leaf_sequence2() {
        // Three level sequence
        sss->set_send_p(true);          // set send_p for whole seq
        // Now the lowest sequence is not longer to be sent. The middle sequence
        // is the lowest with fields to be sent and so should be the leaf.
        Sequence::Vars_iter i = sss->var_begin();
        Sequence *inner = dynamic_cast<Sequence*>(*++i);
        i = inner->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        inner->set_send_p(false);       // now clear send_p for the inner most seq
        sss->set_leaf_sequence(1);

        CPPUNIT_ASSERT(!sss->is_leaf_sequence());

        i = sss->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner && inner->is_leaf_sequence());

        i = inner->var_begin();
        Sequence *inner2 = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner2 && !inner2->is_leaf_sequence());
    }

    void test_set_leaf_sequence() {
        // One level sequence
        s->set_send_p(true);
        s->set_leaf_sequence(1);
        CPPUNIT_ASSERT(s->is_leaf_sequence());

        // Two level sequence
        ss->set_send_p(true);
        ss->set_leaf_sequence(1);
        CPPUNIT_ASSERT(!ss->is_leaf_sequence());
        // add_var() _copies_ the object, so ps should not be used here.
        Sequence::Vars_iter i = ss->var_begin();
        Sequence *inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner->type() == dods_sequence_c && inner->is_leaf_sequence());

        // Three level sequence
        sss->set_send_p(true);
        sss->set_leaf_sequence(1);
        CPPUNIT_ASSERT(!sss->is_leaf_sequence());

        i = sss->var_begin();
        inner = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner && !inner->is_leaf_sequence());

        i = inner->var_begin();
        Sequence *inner2 = dynamic_cast<Sequence*>(*++i);
        CPPUNIT_ASSERT(inner2 && inner2->is_leaf_sequence());
    }

    void ctor_test() {
	DBG(cerr << "s: " << s->toString() << endl);
	CPPUNIT_ASSERT(re_match(s_regex, s->toString().c_str()));
    }

    void assignment() {
	Sequence ts2;

	ts2 = *s;
	DBG(cerr << "ts2: " << ts2.toString() << endl);
	CPPUNIT_ASSERT(re_match(s_regex, ts2.toString().c_str()));
    }

    void copy_ctor() {
	Sequence s2 = *s;
	CPPUNIT_ASSERT(re_match(s_regex, s2.toString().c_str()));
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION(SequenceTest);

int
main( int, char** )
{
    CppUnit::TextTestRunner runner;
    runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );

    bool wasSuccessful = runner.run( "", false ) ;

    return wasSuccessful ? 0 : 1;
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2014 Sensics, Inc.
//
// 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.

// Internal Includes
#include "OSVRUpdateCallback.h"
#include "OSGMathInterop.h"
#include "OSVRInterfaceData.h"
#include "OSVRContext.h"

// Library/third-party includes
#include <osvr/ClientKit/ClientKit.h>

#include <osg/ref_ptr>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/NodeCallback>
#include <osg/LineWidth>
#include <osg/Version>

#include <osgDB/ReadFile>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

// Standard includes
#include <iostream>
#include <cmath> // for floor

/// @brief A struct that does our casting for us.
struct CallbackHelper {
    CallbackHelper(void *userdata)
        : xform(static_cast<osg::MatrixTransform *>(userdata)),
          iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {}
    osg::MatrixTransform *xform;
    OSVRInterfaceData *iface;
};

void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
                  const OSVR_PoseReport *report) {
    CallbackHelper cb(userdata);
    cb.xform->setMatrix(toMatrix(report->pose));

    // std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}

void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
                         const OSVR_OrientationReport *report) {
    CallbackHelper cb(userdata);
    osg::Matrix mat = cb.xform->getMatrix();
    mat.setRotate(toQuat(report->rotation));
    cb.xform->setMatrix(mat);

    // std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}

/// A little utility class to draw a simple grid.
class Grid : public osg::Group {
  public:
    Grid(unsigned int line_count = 49, float line_spacing = 1.0f,
         unsigned int bold_every_n = 0) {
        this->addChild(make_grid(line_count, line_spacing));
#if 0
        std::cout << "Regular: count = " << line_count
                  << ", spacing = " << line_spacing << std::endl;
#endif

        // Bold grid
        if (bold_every_n > 0) {
            line_count = static_cast<unsigned int>(
                             std::floor(line_count / bold_every_n)) +
                         1;
            line_spacing *= bold_every_n;

#if 0
            std::cout << "Bold: count = " << line_count
                      << ", spacing = " << line_spacing << std::endl;
#endif
            osg::MatrixTransform *mt = make_grid(line_count, line_spacing);

            osg::StateSet *stateset = new osg::StateSet();
            osg::LineWidth *linewidth = new osg::LineWidth();
            linewidth->setWidth(2.0f);
            stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
            stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
            mt->setStateSet(stateset);

            this->addChild(mt);
        }

        // Heavy origin lines
        this->addChild(make_axes(line_count, line_spacing));
    }

    osg::MatrixTransform *make_grid(const unsigned int line_count,
                                    const float line_spacing) {
        const unsigned int numVertices = 2 * 2 * line_count;
        osg::Vec3Array *vertices = new osg::Vec3Array(numVertices);
        float length = static_cast<float>(line_count - 1) * line_spacing;
        osg::Vec3Array::size_type ptr = 0;

        for (unsigned int i = 0; i < line_count; ++i) {
            (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
                                   length / 2.0f, 0.0f);
            (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
                                   -length / 2.0f, 0.0f);
        }

        for (unsigned int i = 0; i < line_count; ++i) {
            (*vertices)[ptr++].set(length / 2.0f,
                                   -length / 2.0f + i * line_spacing, 0.0f);
            (*vertices)[ptr++].set(-length / 2.0f,
                                   -length / 2.0f + i * line_spacing, 0.0f);
        }

        osg::Geometry *geometry = new osg::Geometry;
        geometry->setVertexArray(vertices);
        geometry->addPrimitiveSet(new osg::DrawArrays(
            osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices)));

        osg::Geode *geode = new osg::Geode;
        geode->addDrawable(geometry);
        geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);

        osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
        grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
        grid_transform->addChild(geode);

        return grid_transform;
    }

    osg::MatrixTransform *make_axes(const unsigned int line_count,
                                    const float line_spacing) {
        const float length = (line_count - 1) * line_spacing;
        const int num_vertices = 6;
        osg::Vec3Array *vertices = new osg::Vec3Array(num_vertices);
        (*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f);
        (*vertices)[1].set(length / 2.0f, 0.0f, 0.0f);
        (*vertices)[2].set(0.0f, -length / 2.0f, 0.0f);
        (*vertices)[3].set(0.0f, length / 2.0f, 0.0f);
        (*vertices)[4].set(0.0f, 0.0f, -length / 2.0f);
        (*vertices)[5].set(0.0f, 0.0f, length / 2.0f);

        osg::Vec4Array *colors = new osg::Vec4Array(num_vertices);
        (*colors)[0].set(1.0, 0.0, 0.0, 1.0);
        (*colors)[1].set(1.0, 0.0, 0.0, 1.0);
        (*colors)[2].set(0.0, 0.0, 1.0, 1.0);
        (*colors)[3].set(0.0, 0.0, 1.0, 1.0);
        (*colors)[4].set(0.0, 1.0, 0.0, 1.0);
        (*colors)[5].set(0.0, 1.0, 0.0, 1.0);

        osg::Geometry *geometry = new osg::Geometry;
        geometry->setVertexArray(vertices);
        geometry->addPrimitiveSet(
            new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices));
#if OSG_VERSION_GREATER_THAN(3, 1, 7)
        geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
#else
        geometry->setColorArray(colors);
        geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
#endif

        osg::Geode *geode = new osg::Geode;
        geode->addDrawable(geometry);
        geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);

        osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
        grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
        grid_transform->addChild(geode);

        osg::StateSet *stateset = new osg::StateSet();
        osg::LineWidth *linewidth = new osg::LineWidth();
        linewidth->setWidth(4.0f);
        stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
        stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
        grid_transform->setStateSet(stateset);

        return grid_transform;
    }
};

static const char MODEL_FN[] = "RPAxes.osg";

class TrackerViewApp {
  public:
    static double worldAxesScale() { return 0.2; }
    static double trackerAxesScale() { return 0.1; }

    TrackerViewApp()
        : m_ctx(new OSVRContext(
              "org.osvr.trackerview")) /// Set up OSVR: making an OSG
                                       /// ref-counted object hold
                                       /// the context.
          ,
          m_scene(new osg::PositionAttitudeTransform),
          m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) {

        /// Transform into default OSVR coordinate system: z near.
        m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0)));

        /// Set the root node's update callback to run the OSVR update,
        /// and give it the context ref
        m_scene->setUpdateCallback(new OSVRUpdateCallback);
        m_scene->setUserData(m_ctx.get());

        /// Load the basic model for axes
        osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile(MODEL_FN);
        if (!axes) {
            std::cerr << "Error: Could not read model " << MODEL_FN
                      << std::endl;
            throw std::runtime_error("Could not load model");
        }

        //{
        //    /// World axes
        //    osg::ref_ptr<osg::MatrixTransform> worldAxes =
        //        new osg::MatrixTransform;
        //    worldAxes->setMatrix(osg::Matrixd::scale(
        //        worldAxesScale(), worldAxesScale(), worldAxesScale()));
        //    worldAxes->addChild(axes);
        //    m_scene->addChild(worldAxes.get());
        //}

        /// Small axes for trackers
        m_smallAxes->setMatrix(osg::Matrixd::scale(
            trackerAxesScale(), trackerAxesScale(), trackerAxesScale()));
        m_smallAxes->addChild(axes.get());

        /// Grid
        m_scene->addChild(new Grid(16, 0.1f, 5));
    }

    osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; }

    void addPoseTracker(std::string const &path) {
        m_addTracker(&poseCallback, path);
        m_numTrackers++;
    }

    void addOrientationTracker(std::string const &path) {
        osg::ref_ptr<osg::MatrixTransform> node =
            m_addTracker(&orientationCallback, path);

        /*
        /// Offset orientation-only trackers up by 1 unit (meter)
        osg::Matrix mat;
        mat.setTrans(0, 1, 0);
        node->setMatrix(mat);
        */

        m_numTrackers++;
    }

    int getNumTrackers() const { return m_numTrackers; }

  private:
    template <typename CallbackType>
    osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb,
                                                    std::string const &path) {
        /// Make scenegraph portion
        osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform;
        node->addChild(m_smallAxes);
        m_scene->addChild(node);

        /// Get OSVR interface and set callback
        osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path);
        data->getInterface().registerCallback(cb,
                                              static_cast<void *>(node.get()));

        /// Transfer ownership of the interface holder to the node
        node->setUserData(data.get());

        return node;
    }
    osg::ref_ptr<OSVRContext> m_ctx;
    osg::ref_ptr<osg::PositionAttitudeTransform> m_scene;
    osg::ref_ptr<osg::MatrixTransform> m_smallAxes;

    int m_numTrackers;
};

int main(int argc, char **argv) {
    /// Parse arguments
    osg::ArgumentParser args(&argc, argv);
    args.getApplicationUsage()->setApplicationName(args.getApplicationName());
    args.getApplicationUsage()->setDescription(
        args.getApplicationName() +
        " is a tool for visualizing tracking data from the OSVR system.");
    args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() +
                                                    " [options] osvrpath ...");
    args.getApplicationUsage()->addCommandLineOption(
        "--orientation <path>", "add an orientation tracker");
    args.getApplicationUsage()->addCommandLineOption("--pose <path>",
                                                     "add a pose tracker");

    /// Init the OSG viewer
    osgViewer::Viewer viewer(args);
    viewer.setUpViewInWindow(20, 20, 640, 480);

    osg::ApplicationUsage::Type helpType;
    if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) {
        args.getApplicationUsage()->write(std::cerr);
        return 1;
    }

    if (args.errors()) {
        args.writeErrorMessages(std::cerr);
        return 1;
    }
    try {
        TrackerViewApp app;

        std::string path;

        // Get pose paths
        while (args.read("--pose", path)) {
            app.addPoseTracker(path);
        }

        // Get orientation paths
        while (args.read("--orientation", path)) {
            app.addOrientationTracker(path);
        }

        // Assume free strings are pose paths
        for (int pos = 1; pos < args.argc(); ++pos) {
            if (args.isOption(pos))
                continue;

            app.addPoseTracker(args[pos]);
        }
        // If no trackers were specified, fall back on these defaults
        if (0 == app.getNumTrackers()) {
            std::cout << "\n\nTracker Viewer: No valid arguments passed: using "
                         "a default of --pose "
                         "/me/hands/left --pose /me/hands/right --pose "
                         "/me/head\nYou can specify --pose or --orientation "
                         "then a path for as many tracker sensors as you want. "
                         "Run with the command line argument --help "
                         "for more info.\n"
                      << std::endl;
            app.addPoseTracker("/me/hands/left");
            app.addPoseTracker("/me/hands/right");
            app.addPoseTracker("/me/head");
        }
        args.reportRemainingOptionsAsUnrecognized();

        if (args.errors()) {
            args.writeErrorMessages(std::cerr);
            return 1;
        }

        viewer.setSceneData(app.getScene());
    } catch (std::exception const &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        std::cerr << "Press enter to exit!" << std::endl;
        std::cin.ignore();
        return -1;
    }

    viewer.setCameraManipulator(new osgGA::TrackballManipulator());

    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
    /// Go!
    viewer.realize();

    return viewer.run();
}
<commit_msg>Remove boatanchor.<commit_after>/** @file
    @brief Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2014 Sensics, Inc.
//
// 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.

// Internal Includes
#include "OSVRUpdateCallback.h"
#include "OSGMathInterop.h"
#include "OSVRInterfaceData.h"
#include "OSVRContext.h"

// Library/third-party includes
#include <osvr/ClientKit/ClientKit.h>

#include <osg/ref_ptr>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/NodeCallback>
#include <osg/LineWidth>
#include <osg/Version>

#include <osgDB/ReadFile>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

// Standard includes
#include <iostream>
#include <cmath> // for floor

/// @brief A struct that does our casting for us.
struct CallbackHelper {
    CallbackHelper(void *userdata)
        : xform(static_cast<osg::MatrixTransform *>(userdata)),
          iface(dynamic_cast<OSVRInterfaceData *>(xform->getUserData())) {}
    osg::MatrixTransform *xform;
    OSVRInterfaceData *iface;
};

void poseCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
                  const OSVR_PoseReport *report) {
    CallbackHelper cb(userdata);
    cb.xform->setMatrix(toMatrix(report->pose));

    // std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}

void orientationCallback(void *userdata, const OSVR_TimeValue * /*timestamp*/,
                         const OSVR_OrientationReport *report) {
    CallbackHelper cb(userdata);
    osg::Matrix mat = cb.xform->getMatrix();
    mat.setRotate(toQuat(report->rotation));
    cb.xform->setMatrix(mat);

    // std::cout << "Got report for " << cb.iface->getPath() << std::endl;
}

/// A little utility class to draw a simple grid.
class Grid : public osg::Group {
  public:
    Grid(unsigned int line_count = 49, float line_spacing = 1.0f,
         unsigned int bold_every_n = 0) {
        this->addChild(make_grid(line_count, line_spacing));
#if 0
        std::cout << "Regular: count = " << line_count
                  << ", spacing = " << line_spacing << std::endl;
#endif

        // Bold grid
        if (bold_every_n > 0) {
            line_count = static_cast<unsigned int>(
                             std::floor(line_count / bold_every_n)) +
                         1;
            line_spacing *= bold_every_n;

#if 0
            std::cout << "Bold: count = " << line_count
                      << ", spacing = " << line_spacing << std::endl;
#endif
            osg::MatrixTransform *mt = make_grid(line_count, line_spacing);

            osg::StateSet *stateset = new osg::StateSet();
            osg::LineWidth *linewidth = new osg::LineWidth();
            linewidth->setWidth(2.0f);
            stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
            stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
            mt->setStateSet(stateset);

            this->addChild(mt);
        }

        // Heavy origin lines
        this->addChild(make_axes(line_count, line_spacing));
    }

    osg::MatrixTransform *make_grid(const unsigned int line_count,
                                    const float line_spacing) {
        const unsigned int numVertices = 2 * 2 * line_count;
        osg::Vec3Array *vertices = new osg::Vec3Array(numVertices);
        float length = static_cast<float>(line_count - 1) * line_spacing;
        osg::Vec3Array::size_type ptr = 0;

        for (unsigned int i = 0; i < line_count; ++i) {
            (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
                                   length / 2.0f, 0.0f);
            (*vertices)[ptr++].set(-length / 2.0f + i * line_spacing,
                                   -length / 2.0f, 0.0f);
        }

        for (unsigned int i = 0; i < line_count; ++i) {
            (*vertices)[ptr++].set(length / 2.0f,
                                   -length / 2.0f + i * line_spacing, 0.0f);
            (*vertices)[ptr++].set(-length / 2.0f,
                                   -length / 2.0f + i * line_spacing, 0.0f);
        }

        osg::Geometry *geometry = new osg::Geometry;
        geometry->setVertexArray(vertices);
        geometry->addPrimitiveSet(new osg::DrawArrays(
            osg::PrimitiveSet::LINES, 0, static_cast<GLsizei>(numVertices)));

        osg::Geode *geode = new osg::Geode;
        geode->addDrawable(geometry);
        geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);

        osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
        grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
        grid_transform->addChild(geode);

        return grid_transform;
    }

    osg::MatrixTransform *make_axes(const unsigned int line_count,
                                    const float line_spacing) {
        const float length = (line_count - 1) * line_spacing;
        const int num_vertices = 6;
        osg::Vec3Array *vertices = new osg::Vec3Array(num_vertices);
        (*vertices)[0].set(-length / 2.0f, 0.0f, 0.0f);
        (*vertices)[1].set(length / 2.0f, 0.0f, 0.0f);
        (*vertices)[2].set(0.0f, -length / 2.0f, 0.0f);
        (*vertices)[3].set(0.0f, length / 2.0f, 0.0f);
        (*vertices)[4].set(0.0f, 0.0f, -length / 2.0f);
        (*vertices)[5].set(0.0f, 0.0f, length / 2.0f);

        osg::Vec4Array *colors = new osg::Vec4Array(num_vertices);
        (*colors)[0].set(1.0, 0.0, 0.0, 1.0);
        (*colors)[1].set(1.0, 0.0, 0.0, 1.0);
        (*colors)[2].set(0.0, 0.0, 1.0, 1.0);
        (*colors)[3].set(0.0, 0.0, 1.0, 1.0);
        (*colors)[4].set(0.0, 1.0, 0.0, 1.0);
        (*colors)[5].set(0.0, 1.0, 0.0, 1.0);

        osg::Geometry *geometry = new osg::Geometry;
        geometry->setVertexArray(vertices);
        geometry->addPrimitiveSet(
            new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, num_vertices));
#if OSG_VERSION_GREATER_THAN(3, 1, 7)
        geometry->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
#else
        geometry->setColorArray(colors);
        geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
#endif

        osg::Geode *geode = new osg::Geode;
        geode->addDrawable(geometry);
        geode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0);

        osg::MatrixTransform *grid_transform = new osg::MatrixTransform;
        grid_transform->setMatrix(osg::Matrix::rotate(osg::PI_2, 1, 0, 0));
        grid_transform->addChild(geode);

        osg::StateSet *stateset = new osg::StateSet();
        osg::LineWidth *linewidth = new osg::LineWidth();
        linewidth->setWidth(4.0f);
        stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
        stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
        grid_transform->setStateSet(stateset);

        return grid_transform;
    }
};

static const char MODEL_FN[] = "RPAxes.osg";

class TrackerViewApp {
  public:
    static double worldAxesScale() { return 0.2; }
    static double trackerAxesScale() { return 0.1; }

    TrackerViewApp()
        : m_ctx(new OSVRContext(
              "org.osvr.trackerview")) /// Set up OSVR: making an OSG
                                       /// ref-counted object hold
                                       /// the context.
          ,
          m_scene(new osg::PositionAttitudeTransform),
          m_smallAxes(new osg::MatrixTransform), m_numTrackers(0) {

        /// Transform into default OSVR coordinate system: z near.
        m_scene->setAttitude(osg::Quat(90, osg::Vec3(1, 0, 0)));

        /// Set the root node's update callback to run the OSVR update,
        /// and give it the context ref
        m_scene->setUpdateCallback(new OSVRUpdateCallback);
        m_scene->setUserData(m_ctx.get());

        /// Load the basic model for axes
        osg::ref_ptr<osg::Node> axes = osgDB::readNodeFile(MODEL_FN);
        if (!axes) {
            std::cerr << "Error: Could not read model " << MODEL_FN
                      << std::endl;
            throw std::runtime_error("Could not load model");
        }

        /// Small axes for trackers
        m_smallAxes->setMatrix(osg::Matrixd::scale(
            trackerAxesScale(), trackerAxesScale(), trackerAxesScale()));
        m_smallAxes->addChild(axes.get());

        /// Grid
        m_scene->addChild(new Grid(16, 0.1f, 5));
    }

    osg::ref_ptr<osg::PositionAttitudeTransform> getScene() { return m_scene; }

    void addPoseTracker(std::string const &path) {
        m_addTracker(&poseCallback, path);
        m_numTrackers++;
    }

    void addOrientationTracker(std::string const &path) {
        osg::ref_ptr<osg::MatrixTransform> node =
            m_addTracker(&orientationCallback, path);

        /*
        /// Offset orientation-only trackers up by 1 unit (meter)
        osg::Matrix mat;
        mat.setTrans(0, 1, 0);
        node->setMatrix(mat);
        */

        m_numTrackers++;
    }

    int getNumTrackers() const { return m_numTrackers; }

  private:
    template <typename CallbackType>
    osg::ref_ptr<osg::MatrixTransform> m_addTracker(CallbackType cb,
                                                    std::string const &path) {
        /// Make scenegraph portion
        osg::ref_ptr<osg::MatrixTransform> node = new osg::MatrixTransform;
        node->addChild(m_smallAxes);
        m_scene->addChild(node);

        /// Get OSVR interface and set callback
        osg::ref_ptr<OSVRInterfaceData> data = m_ctx->getInterface(path);
        data->getInterface().registerCallback(cb,
                                              static_cast<void *>(node.get()));

        /// Transfer ownership of the interface holder to the node
        node->setUserData(data.get());

        return node;
    }
    osg::ref_ptr<OSVRContext> m_ctx;
    osg::ref_ptr<osg::PositionAttitudeTransform> m_scene;
    osg::ref_ptr<osg::MatrixTransform> m_smallAxes;

    int m_numTrackers;
};

int main(int argc, char **argv) {
    /// Parse arguments
    osg::ArgumentParser args(&argc, argv);
    args.getApplicationUsage()->setApplicationName(args.getApplicationName());
    args.getApplicationUsage()->setDescription(
        args.getApplicationName() +
        " is a tool for visualizing tracking data from the OSVR system.");
    args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName() +
                                                    " [options] osvrpath ...");
    args.getApplicationUsage()->addCommandLineOption(
        "--orientation <path>", "add an orientation tracker");
    args.getApplicationUsage()->addCommandLineOption("--pose <path>",
                                                     "add a pose tracker");

    /// Init the OSG viewer
    osgViewer::Viewer viewer(args);
    viewer.setUpViewInWindow(20, 20, 640, 480);

    osg::ApplicationUsage::Type helpType;
    if ((helpType = args.readHelpType()) != osg::ApplicationUsage::NO_HELP) {
        args.getApplicationUsage()->write(std::cerr);
        return 1;
    }

    if (args.errors()) {
        args.writeErrorMessages(std::cerr);
        return 1;
    }
    try {
        TrackerViewApp app;

        std::string path;

        // Get pose paths
        while (args.read("--pose", path)) {
            app.addPoseTracker(path);
        }

        // Get orientation paths
        while (args.read("--orientation", path)) {
            app.addOrientationTracker(path);
        }

        // Assume free strings are pose paths
        for (int pos = 1; pos < args.argc(); ++pos) {
            if (args.isOption(pos))
                continue;

            app.addPoseTracker(args[pos]);
        }
        // If no trackers were specified, fall back on these defaults
        if (0 == app.getNumTrackers()) {
            std::cout << "\n\nTracker Viewer: No valid arguments passed: using "
                         "a default of --pose "
                         "/me/hands/left --pose /me/hands/right --pose "
                         "/me/head\nYou can specify --pose or --orientation "
                         "then a path for as many tracker sensors as you want. "
                         "Run with the command line argument --help "
                         "for more info.\n"
                      << std::endl;
            app.addPoseTracker("/me/hands/left");
            app.addPoseTracker("/me/hands/right");
            app.addPoseTracker("/me/head");
        }
        args.reportRemainingOptionsAsUnrecognized();

        if (args.errors()) {
            args.writeErrorMessages(std::cerr);
            return 1;
        }

        viewer.setSceneData(app.getScene());
    } catch (std::exception const &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        std::cerr << "Press enter to exit!" << std::endl;
        std::cin.ignore();
        return -1;
    }

    viewer.setCameraManipulator(new osgGA::TrackballManipulator());

    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
    /// Go!
    viewer.realize();

    return viewer.run();
}
<|endoftext|>


<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Thomas Krennwallner
 * Copyright (C) 2009, 2010, 2011 Peter Schüller
 * Copyright (C) 2011, 2012, 2013 Christoph Redl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex 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 dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file DLPlugin.cpp
 * @author Christoph Redl
 *
 * @brief Provides dummy implementations of external predicates
 *        which are never evaluated. This is useful in combination
 *        with special model generators.
 */

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

#include "dlvhex2/DLPlugin.h"
#include "dlvhex2/PlatformDefinitions.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Logger.h"
#include <iostream>
#include <string>
#include "boost/program_options.hpp"
#include "boost/range.hpp"
#include "boost/foreach.hpp"
#include "boost/filesystem.hpp"

#if defined(HAVE_OWLCPP)
#include "owlcpp/rdf/triple_store.hpp"
#include "owlcpp/io/input.hpp"
#include "owlcpp/io/catalog.hpp"
#include "owlcpp/terms/node_tags_owl.hpp"

#endif //HAVE_OWLCPP

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

DLVHEX_NAMESPACE_BEGIN

namespace
{
	// ***** Impementation of DL plugin
class CDLAtom:	// tests user-defined external learning
  public PluginAtom
{

public:		// testDL is the name of our external atom
    	CDLAtom():
	PluginAtom("cDL", true) // monotonic
  {
		DBGLOG(DBG,"Constructor of DL plugin is started");
		addInputConstant(); // the ontology
    	addInputPredicate(); // the positive concept
    	addInputPredicate(); // the negative concept
		addInputPredicate(); // the positive role
		addInputPredicate(); // the negative role
		addInputConstant(); // the query
    	setOutputArity(1); // arity of the output list
  }

virtual void retrieve(const Query& query, Answer& answer)
  {
	assert(false);
  }

// If there is a function with nogoods then the one without nogoods should never be called
// function that evaluates external atom with learning
// input parameters:
// 1. Query is a class, defined in PluginInterface.h (struct DLVHEX_EXPORT Query)
// 2. Answer is a class, defined in PluginInterface.h (struct DLVHEX_EXPORT Answer)
// 3. Learnt Nogoods

  virtual void retrieve(const Query& query, Answer& answer, NogoodContainerPtr nogoods)
  {

	#if defined(HAVE_OWLCPP)

	  DBGLOG(DBG,"*****Retrieve is started");

	  DBGLOG(DBG,"*****Construction of the program for computing the TBox closure");

	  DBGLOG(DBG,"*****1. Transitivity rule: sub(Y,Z):-sub(X,Y),sub(Y,Z)");

	RegistryPtr reg = getRegistry();
	ID subid = reg->storeConstantTerm("sub");
	ID xid = reg->storeVariableTerm("X");
	ID yid = reg->storeVariableTerm("Y");
	ID zid = reg->storeVariableTerm("Z");

	//reg->terms.getByID to get it

	OrdinaryAtom bodysub1 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodysub1.tuple.push_back(subid);
	bodysub1.tuple.push_back(xid);
	bodysub1.tuple.push_back(yid);

	OrdinaryAtom bodysub2 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodysub2.tuple.push_back(subid);
	bodysub2.tuple.push_back(yid);
	bodysub2.tuple.push_back(zid);

	OrdinaryAtom headsub (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	headsub.tuple.push_back(subid);
	headsub.tuple.push_back(yid);
	headsub.tuple.push_back(zid);

	ID bodysub1id = reg->storeOrdinaryAtom(bodysub1);
	ID bodysub2id = reg->storeOrdinaryAtom(bodysub2);
	ID headsubid = reg->storeOrdinaryAtom(headsub);

	Rule trans(ID::MAINKIND_RULE);
	trans.body.push_back(bodysub1id);
	trans.body.push_back(bodysub2id);
	trans.head.push_back(headsubid);
	ID transid = reg->storeRule(trans);

	DBGLOG(DBG,"*****2. Contraposition rule: sub(Y',X'):-op(X,X'),op(Y,Y'),sub(X,Y).");

	DBGLOG(DBG,"*****3. Conflict rule: conf(X,Y):-op(X,Y),sub(X,Y).");

	std::string ontoName = getRegistry()->terms.getByID(query.input[0]).getUnquotedString();
	DBGLOG(DBG,"******Name of the onto");
	DBGLOG(DBG,ontoName);

	owlcpp::Triple_store store;
	owlcpp::Triple_store::result_b<0,0,0,0>::type r = store.find_triple(
			   	   owlcpp::any(),
				   owlcpp::any(),
				   owlcpp::any(),
	               owlcpp::any());
	DBGLOG(DBG,"******Before loading the file");
	load_file("/home/dasha/ontologies/taxi/taxi.owl",store);
	DBGLOG(DBG,"******onto File is loaded");
	BOOST_FOREACH( owlcpp::Triple const& t, store.map_triple() ) {
				if (to_string(t.subj_,store)=="owl:Class") {
		        	DBGLOG(DBG,to_string(t.subj_, store));
		        	DBGLOG(DBG,"Construct facts of the form op(C,negC), sub(C,C) for this class.");
				}
				if (to_string(t.subj_,store)=="owl:ObjectProperty") {
						        	DBGLOG(DBG,to_string(t.subj_, store));
						        	DBGLOG(DBG,"Construct facts of the form op(Subj,negSubj), sub(Subj,Subj), sup(Subj,Subj)");
				}

				if (to_string(t.pred_,store)=="owl:subClassOf")
				{
									DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store) << to_string(t.obj_, store));
									DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
				}

				if (to_string(t.pred_,store)=="owl:subPropertyOf")
								{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
								}

				if (to_string(t.pred_,store)=="owl:disjointWith")
								{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,negObj)");
								}
				if (to_string(t.pred_,store)=="owl:propertyDisjointWith")
											{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
											}
				if (to_string(t.pred_,store)=="rdfs:Domain")
															{
																	DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
																	DBGLOG(DBG,"Construct facts of the form sub(exSubj,Obj)");
															}

	         }

	// Iterators (objects that mark the begin and the end of some structure)

	bm::bvector<>::enumerator en = query.interpretation->getStorage().first();
	bm::bvector<>::enumerator en_end = query.interpretation->getStorage().end();

	std::vector<Tuple> tuples1;
	std::vector<Tuple> tuples2;
	std::vector<Tuple> tuples3;
	std::vector<Tuple> tuples4;

	// go through all atoms using the iterator
	while (en < en_end){
	// extract the current atom
	// *emn is the id of the current atom, to which the iterator points
		const OrdinaryAtom& atom = getRegistry()->ogatoms.getByID(ID(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *en));
		Tuple tu;
	// Iterate over the input elements of the current atom (for p(x,y), we go through x and y)
	// We start with 1 because the position 0 is the predicate itself
		for (int i = 1; i < atom.tuple.size(); ++i){
	// Get element number i from the input list
			tu.push_back(atom.tuple[i]);
		}

		if (atom.tuple[0] == query.input[1]){
			tuples1.push_back(tu);
		}
		if (atom.tuple[0] == query.input[2]){
			tuples2.push_back(tu);
		}
		if (atom.tuple[0] == query.input[3]){
			tuples3.push_back(tu);
		}
		if (atom.tuple[0] == query.input[4]){
			tuples4.push_back(tu);
		}
		en++;
	}

	// for each element t of tuples1 add t to the answer
	BOOST_FOREACH (Tuple t, tuples1){
		answer.get().push_back(t);
		// G in the end stands for ground learning (N for nonground)
		// Create a new object where we store the copy of the first input predictae
		OrdinaryAtom at1(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG);
		// Copy input predicate with the parameters to at1
		at1.tuple.push_back(query.input[1]);
		// arity is always 1 here
		BOOST_FOREACH (ID i, t) {
		at1.tuple.push_back(i);
		}
		// Start with empty nogood
		Nogood nogood;
		// Add the first literal
		// In case of a nonground nogood, we need to store NAtom (storeOrdinaryNAtom)
		// First true is the sign of the literal
		// Second parameter is true if we create ground nogood

		nogood.insert(NogoodContainer::createLiteral(getRegistry()->storeOrdinaryGAtom(at1).address, true, true));

		// ExternalLearningHelper is a function that helps to create an element in a nogood for external atom: call the function for the given output tuple
		// Always the same (add the false output in case if under the input parameters the result is true)
		//nogood.insert(NogoodContainer::createLiteral(ExternalLearningHelper::getOutputAtom(query, t, false).address, true, false));
		// add the nogood to the set of all nogoods if nogoods is not zero
		if (!!nogoods)
			nogoods->addNogood(nogood);
    DBGLOG(DBG,"nogood is " << nogood);

	}

	BOOST_FOREACH (Tuple t, tuples2){
		answer.get().push_back(t);
	}
BOOST_FOREACH (Tuple t, tuples2){
		answer.get().push_back(t);
	}
BOOST_FOREACH (Tuple t, tuples3){
		answer.get().push_back(t);
	}
#endif //HAVE_OWLCPP
  }

};

//Define the RDlatom class for roles
}

// Collect all types of external atoms
DLPlugin::DLPlugin():
	PluginInterface()
{
	setNameVersion("dlvhex-DLplugin[internal]", 2, 0, 0);
}

DLPlugin::~DLPlugin()
{
}

// Define two external atoms: for the roles and for the concept queries

std::vector<PluginAtomPtr> DLPlugin::createAtoms(ProgramCtx& ctx) const{
	std::vector<PluginAtomPtr> ret;

		ret.push_back(PluginAtomPtr(new CDLAtom()));
		//ret.push_back(PluginAtomPtr(new DLPluginAtom("repairDLR", false, it, 2)));

	return ret;
}

DLVHEX_NAMESPACE_END

// this would be the code to use this plugin as a "real" plugin in a .so file
// but we directly use it in dlvhex.cpp
#if 0
DLPlugin theDLPlugin;

// return plain C type s.t. all compilers and linkers will like this code
extern "C"
void * PLUGINIMPORTFUNCTION()
{
	return reinterpret_cast<void*>(& DLVHEX_NAMESPACE theDLPlugin);
}

#endif
/* vim: set noet sw=2 ts=2 tw=80: */

// Local Variables:
// mode: C++
// End:
<commit_msg>DL-plugin updates<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Thomas Krennwallner
 * Copyright (C) 2009, 2010, 2011 Peter Schüller
 * Copyright (C) 2011, 2012, 2013 Christoph Redl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex 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 dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file DLPlugin.cpp
 * @author Christoph Redl
 *
 * @brief Provides dummy implementations of external predicates
 *        which are never evaluated. This is useful in combination
 *        with special model generators.
 */

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

#include "dlvhex2/DLPlugin.h"
#include "dlvhex2/PlatformDefinitions.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Logger.h"
#include <iostream>
#include <string>
#include "boost/program_options.hpp"
#include "boost/range.hpp"
#include "boost/foreach.hpp"
#include "boost/filesystem.hpp"

#if defined(HAVE_OWLCPP)
#include "owlcpp/rdf/triple_store.hpp"
#include "owlcpp/io/input.hpp"
#include "owlcpp/io/catalog.hpp"
#include "owlcpp/terms/node_tags_owl.hpp"

#endif //HAVE_OWLCPP

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

DLVHEX_NAMESPACE_BEGIN

namespace
{
	// ***** Impementation of DL plugin
class CDLAtom:	// tests user-defined external learning
  public PluginAtom
{

public:		// testDL is the name of our external atom
    	CDLAtom():
	PluginAtom("cDL", true) // monotonic
  {
		DBGLOG(DBG,"Constructor of DL plugin is started");
		addInputConstant(); // the ontology
    	addInputPredicate(); // the positive concept
    	addInputPredicate(); // the negative concept
		addInputPredicate(); // the positive role
		addInputPredicate(); // the negative role
		addInputConstant(); // the query
    	setOutputArity(1); // arity of the output list
  }

virtual void retrieve(const Query& query, Answer& answer)
  {
	assert(false);
  }

// If there is a function with nogoods then the one without nogoods should never be called
// function that evaluates external atom with learning
// input parameters:
// 1. Query is a class, defined in PluginInterface.h (struct DLVHEX_EXPORT Query)
// 2. Answer is a class, defined in PluginInterface.h (struct DLVHEX_EXPORT Answer)
// 3. Learnt Nogoods

  virtual void retrieve(const Query& query, Answer& answer, NogoodContainerPtr nogoods)
  {

	#if defined(HAVE_OWLCPP)

	  DBGLOG(DBG,"*****Retrieve is started");

	  DBGLOG(DBG,"*****Construction of the program for computing the TBox closure");

	  DBGLOG(DBG,"*****1. Transitivity rule: sub(X,Z):-sub(X,Y),sub(Y,Z)");

	RegistryPtr reg = getRegistry();
	ID subid = reg->storeConstantTerm("sub");
	ID xid = reg->storeVariableTerm("X");
	ID yid = reg->storeVariableTerm("Y");
	ID zid = reg->storeVariableTerm("Z");

	DBGLOG(DBG,"*****Create atom sub(X,Y)");
	OrdinaryAtom bodysub1 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodysub1.tuple.push_back(subid);
	bodysub1.tuple.push_back(xid);
	bodysub1.tuple.push_back(yid);

	DBGLOG(DBG,"*****Create atom sub(Y,Z)");
	OrdinaryAtom bodysub2 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodysub2.tuple.push_back(subid);
	bodysub2.tuple.push_back(yid);
	bodysub2.tuple.push_back(zid);

	DBGLOG(DBG,"*****Create atom sub(X,Z)");
	OrdinaryAtom headsub (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	headsub.tuple.push_back(subid);
	headsub.tuple.push_back(yid);
	headsub.tuple.push_back(zid);

	ID bodysub1id = reg->storeOrdinaryAtom(bodysub1);
	ID bodysub2id = reg->storeOrdinaryAtom(bodysub2);
	ID headsubid = reg->storeOrdinaryAtom(headsub);

	DBGLOG(DBG,"*****Create a rule");
	Rule trans(ID::MAINKIND_RULE);
	trans.body.push_back(bodysub1id);
	trans.body.push_back(bodysub2id);
	trans.head.push_back(headsubid);
	ID transid = reg->storeRule(trans);

	DBGLOG(DBG,"*****2. Contraposition rule: sub(Y',X'):-op(X,X'),op(Y,Y'),sub(X,Y).");

	ID opid = reg->storeConstantTerm("op");
	ID nxid = reg->storeVariableTerm("NX");
	ID nyid = reg->storeVariableTerm("NY");

	OrdinaryAtom bodyop1 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodyop1.tuple.push_back(opid);
	bodyop1.tuple.push_back(xid);
	bodyop1.tuple.push_back(nxid);

	OrdinaryAtom bodyop2 (ID::MAINKIND_ATOM|ID::SUBKIND_ATOM_ORDINARYN);
	bodyop2.tuple.push_back(opid);
	bodyop2.tuple.push_back(yid);
	bodyop2.tuple.push_back(nyid);

/*	Rule op(ID::MAINKIND_RULE);
	op.body.push_back(bodyop1);
	op.body.push_back(bodyop2);
	op.head.push_back(bodysub1);

	ID opid = reg->storeRule(op);
*/

	DBGLOG(DBG,"*****3. Conflict rule: conf(X,Y):-op(X,Y),sub(X,Y).");

	std::string ontoName = getRegistry()->terms.getByID(query.input[0]).getUnquotedString();
	DBGLOG(DBG,"******Name of the onto");
	DBGLOG(DBG,ontoName);

	owlcpp::Triple_store store;
	owlcpp::Triple_store::result_b<0,0,0,0>::type r = store.find_triple(
			   	   owlcpp::any(),
				   owlcpp::any(),
				   owlcpp::any(),
	               owlcpp::any());
	DBGLOG(DBG,"******Before loading the file");
	load_file("/home/dasha/ontologies/taxi/taxi.owl",store);
	DBGLOG(DBG,"******onto File is loaded");
	BOOST_FOREACH( owlcpp::Triple const& t, store.map_triple() ) {
				if (to_string(t.subj_,store)=="owl:Class") {
		        	DBGLOG(DBG,to_string(t.subj_, store));
		        	DBGLOG(DBG,"Construct facts of the form op(C,negC), sub(C,C) for this class.");
				}
				if (to_string(t.subj_,store)=="owl:ObjectProperty") {
						        	DBGLOG(DBG,to_string(t.subj_, store));
						        	DBGLOG(DBG,"Construct facts of the form op(Subj,negSubj), sub(Subj,Subj), sup(Subj,Subj)");
				}

				if (to_string(t.pred_,store)=="owl:subClassOf")
				{
									DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store) << to_string(t.obj_, store));
									DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
				}

				if (to_string(t.pred_,store)=="owl:subPropertyOf")
								{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
								}

				if (to_string(t.pred_,store)=="owl:disjointWith")
								{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,negObj)");
								}
				if (to_string(t.pred_,store)=="owl:propertyDisjointWith")
											{
													DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
													DBGLOG(DBG,"Construct facts of the form sub(Subj,Obj)");
											}
				if (to_string(t.pred_,store)=="rdfs:Domain")
															{
																	DBGLOG(DBG,to_string(t.subj_, store) << to_string(t.pred_, store)<< to_string(t.obj_, store));
																	DBGLOG(DBG,"Construct facts of the form sub(exSubj,Obj)");
															}

	         }

	// Iterators (objects that mark the begin and the end of some structure)

	bm::bvector<>::enumerator en = query.interpretation->getStorage().first();
	bm::bvector<>::enumerator en_end = query.interpretation->getStorage().end();

	std::vector<Tuple> tuples1;
	std::vector<Tuple> tuples2;
	std::vector<Tuple> tuples3;
	std::vector<Tuple> tuples4;

	// go through all atoms using the iterator
	while (en < en_end){
	// extract the current atom
	// *emn is the id of the current atom, to which the iterator points
		const OrdinaryAtom& atom = getRegistry()->ogatoms.getByID(ID(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *en));
		Tuple tu;
	// Iterate over the input elements of the current atom (for p(x,y), we go through x and y)
	// We start with 1 because the position 0 is the predicate itself
		for (int i = 1; i < atom.tuple.size(); ++i){
	// Get element number i from the input list
			tu.push_back(atom.tuple[i]);
		}

		if (atom.tuple[0] == query.input[1]){
			tuples1.push_back(tu);
		}
		if (atom.tuple[0] == query.input[2]){
			tuples2.push_back(tu);
		}
		if (atom.tuple[0] == query.input[3]){
			tuples3.push_back(tu);
		}
		if (atom.tuple[0] == query.input[4]){
			tuples4.push_back(tu);
		}
		en++;
	}

	// for each element t of tuples1 add t to the answer
	BOOST_FOREACH (Tuple t, tuples1){
		answer.get().push_back(t);
		// G in the end stands for ground learning (N for nonground)
		// Create a new object where we store the copy of the first input predictae
		OrdinaryAtom at1(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG);
		// Copy input predicate with the parameters to at1
		at1.tuple.push_back(query.input[1]);
		// arity is always 1 here
		BOOST_FOREACH (ID i, t) {
		at1.tuple.push_back(i);
		}
		// Start with empty nogood
		Nogood nogood;
		// Add the first literal
		// In case of a nonground nogood, we need to store NAtom (storeOrdinaryNAtom)
		// First true is the sign of the literal
		// Second parameter is true if we create ground nogood

		nogood.insert(NogoodContainer::createLiteral(getRegistry()->storeOrdinaryGAtom(at1).address, true, true));

		// ExternalLearningHelper is a function that helps to create an element in a nogood for external atom: call the function for the given output tuple
		// Always the same (add the false output in case if under the input parameters the result is true)
		//nogood.insert(NogoodContainer::createLiteral(ExternalLearningHelper::getOutputAtom(query, t, false).address, true, false));
		// add the nogood to the set of all nogoods if nogoods is not zero
		if (!!nogoods)
			nogoods->addNogood(nogood);
    DBGLOG(DBG,"nogood is " << nogood);

	}

	BOOST_FOREACH (Tuple t, tuples2){
		answer.get().push_back(t);
	}
BOOST_FOREACH (Tuple t, tuples2){
		answer.get().push_back(t);
	}
BOOST_FOREACH (Tuple t, tuples3){
		answer.get().push_back(t);
	}
#endif //HAVE_OWLCPP
  }

};

//Define the RDlatom class for roles
}

// Collect all types of external atoms
DLPlugin::DLPlugin():
	PluginInterface()
{
	setNameVersion("dlvhex-DLplugin[internal]", 2, 0, 0);
}

DLPlugin::~DLPlugin()
{
}

// Define two external atoms: for the roles and for the concept queries

std::vector<PluginAtomPtr> DLPlugin::createAtoms(ProgramCtx& ctx) const{
	std::vector<PluginAtomPtr> ret;

		ret.push_back(PluginAtomPtr(new CDLAtom()));
		//ret.push_back(PluginAtomPtr(new DLPluginAtom("repairDLR", false, it, 2)));

	return ret;
}

DLVHEX_NAMESPACE_END

// this would be the code to use this plugin as a "real" plugin in a .so file
// but we directly use it in dlvhex.cpp
#if 0
DLPlugin theDLPlugin;

// return plain C type s.t. all compilers and linkers will like this code
extern "C"
void * PLUGINIMPORTFUNCTION()
{
	return reinterpret_cast<void*>(& DLVHEX_NAMESPACE theDLPlugin);
}

#endif
/* vim: set noet sw=2 ts=2 tw=80: */

// Local Variables:
// mode: C++
// End:
<|endoftext|>


<commit_before>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

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.

=========================================================================*/

#ifndef __itktubeTubeXIO_hxx
#define __itktubeTubeXIO_hxx

#include "itktubeTubeXIO.h"

#include "metaUtils.h"

namespace itk
{

namespace tube
{

template< unsigned int TDimension >
TubeXIO< TDimension >
::TubeXIO()
{
  m_TubeGroup = TubeGroupType::New();
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    m_Dimensions[i] = 1;
    }
}

template< unsigned int TDimension >
TubeXIO< TDimension >
::~TubeXIO( void )
{
}

//
template< unsigned int TDimension >
void
TubeXIO< TDimension >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  if( this->m_TubeGroup.IsNotNull() )
    {
    os << indent << "Tube Group = " << this->m_TubeGroup << std::endl;
    }
  else
    {
    os << indent << "Tube Group = NULL" << std::endl;
    }
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Read( const std::string & _fileName )
{
  std::vector< MET_FieldRecordType * > fields;

  MET_FieldRecordType * mF;

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NDims", MET_INT, false);
  fields.push_back(mF);
  int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Dimensions", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "VoxelSize", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NObjects", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "End Header", MET_NONE, false);
  mF->terminateRead = true;
  fields.push_back(mF);

  std::ifstream tmpReadStream( _fileName.c_str(), std::ios::binary |
    std::ios::in );

  if( !tmpReadStream.rdbuf()->is_open() )
    {
    return false;
    }

  std::vector< MET_FieldRecordType * > extraFields;
  if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
    {
    std::cerr << "Tube: Read failed" << std::endl;
    return false;
    }

  mF = MET_GetFieldRecord( "NDims", &fields );
  if( mF->defined )
    {
    int nDims = (int)mF->value[0];

    if( (int)mF->value[0] != TDimension )
      {
      std::cerr << "Tube: Read failed: object is " << nDims
        << " dimensional and was expecting " << TDimension << " dimensional."
        << std::endl;
      return false;
      }
    }

  mF = MET_GetFieldRecord( "Dimensions", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      this->m_Dimensions[i] = (int)( mF->value[i] );
      }
    }

  double voxelSize[ TDimension ];
  mF = MET_GetFieldRecord( "VoxelSize", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      voxelSize[i] = (float)( mF->value[i] );
      }
    }

  int nObjects = 0;
  mF = MET_GetFieldRecord( "NObjects", &fields );
  if(mF->defined)
    {
    nObjects = (int)mF->value[0];
    }

  fields.clear();

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ID", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Type", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Anat", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "TreeType", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Color", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  fields.push_back(mF);

  for( int obj = 0; obj < nObjects; ++obj )
    {
    if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
      {
      std::cerr << "Tube: Read failed" << std::endl;
      return false;
      }

    int tubeId = 0;
    mF = MET_GetFieldRecord( "ID", &fields );
    if(mF->defined)
      {
      tubeId = (int)( mF->value[0] );
      }

    char tubeType[80];
    strcpy( tubeType, "" );
    mF = MET_GetFieldRecord( "Type", &fields );
    if(mF->defined)
      {
      strcpy( tubeType, (char *)(mF->value) );
      }

    char tubeAnat[80];
    strcpy( tubeAnat, "" );
    mF = MET_GetFieldRecord( "Anat", &fields );
    if(mF->defined)
      {
      strcpy( tubeAnat, (char *)(mF->value) );
      }

    char tubeTreeType[80];
    strcpy( tubeTreeType, "" );
    mF = MET_GetFieldRecord( "TreeType", &fields );
    if(mF->defined)
      {
      strcpy( tubeTreeType, (char *)(mF->value) );
      }

    char tubeColor[80];
    strcpy( tubeColor, "" );
    mF = MET_GetFieldRecord( "Color", &fields );
    if(mF->defined)
      {
      strcpy( tubeColor, (char *)(mF->value) );
      }

    char tubePointDim[80];
    strcpy( tubePointDim, "" );
    mF = MET_GetFieldRecord( "PointDim", &fields );
    if(mF->defined)
      {
      strcpy( tubePointDim, (char *)(mF->value) );
      }

    unsigned int nPoints = 0;
    mF = MET_GetFieldRecord( "NPoints", &fields );
    if(mF->defined)
      {
      nPoints = (unsigned int)( mF->value[0] );
      }

    typename TubeType::Pointer tube = TubeType::New();

    for( unsigned int j=0; j<nPoints; ++j )
      {
      typename TubeType::TubePointType pnt;

      typename TubeType::TubePointType::PointType x;
      for( unsigned int d=0; d<TDimension; ++d )
        {
        tmpReadStream >> x[d];
        tmpReadStream.get();
        }
      pnt.SetPosition( x );

      double r;
      tmpReadStream >> r;
      pnt.SetRadius( r );

      tube->GetPoints().push_back( pnt );
      }

    char c = ' ';
    while( c != '\n' && !tmpReadStream.eof() )
      {
      c = tmpReadStream.get();// to avoid unrecognize charactere
      }

    tube->SetSpacing( voxelSize );
    tube->SetId( tubeId );
    tube->ComputeTangentAndNormals();

    m_TubeGroup->AddSpatialObject( tube );
    }

  tmpReadStream.close();

  return true;
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Write( const std::string & _fileName )
{
  typedef typename TubeType::PointListType  PointListType;

  std::ofstream tmpWriteStream( _fileName.c_str(), std::ios::binary |
    std::ios::out);

  tmpWriteStream << "NDims: " << TDimension << std::endl;
  tmpWriteStream << "Dimensions: ";
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    tmpWriteStream << this->m_Dimensions[i];
    if ( i != TDimension - 1 )
      {
      tmpWriteStream << " ";
      }
    }
  tmpWriteStream << std::endl;

  char soType[80];
  sprintf( soType, "Tube" );
  typename TubeType::ChildrenListType * tubeList =
    m_TubeGroup->GetChildren( 99999, soType );
  tmpWriteStream << "VoxelSize:";
  for( unsigned int i=0; i<TDimension; ++i )
    {
    tmpWriteStream << " " << ( *(tubeList->begin()) )->GetSpacing()[i];
    }
  tmpWriteStream << std::endl;

  unsigned int nObjects = tubeList->size();
  tmpWriteStream << "NObjects: " << nObjects << std::endl;

  tmpWriteStream << "End Header:" << std::endl << std::endl;

  typename TubeType::ChildrenListType::iterator tIt = tubeList->begin();
  typename TubeType::ChildrenListType::iterator tEnd = tubeList->end();
  while( tIt != tEnd )
    {
    typename TubeType::Pointer tube = ((TubeType *)(tIt->GetPointer()));

    tmpWriteStream << "ID: " << tube->GetId() << std::endl;
    tmpWriteStream << "Type: Tube" << std::endl;
    tmpWriteStream << "Anat: artery" << std::endl;
    tmpWriteStream << "TreeType: orphan" << std::endl;
    tmpWriteStream << "Color: 1 0.3 0.21" << std::endl;
    tmpWriteStream << "PointDim: 4 x y z r" << std::endl;
    unsigned int nPoints = tube ->GetNumberOfPoints();
    tmpWriteStream << "NPoints: " << nPoints << std::endl;
    tmpWriteStream << "Points:" << std::endl;
    for( unsigned int i=0; i<nPoints; ++i )
      {
      typedef const typename TubeType::TubePointType  TubePointType;
      TubePointType * pnt;
      pnt = static_cast< TubePointType * >( tube->GetPoint( i ) );
      for( unsigned int k=0; k<TDimension; ++k )
        {
        tmpWriteStream << pnt->GetPosition()[k] << " ";
        }
      tmpWriteStream << pnt->GetRadius() << std::endl;
      }
    tmpWriteStream << std::endl;

    ++tIt;
    }
  tmpWriteStream.close();

  return true;
}

template< unsigned int TDimension >
void
TubeXIO< TDimension >
::SetTubeGroup( TubeGroupType * _tubes )
{
  m_TubeGroup = _tubes;
}

template< unsigned int TDimension >
typename GroupSpatialObject< TDimension >::Pointer &
TubeXIO< TDimension >
::GetTubeGroup( void )
{
  return m_TubeGroup;
}

}; // tube namespace

}; // itk namespace

#endif

<commit_msg>BUG: Did not read entire line for each point.<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

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.

=========================================================================*/

#ifndef __itktubeTubeXIO_hxx
#define __itktubeTubeXIO_hxx

#include "itktubeTubeXIO.h"

#include "metaUtils.h"

namespace itk
{

namespace tube
{

template< unsigned int TDimension >
TubeXIO< TDimension >
::TubeXIO()
{
  m_TubeGroup = TubeGroupType::New();
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    m_Dimensions[i] = 1;
    }
}

template< unsigned int TDimension >
TubeXIO< TDimension >
::~TubeXIO( void )
{
}

//
template< unsigned int TDimension >
void
TubeXIO< TDimension >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  if( this->m_TubeGroup.IsNotNull() )
    {
    os << indent << "Tube Group = " << this->m_TubeGroup << std::endl;
    }
  else
    {
    os << indent << "Tube Group = NULL" << std::endl;
    }
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Read( const std::string & _fileName )
{
  std::vector< MET_FieldRecordType * > fields;

  MET_FieldRecordType * mF;

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NDims", MET_INT, false);
  fields.push_back(mF);
  int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Dimensions", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "VoxelSize", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NObjects", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "End Header", MET_NONE, false);
  mF->terminateRead = true;
  fields.push_back(mF);

  std::ifstream tmpReadStream( _fileName.c_str(), std::ios::binary |
    std::ios::in );

  if( !tmpReadStream.rdbuf()->is_open() )
    {
    return false;
    }

  std::vector< MET_FieldRecordType * > extraFields;
  if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
    {
    std::cerr << "Tube: Read failed" << std::endl;
    return false;
    }

  mF = MET_GetFieldRecord( "NDims", &fields );
  if( mF->defined )
    {
    int nDims = (int)mF->value[0];

    if( (int)mF->value[0] != TDimension )
      {
      std::cerr << "Tube: Read failed: object is " << nDims
        << " dimensional and was expecting " << TDimension << " dimensional."
        << std::endl;
      return false;
      }
    }

  mF = MET_GetFieldRecord( "Dimensions", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      this->m_Dimensions[i] = (int)( mF->value[i] );
      }
    }

  double voxelSize[ TDimension ];
  mF = MET_GetFieldRecord( "VoxelSize", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      voxelSize[i] = (float)( mF->value[i] );
      }
    }

  int nObjects = 0;
  mF = MET_GetFieldRecord( "NObjects", &fields );
  if(mF->defined)
    {
    nObjects = (int)mF->value[0];
    }

  fields.clear();

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ID", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Type", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Anat", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "TreeType", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Color", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  fields.push_back(mF);

  for( int obj = 0; obj < nObjects; ++obj )
    {
    if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
      {
      std::cerr << "Tube: Read failed" << std::endl;
      return false;
      }

    int tubeId = 0;
    mF = MET_GetFieldRecord( "ID", &fields );
    if(mF->defined)
      {
      tubeId = (int)( mF->value[0] );
      }

    char tubeType[80];
    strcpy( tubeType, "" );
    mF = MET_GetFieldRecord( "Type", &fields );
    if(mF->defined)
      {
      strcpy( tubeType, (char *)(mF->value) );
      }

    char tubeAnat[80];
    strcpy( tubeAnat, "" );
    mF = MET_GetFieldRecord( "Anat", &fields );
    if(mF->defined)
      {
      strcpy( tubeAnat, (char *)(mF->value) );
      }

    char tubeTreeType[80];
    strcpy( tubeTreeType, "" );
    mF = MET_GetFieldRecord( "TreeType", &fields );
    if(mF->defined)
      {
      strcpy( tubeTreeType, (char *)(mF->value) );
      }

    char tubeColor[80];
    strcpy( tubeColor, "" );
    mF = MET_GetFieldRecord( "Color", &fields );
    if(mF->defined)
      {
      strcpy( tubeColor, (char *)(mF->value) );
      }

    char tubePointDim[80];
    strcpy( tubePointDim, "" );
    mF = MET_GetFieldRecord( "PointDim", &fields );
    if(mF->defined)
      {
      strcpy( tubePointDim, (char *)(mF->value) );
      }

    unsigned int nPoints = 0;
    mF = MET_GetFieldRecord( "NPoints", &fields );
    if(mF->defined)
      {
      nPoints = (unsigned int)( mF->value[0] );
      }

    typename TubeType::Pointer tube = TubeType::New();

    for( unsigned int j=0; j<nPoints; ++j )
      {
      typename TubeType::TubePointType pnt;

      typename TubeType::TubePointType::PointType x;
      for( unsigned int d=0; d<TDimension; ++d )
        {
        tmpReadStream >> x[d];
        tmpReadStream.get();
        }
      pnt.SetPosition( x );

      double r;
      tmpReadStream >> r;
      pnt.SetRadius( r );

      tube->GetPoints().push_back( pnt );

      char c = ' ';
      while( c != '\n' && !tmpReadStream.eof() )
        {
        c = tmpReadStream.get();// to avoid unrecognize charactere
        }
      }

    tube->SetSpacing( voxelSize );
    tube->SetId( tubeId );
    tube->ComputeTangentAndNormals();

    m_TubeGroup->AddSpatialObject( tube );
    }

  tmpReadStream.close();

  return true;
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Write( const std::string & _fileName )
{
  typedef typename TubeType::PointListType  PointListType;

  std::ofstream tmpWriteStream( _fileName.c_str(), std::ios::binary |
    std::ios::out);

  tmpWriteStream << "NDims: " << TDimension << std::endl;
  tmpWriteStream << "Dimensions: ";
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    tmpWriteStream << this->m_Dimensions[i];
    if ( i != TDimension - 1 )
      {
      tmpWriteStream << " ";
      }
    }
  tmpWriteStream << std::endl;

  char soType[80];
  sprintf( soType, "Tube" );
  typename TubeType::ChildrenListType * tubeList =
    m_TubeGroup->GetChildren( 99999, soType );
  tmpWriteStream << "VoxelSize:";
  for( unsigned int i=0; i<TDimension; ++i )
    {
    tmpWriteStream << " " << ( *(tubeList->begin()) )->GetSpacing()[i];
    }
  tmpWriteStream << std::endl;

  unsigned int nObjects = tubeList->size();
  tmpWriteStream << "NObjects: " << nObjects << std::endl;

  tmpWriteStream << "End Header:" << std::endl << std::endl;

  typename TubeType::ChildrenListType::iterator tIt = tubeList->begin();
  typename TubeType::ChildrenListType::iterator tEnd = tubeList->end();
  while( tIt != tEnd )
    {
    typename TubeType::Pointer tube = ((TubeType *)(tIt->GetPointer()));

    tmpWriteStream << "ID: " << tube->GetId() << std::endl;
    tmpWriteStream << "Type: Tube" << std::endl;
    tmpWriteStream << "Anat: artery" << std::endl;
    tmpWriteStream << "TreeType: orphan" << std::endl;
    tmpWriteStream << "Color: 1 0.3 0.21" << std::endl;
    tmpWriteStream << "PointDim: 4 x y z r" << std::endl;
    unsigned int nPoints = tube ->GetNumberOfPoints();
    tmpWriteStream << "NPoints: " << nPoints << std::endl;
    tmpWriteStream << "Points:" << std::endl;
    for( unsigned int i=0; i<nPoints; ++i )
      {
      typedef const typename TubeType::TubePointType  TubePointType;
      TubePointType * pnt;
      pnt = static_cast< TubePointType * >( tube->GetPoint( i ) );
      for( unsigned int k=0; k<TDimension; ++k )
        {
        tmpWriteStream << pnt->GetPosition()[k] << " ";
        }
      tmpWriteStream << pnt->GetRadius() << std::endl;
      }
    tmpWriteStream << std::endl;

    ++tIt;
    }
  tmpWriteStream.close();

  return true;
}

template< unsigned int TDimension >
void
TubeXIO< TDimension >
::SetTubeGroup( TubeGroupType * _tubes )
{
  m_TubeGroup = _tubes;
}

template< unsigned int TDimension >
typename GroupSpatialObject< TDimension >::Pointer &
TubeXIO< TDimension >
::GetTubeGroup( void )
{
  return m_TubeGroup;
}

} // tube namespace

} // itk namespace

#endif
<|endoftext|>